我创建了一个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);
}
}
}
所以,我得到了一个无穷大的JOptionPane Dialog
,它的值是和。我在网上进行了研究,认为编辑后可以通过添加view.getMyJTable().putClientProperty("terminateEditOnFocusLost", true);
来终止侦听器。
帮不上忙。基本上,我只想得到列2-5的和,无论列是否有值,这就是我将BigDecimal
初始化为ZERO
的原因。
即使在第6栏,它似乎也在听表模式的变化。我不知道如何选择应用tablechanged
的特定列。
谢谢。
发布于 2018-02-13 12:50:51
我已经解决了我的问题。很抱歉问这个。解决办法很简单。我做了一些研究,发现了一种叫做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);
}
}
}
}
https://stackoverflow.com/questions/48766930
复制相似问题