3

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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nikola Luburic
  • 133
  • 1
  • 3
  • 10

2 Answers2

4

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.

Robin
  • 36,233
  • 5
  • 47
  • 99
  • Yeah, I realized the HashMap was the problem. I fixed the issue by going through my table after adding a new element, comparing the key as I go along and breaking at the spot the key equals a key from the table. That was the row I needed selected and then I simply called the lines above. – Nikola Luburic Jan 04 '13 at 14:09
  • @NikolaLuburic sounds like your model implemenation could be invalid: the sequence of rows shouldn't be changed by an insert. If an insert indeed does change the sequence of existing row, the model must fire a dataChanged (which will loose any selection and pose the problems you have :-). – kleopatra Jun 25 '13 at 09:43
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

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319