How to select the last inserted row in a JTable?

一世执手 提交于 2019-12-20 02:13:57

问题


I have a JTable with two columns and a table model that uses a class which works with a hash map. 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 (e.g. "A", "B", "C" and not even then since "D", for example, is placed ahead of A once added). Could someone tell me how to solve this problem?


回答1:


The problem is most likely in your TableModel, since the code you posted is just fine. You mention you use a HashMap for storing the data of your TableModel. Problem with a HashMap is that it hasn't any ordering. 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.




回答2:


better could be to use prepareRendered for hightlighting max row index from XxxTableModel

JTable could be Sorted and Filtered too, then last added row couldn't be visible in JTables view

depends of ListSelectionMode, but by default you can do

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



来源:https://stackoverflow.com/questions/14155429/how-to-select-the-last-inserted-row-in-a-jtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!