有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么不像我预期的那样重新验证()和重新绘制()工作?

我希望一旦选择了combobox,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);
……

现在,当我在combobox中选择项时,JTable没有改变。为什么?


共 (1) 个答案

  1. # 1 楼答案

    您的错误是一个基本的核心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

    为了实现您的目标,您需要更改显示的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);