Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 723
user489041 Avatar asked Jan 12 '11 19:01

user489041


People also ask

How to detect if user pressed enter in Java?

To check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself. Then in bind() function check the keycode of pressed key whether it's value is 13 is not.

How do I check if the user is pressing a key?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.

What is keyReleased in Java?

keyReleased(KeyEvent e) Invoked when a key has been released. void. keyTyped(KeyEvent e) Invoked when a key has been typed.

How does keyPressed work Java?

In Java, there are three types of KeyEvent. The types correspond to pressing a key, releasing a key, and typing a character. The keyPressed method is called when the user presses a key, the keyReleased method is called when the user releases a key, and the keyTyped method is called when the user types a character.


1 Answers

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.

like image 110
jricher Avatar answered Sep 28 '22 11:09

jricher