setMnemonic() and call a method by pressing the key

It’s worth reading here about Oracle Tutorial – Enabling Keyboard Operation where it is explained in details along with sample.

Read more about on Oracle Tutorial – How to Use Key Bindings

Some example directly from the above tutorial:

//Setting the mnemonic when constructing a menu item:
menuItem = new JMenuItem("A text-only menu item",
                     KeyEvent.VK_H);

//Setting the mnemonic after creation time:
menuItem.setMnemonic(KeyEvent.VK_H);

//Setting the accelerator:
menuItem.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_H, ActionEvent.ALT_MASK));


Read more here Oracle Tutorial – How to Use Buttons, Check Boxes, and Radio Buttons

Sample code: (Alt-H would click the Middle button)

JButton b2 = new JButton("Middle button", middleButtonIcon);
b2.setMnemonic(KeyEvent.VK_H);

Leave a Comment