Reputation: 153
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?
Upvotes: 3
Views: 5206
Reputation: 36611
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.
Upvotes: 4
Reputation: 109813
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
Upvotes: 2