[英]How to stop JTable TableModelListener from firing or listening when specific column on table changed
我创建了一个TableModelListener
,它侦听特定的列。 具体来说,第2、3、4、5列。 这样,当2-5中的任何列都具有值或not null
,它将采用并将值存储的值添加到BigDecimal
值中以获得总和 。 之后,我需要将第6列的值设置为第2-5列的值之和。 所以我认为我可以简单地收集值,然后如果遇到第6列,它将设置总和。
这是代码。
@Override
public void tableChanged(TableModelEvent e) {
DefaultTableModel tableModel = (DefaultTableModel) e.getSource();
if (tableModel.getRowCount() > 0) {
for (int row = 0; row < tableModel.getRowCount(); row++) {
BigDecimal sum = new BigDecimal(BigInteger.ZERO).setScale(2,RoundingMode.HALF_UP);
for (int col = 0; col < tableModel.getColumnCount(); col++) {
if (col == 2 || col == 3 || col == 4 || col == 5) {
if (tableModel.getValueAt(row, col) != null) {
sum = sum.add(new BigDecimal(Double.parseDouble(tableModel.getValueAt(row, col).toString())));
}
}
}
JOptionPane.showMessageDialog(null,"Sum: "+sum);
tableModel.setValueAt(sum, row, 6);
}
}
}
所以发生了什么事,我得到了一个带有sum值的无限JOptionPane Dialog
。 我在网上进行了研究,认为在编辑后,可以通过添加view.getMyJTable().putClientProperty("terminateEditOnFocusLost", true);
来终止侦听器view.getMyJTable().putClientProperty("terminateEditOnFocusLost", true);
没有帮助。 我基本上只是想能够获得第2-5列的总和,无论这些列是否具有值,这就是为什么我将BigDecimal
初始化为ZERO
似乎在第6列上正在监听表模型更改。 我不知道如何选择tablechanged
将应用的特定列。
谢谢。
我已经解决了我的问题。 抱歉问这个。 解决方案很简单。 我做了一些研究,发现了一种名为e.getColumn()
的方法。
无论如何,感谢您查看我的问题。
@Override
public void tableChanged(TableModelEvent e) {
int colChanged = e.getColumn();
if (colChanged == 2|| colChanged == 3 || colChanged == 4 || colChanged == 5) {
DefaultTableModel tableModel = (DefaultTableModel) e.getSource();
if (tableModel.getRowCount() > 0) {
for (int row = 0; row < tableModel.getRowCount(); row++) {
BigDecimal sum = new BigDecimal(BigInteger.ZERO).setScale(2, RoundingMode.HALF_UP);
for (int col = 0; col < tableModel.getColumnCount(); col++) {
if (col == 2 || col == 3 || col == 4 || col == 5) {
if (tableModel.getValueAt(row, col) != null) {
sum = sum.add(new BigDecimal(Double.parseDouble(tableModel.getValueAt(row, col).toString())));
}
}
}
JOptionPane.showMessageDialog(null, "Sum: " + sum);
tableModel.setValueAt(sum, row, 6);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.