setMnemonic()并按键调用方法

Yit*_*ash 1 java swing key pressed mnemonics

我必须在按下键(Alt + H)时手动运行方法().

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

public void callMethod(){
    //Some codes here
}
Run Code Online (Sandbox Code Playgroud)

我怎么能用Java实际做到这一点.请给我一个简单的方法来做到这一点.

Bra*_*raj 5

这里值得一读的有关Oracle教程 - 启用键盘操作的内容,详细说明以及示例.

阅读有关Oracle 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));
Run Code Online (Sandbox Code Playgroud)

在此处阅读更多Oracle教程 - 如何使用按钮,复选框和单选按钮

示例代码:( Alt-H将单击"中间"按钮)

JButton b2 = new JButton("Middle button", middleButtonIcon);
b2.setMnemonic(KeyEvent.VK_H);
Run Code Online (Sandbox Code Playgroud)