如何防止JTable在按下Tab键时返回第一行?

3
当在表格的最后一个单元格按下tab键时,如何禁用JTable返回到第一行的默认行为?而是保持当前单元格的焦点。
1个回答

6
简单来说,找到绑定Tab键的操作,将其包装成自定义操作,并在最后一个单元格之外才委托给原始操作,然后用你的自定义实现替换原始操作。
代码如下:
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接