How to prevent JTable from returning to the first row when Tab is pressed?

社会主义新天地 提交于 2019-12-10 20:43:28

问题


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.


回答1:


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.

In code:

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


来源:https://stackoverflow.com/questions/17574338/how-to-prevent-jtable-from-returning-to-the-first-row-when-tab-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!