对 JTable 进行排序后,JTable 和 DefaultTableModel 的行索引失去同步
爪哇 NETBEANS
// resultsTable, myModel
JTable resultsTable;
DefaultTableModel myModel; //javax.swing.table.DefaultTableModel
myModel = (DefaultTableModel) resultsTable.getModel();
// event of clicking on item of table
String value = (String) myModel.getValueAt(resultsTable.getSelectedRow(), columnIndex)
我使用 JTable 和 DefaultTableModel 来查看各种信息的表格 我想获取表中选定索引的某一列的值。
我上面写的代码工作正常,除了以下情况: 我使用GUI的排序(点击表格上我想要排序的字段名称) 该表已正确排序,但之后当我选择一行时,它会出现 排序之前存在的行的值。 这意味着排序后(使用 JTable 的 GUI) “myModel”和“resultsTable”对象具有不同的行索引。
我如何同步这两个?
JAVA
NETBEANS
// resultsTable, myModel
JTable resultsTable;
DefaultTableModel myModel; //javax.swing.table.DefaultTableModel
myModel = (DefaultTableModel) resultsTable.getModel();
// event of clicking on item of table
String value = (String) myModel.getValueAt(resultsTable.getSelectedRow(), columnIndex)
I use JTable and DefaultTableModel to view a table of various info
and I want to get a value of a certain column of the selected index of the table.
The code I wrote above works fine except when:
I use the sort of the GUI (click on the field name I want to sort on the table)
The table is properly sorted but after that when I select a row, it gets
the value of the row that was there before the sort.
This means that after sorting (using the JTable's GUI)
the 'myModel' and 'resultsTable' objects have different row indexes.
How do I synchronize those two?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在 JTable 查看 JavaDoc
You need to use the 'convertXXX' methods on the JTable see the JavaDoc
使用
JTable.getValueAt()
的一个问题是获取所需的列。当列在 GUI 中移动时,索引会“更改”以匹配视图。通过使用AbstractTableModel.getValueAt()
和JTable.convertXXX()
(如 Guillaume 概述),只需在检索数据时使用模型的列索引即可。A problem with using the
JTable.getValueAt()
is to get the column you want. When the columns are moved around in the GUI the indexes "change" to match the view. By using theAbstractTableModel.getValueAt()
and theJTable.convertXXX()
(as outlined by Guillaume) it's just a matter of using the column indexes for the model when retrieving data.除了纪尧姆给出的解决方案(谢谢)
我这样做了:
我使用 resultsTable 对象而不是 myModel 对象来获取值。
Except from the solution Guillaume gave (Thanks)
I did this:
I used the resultsTable Object instead of the myModel Object to get the value.