How to capture key events

advertisements

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?

See: How to Use Key Bindings

Or use a JMenuBar with menus and menu items.