Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中检测用户何时按enter键_Java_Events_Swing_Jcombobox_Keylistener - Fatal编程技术网

在Java中检测用户何时按enter键

在Java中检测用户何时按enter键,java,events,swing,jcombobox,keylistener,Java,Events,Swing,Jcombobox,Keylistener,我有一个JComboBox的子类。我尝试用以下代码添加一个键侦听器 addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { if(evt.getKeyCode() == KeyEvent.VK_ENTER) { Syste

我有一个JComboBox的子类。我尝试用以下代码添加一个键侦听器


        addKeyListener(new KeyAdapter() 
        {
            public void keyPressed(KeyEvent evt)
            {
                if(evt.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    System.out.println("Pressed");
                }
            }
        });

但是,当用户按键时,这无法正确检测。实际上根本不叫它。我添加这个侦听器是错误的吗?还有其他方法可以添加它吗?

关键事件不会在框本身上触发,而是在其编辑器上触发。您需要将keyListener添加到JComboBox的编辑器中,而不是直接添加到该框中:

comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() 
    {
        public void keyPressed(KeyEvent evt)
        {
            if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            {
                System.out.println("Pressed");
            }
        }
    });

编辑:修复了方法调用。

这不是正确的方法。JComboBox的编辑器是JTextField。如果要处理Enter键,则向文本字段添加ActionListener

始终避免使用KeyListener

编辑:


请给我们看完整的代码,我可以知道为什么需要在组合框中按enter键吗?这个函数似乎没有问题,也许你调用它的方式有问题。我们需要看到更多的code@user489041,您不应该为此使用KeyListener。@user489041,您是否向JButton添加过ActionListener?代码完全一样。如果您还没有阅读Swing教程中关于“如何编写动作侦听器”()的部分,则需要comboBox.getEditor().addActionListener(…)
comboBox.getEditorComponent().addActionListener( ... );