linsek
linsek

Reputation: 3480

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

Upvotes: 2

Views: 1478

Answers (2)

Michael
Michael

Reputation: 1

I have had a similar issue which i solved with help of above first I added gotoButton and text field

    JPanel gotoPanel = new JPanel();
    JButton gotoRowButton = new JButton("Goto Address");
    JTextField gotoAddressTextField = new JTextField();
    gotoAddressTextField.setColumns(12);
    gotoPanel.add(gotoRowButton);
    gotoPanel.add(gotoAddressTextField);

    frame.add(gotoPanel, BorderLayout.NORTH);

then I added an actionListnener for the gotoRowButton

        gotoRowButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
            
             table.setRowSelectionInterval(
                 Integer.parseInt(gotoAddressTextField.getText(), 
                 Integer.parseInt(gotoAddressTextField.getText()));
            table.scrollRectToVisible(
            table.getCellRect(
              Integer.parseInt(gotoAddressTextField.getText()), 1, true)
      );
        }
    });

a visual of my work An image showing gotobutton and textfield and highlight of gotoRow

Upvotes: 0

Michael Myers
Michael Myers

Reputation: 191995

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.

Upvotes: 3

Related Questions