Change focus to next component in JTable using TAB

后端 未结 4 1985
一个人的身影
一个人的身影 2020-12-20 15:35

JTable\'s default behavior is changing focus to next cell and I want to force it to move focus to next component (e.g. JTextField) on TAB key pressed.
I overrided

4条回答
  •  一个人的身影
    2020-12-20 16:14

    If you really want this, you need to change the default behavior of the tables action map.

    ActionMap am = table.getActionMap();
    am.put("selectPreviousColumnCell", new PreviousFocusHandler());    
    am.put("selectNextColumnCell", new NextFocusHandler());    
    

    Then you need a couple of actions to handle the traversal

    public class PreviousFocusHandler extends AbstractAction {
        public void actionPerformed(ActionEvent evt) {
            KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            manager.focusPreviousComponent();
        }
    }
    
    public class NextFocusHandler extends AbstractAction {
        public void actionPerformed(ActionEvent evt) {
            KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            manager.focusNextComponent();
        }
    }
    

    Another approach would be to disable the underlying Action...

    ActionMap am = table.getActionMap();
    am.get("selectPreviousColumnCell").setEnabled(false);
    am.get("selectNextColumnCell").setEnabled(false);
    

    (haven't tested this)

    The benefit of this approach is can enable/disable the behaviour as you need it without needing to maintain a reference to the old Actions

提交回复
热议问题