简体   繁体   English

如何选择JTable中最后插入的行?

[英]How to select the last inserted row in a JTable?

I have a JTable with two columns and a table model that uses a class which works with a hash map. 我有一个带有两列的JTable和一个使用一个与哈希映射一起工作的类的表模型。 The elements of this map are the table rows. 此映射的元素是表行。

Every time I add a new element I need the element to be selected, regardless of any sorting. 每次添加新元素时,我都需要选择元素,而不管任何排序。 Now, I've tried using the following method: 现在,我尝试使用以下方法:

int lastRow = table.convertRowIndexToView(tableModel.getRowCount() - 1);
table.setRowSelectionInterval(lastRow, lastRow);

The problem is, this works only when I'm adding data in a sorted fashion (eg "A", "B", "C" and not even then since "D", for example, is placed ahead of A once added). 问题是,这只适用于我以排序的方式添加数据(例如“A”,“B”,“C”而不是那时,因为“D”,例如,一旦添加就放在A之前) 。 Could someone tell me how to solve this problem? 有人能告诉我如何解决这个问题吗?

The problem is most likely in your TableModel , since the code you posted is just fine. 问题很可能在你的TableModel ,因为你发布的代码很好。 You mention you use a HashMap for storing the data of your TableModel . 您提到使用HashMap存储TableModel的数据。 Problem with a HashMap is that it hasn't any ordering. HashMap问题在于它没有任何排序。 Adding an element to it might alter the order in which you get the elements in the map. 向其添加元素可能会改变您在地图中获取元素的顺序。

Better to use a data structure which respects the ordering. 最好使用尊重订购的数据结构。

better could be to use prepareRendered for hightlighting max row index from XxxTableModel 更好的方法是使用prepareRendered从XxxTableModel高亮显示最大行索引

JTable could be Sorted and Filtered too, then last added row couldn't be visible in JTables view JTable也可以进行Sorted and Filtered ,然后在JTables视图中无法看到最后添加的行

depends of ListSelectionMode , but by default you can do 取决于ListSelectionMode ,但默认情况下你可以这样做

table.setRowSelectionInterval(lastRow, lastRow);
table.setColumnSelectionInterval(columnMinIndex, columnMaxIndex);

for better help sooner post an SSCCE, short, runnable, compilable, just about JFrame , JTable in JScrollPane and a new addRow fired from swing.Timer 为更好地帮助越早张贴SSCCE,短,可运行,编译,只是JFrameJTable in JScrollPane和新的addRow烧制而成swing.Timer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM