简体   繁体   English

仅当按下Enter键时,按键侦听器才起作用。 对于其他键不起作用

[英]Key listener only works when the Enter key is pressed. Doesn't work for other keys

This code works fine when I press "Enter", but not when I press other keys. 当我按“ Enter”键时,此代码工作正常,但当我按其他键时,此代码无法正常工作。 I added a key event in editable JComboBox which works only when the "Enter" key is pressed. 我在可编辑的JComboBox添加了一个按键事件,该事件仅在按下“ Enter”键时有效。 I also want to add an event to another key. 我还想将一个事件添加到另一个键。

comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
    @Override
    public void keyTyped(KeyEvent e) {
        int keyChar = e.getKeyChar();
        if (keyChar == KeyEvent.VK_ENTER) {
            textField.requestFocus();
        }    
        if (keyChar == KeyEvent.VK_TAB) { // tried other key also such as shift,alt,decimal...  
            textField_2.requestFocus();
        }        
    }
});

Certain keys like TAB, which are used for focus events (eg tabbing from component to component) are already being consumed by the focus subsystem, which is why you are not seeing them on your key listener. 用于焦点事件(例如,从一个组件到另一个组件的制表符)的某些键(如TAB)已被焦点子系统占用,这就是为什么您没有在键侦听器上看到它们的原因。 https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html . https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Read the part labeled Version Note . 阅读标有版本注释的部分。 The article also offers alternatives on what you can do to capture TAB and other focus keys. 本文还提供了一些其他方法来捕获TAB和其他焦点键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM