【问题标题】:How to prevent JTable from returning to the first row when Tab is pressed?Tab按下时如何防止JTable返回第一行?
【发布时间】:2013-07-10 15:11:30
【问题描述】:

当在表格的最后一个单元格中按下 tab 键时,如何禁用 JTable 返回第一行的默认行为?相反,当前单元格应保持其焦点。

【问题讨论】:

    标签: java swing jtable key-bindings key-events


    【解决方案1】:

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

    在代码中:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-21
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2020-01-03
      • 2013-10-04
      相关资源
      最近更新 更多