微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

计算 JTable 中具有特定值的行

如何解决计算 JTable 中具有特定值的行

enter image description here

所以我想弄清楚如何计算表格中具有特定值的行并将其显示标签中,例如,我想计算一本书软装订的所有行。

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     // count total of books that is softbound
      for(int i =0; i<jTable2.getRowCount(); i++){
      if(jTable2.getValueAt(i,6) == "SoftBound")
          {
             //val = Integer.valueOf(jTable2.getValueAt(i,6).toString());
              int numrow = jTable2.getRowCount();
              jLabel11.setText(Integer.toString(numrow));
          }

      }  
     
 }

解决方法

您错误地比较了 String,请参阅 How do I compare Strings in Java?。此外,您当前用于计算行数的逻辑有问题。

目前您并没有仅使用“软绑定”来缩小行的范围。如果“Softbound”与检索到的值匹配,您仍将显示完整的行数。

要修复您的逻辑,您需要创建某种计数器,像您一样循环遍历行,正确比较值(使用 equals 或 equalsIgnoreCase),在每个找到的行上增加计数器,然后在循环后所有行,显示找到的金额。

工作示例可以修复您使用的方法:

public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> buildGui());
}

private static void buildGui() {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    String[] header = { "ISBN","Title","Type" };
    Object[][] data = { { 1111,"Title1","Softbound" },{ 2222,"Title2",{ 3333,"Title3","Hardbound" } };

    JTable table = new JTable(data,header);
    JLabel label = new JLabel("Found result:");
    JLabel labelAmount = new JLabel();

    JComboBox<String> comboBox = new JComboBox<>(new String[] { "Hardbound","Softbound" });

    JScrollPane scrollPane = new JScrollPane(table);
    JButton btn = new JButton("Get amount");
    btn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int amount = 0;
            for (int i = 0; i < table.getRowCount(); i++) {
                if (table.getValueAt(i,2).equals(comboBox.getSelectedItem())) {
                    amount++;
                }
            }
            labelAmount.setText("" + amount);
        }
    });

    frame.add(scrollPane,BorderLayout.CENTER);
    panel.add(comboBox);
    panel.add(btn);
    panel.add(label);
    panel.add(labelAmount);
    frame.add(panel,BorderLayout.SOUTH);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

结果

enter image description here

旁注

如果您想修改 JTable 中显示的值,尤其是通过排序和过滤,可以使用教程 How to use Tables - Sorting and Filtering 中所示的一些有用工具来完成。仔细查看 TableFilterDemoRowFilter

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?