Scroll a JScrollPane to a specific row on a JTable

David picture David · Aug 13, 2011 · Viewed 15.1k times · Source

Possible Duplicate:
JTable Scrolling to a specified row index

I have a JTable and I programmatically need to select a row by using this code:

  myTable.setRowSelectionInterval(i, j);

(where i and j are valid row and column numbers respectively).

The problem is, when you jump to a row, the JScrollPane does not move. In this case, the table is quite long, and often the "selected row" is not visible on the screen, so the user has to stay scrolling up/down manually to find it. I would like to know how I can make the JScrollPane automatically jump to the specific location of the row.

Edit: Found this one liner which can do it:

table.scrollRectToVisible(table.getCellRect(row,0, true)); 

Answer

Eng.Fouad picture Eng.Fouad · Aug 13, 2011

I used this in my old project:

public static void scrollToVisible(JTable table, int rowIndex, int vColIndex)
{
    if (!(table.getParent() instanceof JViewport)) return;
    JViewport viewport = (JViewport)table.getParent();
    Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
    Point pt = viewport.getViewPosition();
    rect.setLocation(rect.x-pt.x, rect.y-pt.y);
    viewport.scrollRectToVisible(rect);
}

Reference: http://www.exampledepot.com/egs/javax.swing.table/Vis.html