views:

440

answers:

2

I'm using GlazedLists to autogenerate an EventTableModel from an EventList, for use with a JTable in a JScrollbarPane.

I'm using the EventList as a FIFO, a bunch of elements are added to the end, then a bunch of elements are sometimes removed from the beginning. When elements are removed, the selection works exactly as I expect: even though the index of the selection has changed, the same elements are selected (or at least the ones that are still in the table). It's great.

Obviously if the objects change their indices due to deleting items at the beginning, it is impossible to keep the viewport showing a fixed range of objects, and a fixed range of indices. The default behavior seems to be to keep the viewport the same.

If I wanted to keep the selected objects at the same place in the viewport, is there a way I can do that? (e.g. set up an event listener on the EventTableModel or the JScrollbarPane or something, and compute the right scrollbar setting so that when I delete items from the beginning, the viewport moves with the objects?)

+1  A: 

if i call correctly there is a method on JComponent which is used by JViewport which does the actual scrolling when you use the arrowkeys in a Jtable

public void scrollRectToVisible(Rectangle aRect)

this way you wouldn't need to adjust scrollbars, but you specifically can state what rect should be visible. Could include some calculation based on the row number and pixel height of a single row. You could also put a breakpoint in this method, and chech how it works when moving with the arrow keys through a Jtable

Houtman
A: 

Another way to show the first selected row in a JTable that is inside a ScrollPane, is to manually set what the vertical scrollbar is showing:

So first, get the first selected row in the table. If there are multiple rows selected, this will still just grab the first row.

int firstSelectedRow = table.getSelectedRow();

Then, get where (the y-coordinate) the selected row is located in the table.

Rectangle cellLocation = table.getCellRect(firstSelectedRow, 0, false);

Finally, we can tell the vertical scrollbar where to be.

scrollPane.getVerticalScrollBar().setValue(cellLocation.y);

Also, if there are no selected rows, this will have the viewport show the top of the table.

I would rather use the scrollRectToVisible() method, but for some reason, it was not working for me and this seems to work every time.

Kevin S