使用Tab键从JTextArea移动焦点

时间:2009-02-08 14:50:20

标签: java swing netbeans

如上所述,我想更改JTextArea内的默认TAB行为(以便它像JTextField或类似组件一样)

这是事件动作

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 个答案:

答案 0 :(得分:25)

根据this class

/**
 * 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中的the commentspatch()可能更短,因为目标是取回JTextArea覆盖的默认行为:

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

这用于问题“How can I modify the behavior of the tab key in a JTextArea?


previous implementation确实涉及Listener和a transferFocus()

   /**
     * 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();可能是您错过的,以便在您的情况下使其发挥作用。

相关问题