该代码有问题,因为每次actionPerformed()
都调用时,您正在创建一个新组件:
table = new JTable(new TestTableModel(data, header));
frame.add(new JScrollPane( table )); // <-- BTW: here you need to put the table otherwise you are adding an empty JScrollPane
frame.validate();
但是,您已经在框架中添加了JScrollPane
带有的JTable
,并且这些继续存在。(如果您尝试调整窗口大小,则会在旧表下方看到新表)。
更新表数据的正确方法是对其TableModel
进行 模型中 所需的任何修改,然后根据您所做的更改,触发适当的fireXXX()
方法来通知表重新绘制自身。
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.combo@R_419_2419@) {
JCombo@R_419_2419@<String> combo@R_419_2419@ = this.combo@R_419_2419@;
newdata.clear(); // Clear your list or create a new one otherwise data will keep piling up.
newdata.add("Test1");
newdata.add("Test2");
TestTableModel model = (TestTableModel) table.getModel();
// Since you need to replace the whole data create a new Object[][] each time
Object[][] newModelData = new Object[newdata.size()][3];
// Set whatever data to the new array
int i = 0;
for (String text : newdata) {
newModelData[i][0] = Boolean.TRUE;
newModelData[i][1] = text;
newModelData[i][2] = text;
i++;
}
// replace all data of the current model
model.setData(newModelData);
}
}
....
// Now inside your table model:
...
@Override
public Class<?> getColumnClass(int column) {
// if (column == 0) {
// return Boolean.class; // <-- this produces a ClassCastException with the data you aretrying to set
// }
return super.getColumnClass(column);
}
public void setData(Object[][] data) {
this.data = data; // <-- Update the data
fireTableDataChanged(); // <-- fire the event so the table is notified. If you change only one cell you need to call the appropriate fire event
}
...
新代码的问题已解决了更新模型中数据的方式。但是,更新data
结构时存在逻辑缺陷。此变量以3行的数组开始。在该actionPerformed()
方法newdata
中,对只有2个条目的list 的长度执行循环。因此,您仅更新模型的前2行。
似乎您错过了重点。在这里,如何更新模型很重要。该表将显示您的模型拥有的所有数据。如果您仅更新2行,但保留第3行不变,则该表将显示3行(新2行和旧1行)。由于每次都需要更改所有数据,因此需要 。每次都需要重新创建您的数据,而不是表。请参阅更新代码示例。我添加了actionPerformed()
使用您当前的源代码重新初始化数据的方法。请阅读内联注释。