我的面板上有一个树和一个表,当我单击树节点时,表需要同时更改,但事实并非如此。我在线搜索并阅读Java教程,但没有找到任何解决方案。从某些帖子我认为我需要使用fireTableStruetureChanged()
,但它在我的代码中不起作用。任何人都可以帮我解决这个问题吗?以下是代码。万分感谢!
public class tableStructureChange extends JFrame implements ... {
.....
/ //columnNames is a public variable, because I need to change the columns later
columnNames = new String[] {"col1","col2"}; */
data = new String[][]{
{"Mary", "Campione"},
{"Alison", "Huml"}, };
table = new JTable(new MyTableModel());
table.setAutoCreateColumnsFromModel( false );
feedback = new JScrollPane(table); //feedback is the bottom panel
...
}
//the following class is the problem, i need the table to be reloaded
//when the class is called, but the table doesn't change at all
public void displayFeedback(String tempString) {
//create table for bottom panel
columnNames = new String[] {"col3","col4", "col5"};
String[][] data = new String[][]{
{"Mary", "Campione", "us"},
{"Alison", "Huml", "canada"}, };
//table = new JTable(data, columnNames);
//fireTableStructureChanged(); //this is the problem part
}
//我的桌子模型 class MyTableModel扩展AbstractTableModel { String [] columnNames = new String [] {“col1”,“col2”};
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];
}
}
... }
答案 0 :(得分:3)
在您的方法displayFeedback
中,您似乎希望替换JTable对象并更改显示以反映上面JTree
中选择的内容。您应该专注于更新模型,而不是替换视图对象中的内容,在这种情况下,您应该创建已创建的AbstractTableModel
子类。有几种方法可以做到这一点,但是对于蛮力的概念证明,你可以做类似以下的事情:
MyTableModel
添加构造函数,该构造函数采用二维数组data
MyTableModel
实例,其中包含与所选树节点相关的新数据。setModel
变量上调用table
。