栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用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 JScrollPaneframe.validate();

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

但是,您已经在框架中添加了

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

更新表数据的正确方法是对其

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

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

@Overridepublic void actionPerformed(ActionEvent e) {    if (e.getSource() == this.combobox) {        JComboBox<String> combobox = this.combobox;        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    }    ...

更新1:
新代码的问题已解决了更新模型中数据的方式。但是,更新

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

更新2:
似乎您错过了重点。在这里,如何更新模型很重要。该表将显示您的模型拥有的所有数据。如果您仅更新2行,但保留第3行不变,则该表将显示3行(新2行和旧1行)。由于每次都需要更改所有数据,因此需要
完全替换模型中的数据
。每次都需要重新创建您的数据,而不是表。请参阅更新代码示例。我添加了

actionPerformed()
使用您当前的源代码重新初始化数据的方法。请阅读内联注释。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610320.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号