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

标签 java swing jtable actionlistener repaint

我希望一旦选择了组合框,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/

相关文章:

java - 如何在 JTable 渲染器上获得完全突出显示(带边框)

java - 监听器需要什么来检测 JTable 单元格是否已被双击并因此切换到编辑模式?

java - 扩展 Abstract Visualizer 时遇到困难 : getting ClassCastException

java - 无法在具有等待和通知的多线程环境中从套接字输入流读取

java - 关于 Swing 图像格式和服务提供商

java - JTable 中第一个不必要的空行。如何去除它?

java - 在具有不同适配器的单个 ListView 中添加两个列表

java - 无法在 Windows 中获取 Java 版本

java - Swing 是否支持 Windows 7 风格的文件选择器?

java - 如何从 JFileChooser(JAVA Swing) 禁用文件操作、文件选择和过滤面板?