Search code examples
javaswingjtable

JTable Goto Row


I am trying to implement a goto function. I have a JTable that has a few thousand rows and I want to be able to jump to a specified row number.

else if (BUTTON_GOTO.equals(command))
{
    int gotoLine = Integer.valueOf(gotoField.getText());            
    logTable.setRowSelectionInterval(gotoLine, gotoLine);
}

The code above will highlight the row I am looking for, but does not jump to it. Does anyone know how to do this?

Thanks

EDIT There is a bug using the solution below where the application jumps a few lines short of the desired line. See the topic below for further details:

Stack Overflow - Java JTable Goto Row Bug


Solution

  • Try:

    logTable.scrollRectToVisible(logTable.getCellRect(gotoLine, 0, true));
    

    getCellRect() returns a Rectangle which bounds the cell at the given row and column, and scrollRectToVisible() tells the table's parent (which should be a JViewPort if you are using a JScrollPane) to scroll there.