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?
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.
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.
keyReleased(KeyEvent e) Invoked when a key has been released. void. keyTyped(KeyEvent e) Invoked when a key has been typed.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With