当我更改数据时,我拼命试图说服我JTable
刷新。数据存储在TreeSet
我正在使用的全局单例中。每当TreeSet
更改 s 数据时,都会触发一个事件以刷新TableModel
. 出于测试目的,我将其替换为简单的Timer
触发事件。
每次触发事件时,都会从TreeSet
中删除一个元素以模拟数据的变化。该事件触发并且TableClass
接收它并按预期处理它,但是在刷新时没有任何反应。TableModel
每次发生事件时,我都尝试创建一个新的并将其设置为全局表。对单例TreeSet
进行了更改,但JTable
.
public class TreeTableObj implements ActionListener{
public JTable table ;
public TreeTableObj(){
MyTableModel myModel = new MyTableModel(getValuesOfTreeSet(), getTreeSetRows());
table = new JTable( myModel){ //some rendering };
table.setAutoCreateRowSorter(true);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames;
private Object[][] data ;
public MyTableModel(Object[][] data, String[] columnNames){
this.data = data;
this.columnNames = columnNames;
System.out.println("Model created");
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public void setData(Object[][] data){
this.data = data;
fireTableDataChanged();
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
if (true) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (true) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
public void refreshTableModel(){
FlightsTreeSet.getInstance().remove(FlightsTreeSet.getInstance().first());
table.setModel(new MyTableModel(getValuesOfTreeSet(), getTreeSetRows()));
}
public void actionPerformed(ActionEvent arg0) {
refreshTableModel();
}
}
任何帮助,将不胜感激!
[编辑1]
我越来越接近问题核心:我发现显示在 JFrame 中的表包含另一个引用作为我更改的那个。我使所有更改可见,它们适用于模型。