3

How can I disable JTable's default behaviour of returning to the first row, when tab key is pressed in the last cell of the table? Instead the current cell should keep its focus.

4

1 回答 1

6

简短的回答:找到绑定到选项卡的操作,将其包装到自定义操作中,仅当不在最后一个单元格中时才委托给原始操作,并用您的自定义实现替换原始操作。

在代码中:

KeyStroke keyStroke = KeyStroke.getKeyStroke("TAB");
Object actionKey = table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
        .get(keyStroke );
final Action action = table.getActionMap().get(actionKey);
Action wrapper = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        JTable table = (JTable) e.getSource();
        int lastRow = table.getRowCount() - 1;
        int lastColumn = table.getColumnCount() -1;
        if (table.getSelectionModel().getLeadSelectionIndex() == lastRow 
                && table.getColumnModel().getSelectionModel()
                        .getLeadSelectionIndex() == lastColumn) {
              return;
        }
        action.actionPerformed(e);
    }

};
table.getActionMap().put(actionKey, wrapper);
于 2013-07-10T15:38:52.473 回答