user489041
user489041

Reputation: 28312

Detecting when user presses enter in Java

I have a subclass of JComboBox. I attempt 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. It is actually not called at all. Am I adding this listener wrong? Are there other ways to add it?

Upvotes: 6

Views: 51851

Answers (2)

jricher
jricher

Reputation: 2677

Key events aren't fired on the box itself, but its editor. You need to add the keyListener to the editor of the JComboBox and not the box 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.

Upvotes: 16

camickr
camickr

Reputation: 324207

This is NOT the proper approach. The editor for a JComboBox is a JTextField. If you want to handle the Enter key then you add an ActionListener to the text field.

Always avoid using KeyListeners.

Edit:

comboBox.getEditorComponent().addActionListener( ... );

Upvotes: 1

Related Questions