How to capture key events
-
18-04-2021 - |
سؤال
All of the examples for key listeners I have been able to find deal with components other than the main panel such as a text box or Menu.
I know how to use setMnemonic to program Menu hotkeys but this method does not seem to be available and the link to the oracle keylistener tutorial is broken.
When I do a Right Click > Events > Key > KeyPressed on the main form I get the following but none of keys cause mainPanelKeyPressed.
What is the correct way to use the key events to trigger an action independent of the focus?
mainPanel.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
mainPanelKeyPressed(evt);
}
});
private void mainPanelKeyPressed(java.awt.event.KeyEvent evt) {
// Added to help find the ID of each 'arrow' key
JOptionPane.showMessageDialog(null, "mainPanelKeyPressed");
}
المحلول
What is the correct way to use the key events to trigger an action independent of the focus?
Or use a JMenuBar with menus and menu items.
نصائح أخرى
the focus is important. you may need to click around and experiment, and use component.requestFocusInWindow() to help.