为什么 revalidate() 和 repaint() 不像我预期的那样工作?

Why don't revalidate() & repaint() work like I expect?

我希望一旦选择了组合框,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、revalidate 或 repaint 无关,与 的核心区别有什么区别? 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 的状态。通过更改其 model.

来完成此操作

即,通过执行以下操作:

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);