如何解决计算 JTable 中具有特定值的行
所以我想弄清楚如何计算表格中具有特定值的行并将其显示在标签中,例如,我想计算一本书软装订的所有行。
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);
}
结果:
旁注:
如果您想修改 JTable
中显示的值,尤其是通过排序和过滤,可以使用教程 How to use Tables - Sorting and Filtering 中所示的一些有用工具来完成。仔细查看 TableFilterDemo
和 RowFilter
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。