setMnemonic() and call a method by pressing the key

Yithirash picture Yithirash · Jun 8, 2014 · Viewed 26.1k times · Source

I have to run a method manually when pressing the key Alt+H

if("The key pressed==(Alt+H)"){
    callMethod();
}

public void callMethod(){
    //Some codes here
}

How I can actually do this in Java. Please give me a simple way to do this.

Answer

Braj picture Braj · Jun 8, 2014

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);