您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用JComboBox更改/更新JTable内容(类别)

使用JComboBox更改/更新JTable内容(类别)

代码有问题,因为每次actionPerformed()调用时,您正在创建一个新组件:

table = new JTable(new TestTableModel(data, header));
frame.add(new JScrollPane( table ));  // <-- BTW: here you need to put the table otherwise you are adding an empty JScrollPane
frame.validate();

(注意:还有一个错误,@mKorbel提到了)。

但是,您已经在框架中添加JScrollPane带有的JTable,并且这些继续存在。(如果您尝试调整窗口大小,则会在旧表下方看到新表)。

更新表数据的正确方法是对其TableModel进行 模型中 所需的任何修改,然后根据您所做的更改,触发适当的fireXXX()方法通知表重新绘制自身。

作为一个粗略的示例,您的代码将是:

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == this.combo@R_419_2419@) {
        JCombo@R_419_2419@<String> combo@R_419_2419@ = this.combo@R_419_2419@;

        newdata.clear();    // Clear your list or create a new one otherwise data will keep piling up.  
        newdata.add("Test1");
        newdata.add("Test2");

        TestTableModel model = (TestTableModel) table.getModel();

        // Since you need to replace the whole data create a new Object[][] each time
        Object[][] newModelData = new Object[newdata.size()][3];

        // Set whatever data to the new array
        int i = 0;
        for (String text : newdata) {
            newModelData[i][0] = Boolean.TRUE;
            newModelData[i][1] = text;
            newModelData[i][2] = text;
            i++;
        }

        // replace all data of the current model
        model.setData(newModelData);
    }
}
....

// Now inside your table model:
    ...
    @Override
    public Class<?> getColumnClass(int column) {
    // if (column == 0) {   
    //     return Boolean.class;             // <-- this produces a ClassCastException with the data you aretrying to set
    // }
       return super.getColumnClass(column);
    }

    public void setData(Object[][] data) {
        this.data = data;       //  <-- Update the data
        fireTableDataChanged(); //  <-- fire the event so the table is notified. If you change only one cell you need to call the appropriate fire event
    }
    ...

代码的问题已解决了更新模型中数据的方式。但是,更新data结构时存在逻辑缺陷。此变量以3行的数组开始。在该actionPerformed()方法newdata中,对只有2个条目的list 的长度执行循环。因此,您仅更新模型的前2行。

似乎您错过了重点。在这里,如何更新模型很重要。该表将显示您的模型拥有的所有数据。如果您仅更新2行,但保留第3行不变,则该表将显示3行(新2行和旧1行)。由于每次都需要更改所有数据,因此需要 。每次都需要重新创建您的数据,而不是表。请参阅更新代码示例。我添加actionPerformed()使用您当前的源代码重新初始化数据的方法。请阅读内联注释。

其他 2022/1/1 18:25:27 有543人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶