Timothy Miller
Timothy Miller

Reputation: 1599

JTable: Select next cell on Tab, but first focus selects same cell, not next one

I would like to:

For the Add button, I do this:

add_button.addActionListener(new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        int row = table_model.addRow();
        table.setRowSelectionInterval(row, row);
        table.scrollRectToVisible(table.getCellRect(row, 0, true));
        table.editCellAt(row, 0);
        table.transferFocus();
        did_add = true;
    }
});

This does indeed cause the table cell to take focus and start editing. To ensure that pressing Tab selects the next cell, I have this:

table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0, false), "selectNextColumnCell");

Here's my problem:

So, it seems that although the cell is focused and being edited, something is awry with the table's focus, because it is incorrect about which cell is next.

I have tried a few work-arounds involving setting the focus to the table, but none seem to work (requestFocus, requestFocusInWindow, setting the table selection, etc.).

Any idea how to fix this?

Upvotes: 1

Views: 3449

Answers (1)

kleopatra
kleopatra

Reputation: 51536

That happens because the column selection is not changed by setting the table's row selection: on startup it's unselected, then navigating to the next column (aka: tabbing out off the edited) sets it to the first column. To solve, set the column selection as well as the row selection

   table.setRowSelectionInterval(row, row);
   table.setColumnSelectionInterval(0, 0);

Upvotes: 1

Related Questions