I would like to:
- Have a button add a row to a JTable
- When that row is created, give it focus and start editing the first column
- When the user presses Tab, select the next column.
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:
- If I have made any cell selections previously, this works perfectly. I can edit the first column, and press Tab, and that causes the next column to be selected.
- However if this table is newly created or some widget outside of that table has previously had focus, and I click my Add button, then this happens:
- The first column is selected properly and is editable
- When I press Tab, usually the same cell is focused
- I have to press Tab a second time to go to the next 开发者_如何学运维column
- Sometimes, that first tab actually goes to cell 0,0
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?
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);
精彩评论