Change focus to next component in JTable using TAB

后端 未结 4 1981
一个人的身影
一个人的身影 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:10

    The shift-/tab keys are used by default for transfering focus between components. JTable explicitly requests to handle the shift-/tab internally (by providing sets of focusTraversalKeys which doesn't include those).

    Following the general rule (if there's specilized api available for a task, use that instead of rolling your own), the solution is to set traversal keys to again contain them:

    Set forward = new HashSet(
            table.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS));
    forward.add(KeyStroke.getKeyStroke("TAB"));
    table.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forward);
    Set backward = new HashSet(
            table.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS));
    backward.add(KeyStroke.getKeyStroke("shift TAB"));
    table.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backward);
    

提交回复
热议问题