按下Tab时如何防止JTable返回第一行? [英] How to prevent JTable from returning to the first row when Tab is pressed?

查看:82
本文介绍了按下Tab时如何防止JTable返回第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

简短的答案:找到绑定到Tab的动作,将其包装到一个自定义动作中,该动作仅在不在最后一个单元格时才委托给原始人,然后替换您自定义实现的原始操作.

The short answer: find the action that's bound to the Tab, wrap it into a custom action that delegates to the original only if not in the last cell and replace the original action with your custom implemenation.

在代码中:

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

这篇关于按下Tab时如何防止JTable返回第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆