How can I listen to a TAB key pressed/typed in Java?

旧街凉风 提交于 2019-11-29 09:07:40

VK_TAB is the tab constant.

However: 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.

See: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

To solve this, apply the following to the component that is firing the key events (e.g., the TextArea):

.setFocusTraversalKeysEnabled(false)

Using this method, you must then handle focus traversal explicitly. Alternatively, the KeyEventDispatcher class can be used to pre-listen to all key events.

In case of editable JComboBox, this one worked for me:

    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) {

        }
       }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!