当前位置:  开发笔记 > 编程语言 > 正文

使用Tab键从JTextArea移动焦点

如何解决《使用Tab键从JTextArea移动焦点》经验,为你挑选了1个好方法。

如上所述,我想更改a中的默认TAB行为JTextArea(以便它像一个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> VonC..:

根据这个类:

/**
 * 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.
 * 
* Here s how to use this class to override the "component's default" * behavior: *
 * JTextArea  area  = new JTextArea(..);
 * TransferFocus.patch( area );
 * 
* 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 strokes = new HashSet(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB"))); c.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes); strokes = new HashSet(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB"))); c.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes); } }

需要注意的是patch()还可以更短,根据约书亚·戈德堡的意见,因为我们的目标是要回默认行为,通过覆盖JTextArea:

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

这用于问题" 我如何修改标签键的行为JTextArea? "


在以前的实现确实是一个参与Listener,和一个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(); 可能是你错过了让它在你的情况下工作.


`patch`可以更简单,因为你想要恢复由JTextArea覆盖的默认行为.仅有2行:`component.setFocusTraversalKeys({的KeyboardFocusManager向前,向后} _TRAVERSAL_KEYS,空)`参见http://stackoverflow.com/a/5043957/411282
推荐阅读
凹凸曼00威威_694
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有