使用 Tab 键从 JTextArea 移动焦点

2022-09-01 10:00:24

如前所述,我想更改 a 中的默认 TAB 行为(以便它像一个或类似的组件一样工作)JTextAreaJTextField

这是事件操作

private void diagInputKeyPressed(java.awt.event.KeyEvent evt) {
    if(evt.KEY_PRESSED == java.awt.event.KeyEvent.VK_TAB) {
        actionInput.transferFocus();
    }
}

这是听众

diagInput.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(java.awt.event.KeyEvent evt) {
        diagInputKeyPressed(evt);
    }
});

我试过evt。KEY_TYPED,没有喜悦。

有什么想法吗?

快速编辑:我也尝试过代替requestFocus()transferFocus()


答案 1

根据这个类

/**
 * Some components treat tabulator (TAB key) in their own way.
 * Sometimes the tabulator is supposed to simply transfer the focus
 * to the next focusable component.
 * <br/>
 * Here s how to use this class to override the "component's default"
 * behavior:
 * <pre>
 * JTextArea  area  = new JTextArea(..);
 * <b>TransferFocus.patch( area );</b>
 * </pre>
 * This should do the trick. 
 * This time the KeyStrokes are used.
 * More elegant solution than TabTransfersFocus().
 * 
 * @author kaimu
 * @since 2006-05-14
 * @version 1.0
 */
public class TransferFocus {

    /**
     * Patch the behaviour of a component. 
     * TAB transfers focus to the next focusable component,
     * SHIFT+TAB transfers focus to the previous focusable component.
     * 
     * @param c The component to be patched.
     */
    public static void patch(Component c) {
        Set<KeyStroke> 
        strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
        c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
        strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
        c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
    }
}

请注意,根据Joshua Goldberg评论中的说法,这可以更短,因为目标是让默认行为被覆盖:patch()JTextArea

component.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERS‌​AL_KEYS, null);
component.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERS‌​AL_KEYS, null);

这在问题“如何修改 JTextArea 中 Tab 键的行为?"


前面的实现确实涉及 a 和 a:ListenertransferFocus()

   /**
     * Override the behaviour so that TAB key transfers the focus
     * to the next focusable component.
     */
    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_TAB) {
            System.out.println(e.getModifiers());
            if(e.getModifiers() > 0) a.transferFocusBackward();
            else a.transferFocus(); 
            e.consume();
        }
    }

e.consume();可能是您错过了使它在您的案例中起作用的原因。


答案 2

推荐