gpt4 book ai didi

java - jTable 行数 VS 模型行数

转载 作者:行者123 更新时间:2023-12-01 12:59:31 25 4
gpt4 key购买 nike

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

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

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

...
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 中指定的:

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

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

因此,您应该

  • 保留对您的分拣机的引用并更新其模型
  • 通过在表格上设置 setAutoCreateRowSorter(true) 来使用默认行排序器,而不是自定义排序器,

关于java - jTable 行数 VS 模型行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23626951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com