我拼命试图说服我的JTable在更改其数据时刷新.数据存储在我正在使用的全局单例TreeSet中.每当更改TreeSets数据时,都会触发一个事件以刷新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();
}
}
任何帮助,将不胜感激!
[EDIT1]
我越来越接近核心问题:
我发现JFrame中显示的表包含另一个引用作为我要更改的引用.我使所有更改可见,并将它们应用于模型.
解决方法:
您的代码中缺少什么吗?不应编译您的表模型,因为它缺少JTable用来访问数据的所有方法(getColumnCount(),getValueAt()等).
另外,您不必每次更改都创建一个新模型-只需使用模型fireTableStructureChanged().
标签:swing,jtable,java
来源: https://codeday.me/bug/20191201/2080173.html