如何收听在 Java 中按下/键入的 TAB 键?

2022-09-01 11:49:25
    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
    {
        //cant capture my TAB?
        System.out.print(evt.getKeyChar());

    }

在java gui中,不使用焦点监听技术来捕获Tab键的最简单方法是什么?


答案 1

VK_TAB是制表符常量。

然而:No Tab key-pressed or key-released events are received by the key event listener. This is because the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab.

请参见:http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

要解决此问题,请将以下内容应用于触发关键事件的组件(例如,TextArea):

.setFocusTraversalKeysEnabled(false)

使用此方法,必须显式处理焦点遍历。或者,可以使用 KeyEventDispatcher 类来预侦听所有密钥事件。


答案 2

在可编辑的JComboBox的情况下,这个对我有用:

    txt.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.emptySet());
    txt.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent event) {
        if (event.getKeyChar() == KeyEvent.VK_TAB) {

        }
       }
    });