我必须手动运行一个方法当按下键Alt+H
if("The key pressed==(Alt+H)"){
callMethod();
}
public void callMethod(){
//Some codes here
}
如何在Java中实现。请给我一个简单的方法。
值得在这里阅读Oracle教程-启用键盘操作,其中详细解释了示例。
阅读更多关于Oracle教程-如何使用键绑定
直接从上面的教程中的一些例子:
//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));
阅读更多在这里Oracle教程-如何使用按钮,复选框和单选按钮
示例代码:(Alt-H
将点击中间按钮)
JButton b2 = new JButton("Middle button", middleButtonIcon);
b2.setMnemonic(KeyEvent.VK_H);
如果使用菜单,则可以使用setMnemonic()
,请参见如何使用菜单的示例。另一个选择是使用键绑定。例如:
import java.awt.event.*;
import javax.swing.*;
public class TestKeys {
private static void createAndShowGUI() {
final JFrame frame = new JFrame("Keys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.ALT_MASK);
Action testAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Alt-H pressed");
}
};
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "TestAction");
frame.getRootPane().getActionMap().put("TestAction", testAction);
JLabel label = new JLabel("Hit Alt-H");
label.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
frame.add(label);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
最好的方法是使用setmnemon(),因为它是最简单的。
查看这篇文章获取更多信息http://www.herongyang.com/Swing/JMenuBar-Set-Keyboard-Mnemonics-on-Menu-Items.html
private JMenu getColorMenu() {
JMenu myMenu = new JMenu("Color");
ButtonGroup myGroup = new ButtonGroup();
JRadioButtonMenuItem myItem = new JRadioButtonMenuItem("Red");
myItem.setSelected(true);
myItem.setMnemonic(KeyEvent.VK_R);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
myItem = new JRadioButtonMenuItem("Green");
myItem.setMnemonic(KeyEvent.VK_G);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
myItem = new JRadioButtonMenuItem("Blue");
myItem.setMnemonic(KeyEvent.VK_B);
myItem.addActionListener(this);
myItem.addMenuKeyListener(this);
myGroup.add(myItem);
myMenu.add(myItem);
return myMenu;