JTable Scrolling to a Specified Row Index

Chris Dail picture Chris Dail · May 12, 2009 · Viewed 49.2k times · Source

I have a JTable that is within a JScrollPane. Rows are added to the table at runtime based on events that happen in my application. I want to have the scoll pane scroll to the bottom of the table when a new row is added to the table.

For JLists There is the [ensureIndexIsVisible][1]() that forces a particular index in the list to be visible. I'm looking for the same thing but for a JTable. It looks like I might have to manually move the scrolling view on the scroll pane but I figured there had to be an easier way.

Answer

martinusadyh picture martinusadyh · Jun 3, 2011

It's very easy, JTable has scrollRectToVisible method too. If you want, you can try something like this to make scrollpane go to to the bottom if a new record is added :

jTable1.getSelectionModel().setSelectionInterval(i, i);
jTable1.scrollRectToVisible(new Rectangle(jTable1.getCellRect(i, 0, true)));

Where i is last added record.