我希望一旦选择了组合框,JTable 就会改变。
这是我的部分代码:
……
chooseAccoutingItemComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeTable();
jScrollpane.revalidate();
jScrollpane. repaint();
}
private void changeTable() {
JTable accountTable2 = new JTable(accountBook.getRowData(startYear, startMonth, endYear, endMonth, (AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()), accountBook.getColumnNames());
accountTable = accountTable2;
}
});
accountTable = new JTable(accountBook.getRowData(startYear, startMonth, endYear, endMonth, accountintItem), accountBook.getColumnNames());
jScrollpane = new JScrollPane(accountTable);
add(jScrollpane, BorderLayout.CENTER);
……
现在,当我在组合框中选择项目时,JTable 没有改变。为什么?
最佳答案
你的是一个基本的核心 Java 错误,与 Swing、重新验证或重新绘制无关,而与 Java 引用变量和引用(或对象):
Changing the object referenced by a variable will have no effect on the original object. For example, your original displayed JTable object, the one initially referenced by the accountTable variable is completely unchanged by your changing the reference that the accountTable variable holds, and for this reason your GUI will not change. Again understand that it's not the variable that's displayed, but rather the object
为了实现您的目标,您需要更改displayed JTable 的状态。通过改变它的模型来做到这一点。
即,通过做类似的事情:
private void changeTable() {
// create a new table model
MyTableModel newModel = new MyTableModel(pertinentParameters);
// use the new model to set the model of the displayed JTable
accountTable.setModel(newModel);
}
使用您当前传递给新 JTable 的参数:
accountBook.getRowData(startYear, startMonth, endYear, endMonth,
(AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()),
accountBook.getColumnNames()
改为创建新的 TableModel。
事实上,您甚至可以直接使用这些数据创建一个 DefaultTableModel,例如:
DefaultTableModel model = new DefaultTableModel(accountBook.getRowData(
startYear, startMonth, endYear, endMonth,
(AccountingItem) chooseAccoutingItemComboBox.getSelectedItem()),
accountBook.getColumnNames());
accountTable.setModel(model);
关于java - 为什么 revalidate() 和 repaint() 不像我预期的那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35168106/