我想知道当用于最初填充它的Object[][]
发生变化时是否可以刷新表的GUI。
Object[][] calculationsTableData;
public Interface() {
...
analysisPanel.add(calculationsTable());
...
}
JScrollPane calculationsTable() {
populateCalculationsTableData();
...
calculationsTable = new JTable(calculationsTableData, calculationsColumnNames);
...
}
void populateCalculationsTableData(){
Object[][] temp = new Object[x.numsSize][7];
for (int i = 0; i < x.numsSize; i++) {
temp[i][0] = df.format(x.nums[i]);
...
}
calculationsTableData = temp;
}
当x对象更改为重新填充populateCalculationsTableData()
时,将调用 calculationsTableData
repaint()
和revalidate()
方法在这种情况下似乎没有效果,fireTableDataChanged()
也没有效果,因为这不是表模型。
答案 0 :(得分:2)
我会创建自己的表模型来包装对象数组,并暴露fireTableDataChanged()方法:
private static class ObjectArrayModel extends AbstractTableModel {
private final Object[][] rowData;
private final Object[] columnNames;
private ObjectArrayModel(Object[][] rowData, Object[] columnNames) {
this.rowData = rowData;
this.columnNames = columnNames;
}
@Override
public void fireTableDataChanged() {
super.fireTableDataChanged();
}
public String getColumnName(int column) {
this.fireTableDataChanged();
return columnNames[column].toString();
}
public int getRowCount() {
return rowData.length;
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int row, int col) { return rowData[row][col]; }
public boolean isCellEditable(int row, int column) { return true; }
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
}
...当数据发生变化时,您应该可以在此处调用fireTableDataChanged(),它将通知需要重绘的表。
答案 1 :(得分:2)
默认情况下JTable会创建 AbstractTableModel [ 1 ] 实施的新实例如果没有明确设置表模型。如果需要更新表,则必须使用其模型。DefaultTableModel
设置新的DefaultTableModel:
void populateCalculationsTableData() {
...
calculationsTableData = temp;
TableModel model = new DefaultTableModel(calculationsTableData, calculationsColumnNames);
calculationsTable.setModel(model);
}
使用DefaultTableModel
:
TableModel model = new DefaultTableModel(calculationsTableData, calculationsColumnNames);
calculationsTable = new JTable(model);
将表格模型转换为DefaultTableModel
,并将其数据和列设置为:
void populateCalculationsTableData() {
...
calculationsTableData = temp;
DefaultTableModel model = (DefaultTableModel)calculationsTable.getModel();
model.setDataVector(calculationsTableData, calculationsColumnNames);
}
[ 1 ] :检查JTable(Object[][] rowData, Object[] columnNames)
源代码后,我意识到没有创建DefaultTableModel
但是新的匿名内部从AbstractTableModel
延伸而来的课程。