JFrame:简单的键绑定?

时间:2013-11-07 03:39:33

标签: java swing jframe keylistener

首先,我是编程的新手,我正在开发一个小应用程序,我希望用户可以按键绑定。目前,我正在使用虚拟密钥,这意味着您必须按 ALT + KEY ,但我更倾向于您必须按 KEYPRESS 。代码我有 KeyListener

我的按钮当前键绑定:

commandsButton.setMnemonic(KeyEvent.VK_A);

我的按钮听众:

commandsButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            runCommand();
      }});

我宁愿只能按“ A ”而不是“ ALT + A

1 个答案:

答案 0 :(得分:2)

根据您要实现的目标,您可以使用Key Bindings API,例如......

InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "Press.A");
am.put("Press.A", new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        gameConsole.append("\n\nCommands: \n ==========");
        commands();
    }
});

现在最重要的是,您可以重复使用Action ...

例如......

public class ConsoleAction extends AbstractAction {

    public ConsoleAction() {
        putValue(NAME, "Text of button");
        putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, 0));
        putValue(MNEMONIC_KEY, KeyEvent.VK_A);
    }

    public void actionPerformed(ActionEvent e) {
        gameConsole.append("\n\nCommands: \n ==========");
        commands();
    }
}

然后......

ConsoleAction consoleAction = new ConsoleAction();
JButton consoleButton = new JButton(consoleAction);
//...
am.put(consoleAction);