jTable行数VS模型行数 [英] jTable row count VS model row count

查看:122
本文介绍了jTable行数VS模型行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jTable,它从数据库查询中加载数据 此加载产生32个结果,因此TableModel中有32行 使用myTable.getRowCount()我可以正确获得32

I have a jTable which loads data from a DB query This load produces 32 results, thus 32 rows in the TableModel With myTable.getRowCount() i correctly get 32

然后我创建一个新的空模型并将其加载到表中 在那之后,如果我拨打myTable.getRowCount()我仍然得到32 但是,如果我调用myModel.getRowCount(),我会正确得到0!

Then i create a new empty model and load it into the table After that, if i call myTable.getRowCount() i still get 32 But if i call myModel.getRowCount() i correctly get 0!

如果我的表正在使用模型,为什么table.getRowCount()和model.getRowCount()之间应该有区别?

Why there should be difference between table.getRowCount() and model.getRowCount() if my table is using the model?

...
System.out.println(myTable.getRowCount());  // 32


String[] columnNames= {null};
DefaultTableModel emptyModel= new DefaultTableModel(null, columnNames);
emptyModel.setRowCount(0);
myTable.setModel(emptyModel);

System.out.println(myTable.getRowCount());  // still 32, expecting 0
System.out.println(emptyModel.getRowCount());  // 0 as expected

推荐答案

在使用自定义RowSorter(或与此相关的任何RowSorter)时,必须注意确保分类器和表格的模型始终匹配.如setRowSorter Javadoc中所述:

When using a custom RowSorter (or any RowSorter for that matter), one must take care to make sure the models of the sorter and the table always match. As specified in the setRowSorter Javadoc:

如果RowSorter的基础模型与此JTable的基础模型不同,则将导致未定义的行为.

If the underlying model of the RowSorter differs from that of this JTable undefined behavior will result.

除非您使用默认的自动排序器(通过设置autoCreateRowSorter标志),否则JTable的setModel方法将不会更新行排序器.

The setModel method of the JTable will not update the row sorter, unless you are using a default automatic one (by setting the autoCreateRowSorter flag).

因此,您应该

  • 保留对您的分类器的引用并更新其模型
    OR
  • 通过在表上设置setAutoCreateRowSorter(true)而不是自定义表,来使用默认的行排序器,
  • keep a reference to your sorter and update its model as well
    OR
  • use the default row sorter by setting setAutoCreateRowSorter(true) on your table and not a custom one,

这篇关于jTable行数VS模型行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆