Detection when user clicks input in Java

I have a subclass of JComboBox. I am trying to add a key listener with the following code.


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

This, however, does not correctly detect when the user presses a key. This is actually not called at all. Can I add this listener incorrectly? Are there any other ways to add it?

+5
source share
2 answers

Key events are not triggered in the window itself, but in its editor. You need to add keyListener to the JComboBox editor, and not to the field directly:

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

Edit: fixed method call.

+13
source

. JComboBox JTextField. Enter, ActionListener .

KeyListeners.

Edit:

comboBox.getEditorComponent().addActionListener( ... );
+1

All Articles