So I have two methods method_1 and method_2. Both these methods are identical, just a minor change in for loop. On the event of a button being clicked,method_1 gets executed and I get the data as intended in the JTable, similarly when clicking on the 2nd button, method_2 gets executed and i get the results, however when I hover over the table header, the previous column names shows and on clicking the rows or scrolling , previous data are overwritten.
JScrollPane scrollPane_2;
DefaultTableModel model;
JTable table;
public void method_1(){
String[][] data = new String[10][4];
for(int i=0;i<10;i++)
for(int j=0; j<4; j++)
data[i][j] = "one";
String[] column = { "Column_1", "Column_2", "Column_3", "Column_4"};
model = new DefaultTableModel(data, column);
table = new JTable(model);
scrollPane_2 = new JScrollPane(table);
panel_6.add(scrollPane_2);
panel_6.revalidate();
}
public void method_2(){
String[][] data = new String[8][2];
for(int i=0;i<8;i++)
for(int j=0; j<2; j++)
data[i][j] = "Row_"+i;
String[] column = { "Column_1", "Column_2"};
model = new DefaultTableModel(data, column);
model.fireTableDataChanged();
table = new JTable(model);
scrollPane_2 = new JScrollPane(table);
panel_6.add(scrollPane_2, BorderLayout.CENTER);
panel_6.revalidate();
}
Tried revalidate() and repaint() on scollPane and the panel, also fireTableDataChanged() on the DefaultTableModel without any success
答案 0 :(得分:3)
panel_6.add(scrollPane_2, BorderLayout.CENTER);
向CENTER添加另一个组件不会删除添加到CENTER的先前组件。 Swing默认绘画将按照与添加到容器相反的顺序绘制组件。因此,有效地将两个组件都画上了,但是你会看到最后一个组件被画但是,这可能会导致将事件分派到不同组件导致绘制问题。
不要继续创建新的JTable和JScrollPane组件。
相反,当您想要更改表中的数据时,您需要做的就是更改现有JTable的模型。所以你需要的只是:
table.setModel( theNewModel );
无需触发事件或重新验证()或其他任何内容。