0

首先,我是编程新手,我正在开发一个小型应用程序,我希望用户能够按下键绑定。目前,我正在使用虚拟键,这意味着您必须按ALT+KEY但我宁愿只是您必须按KEYPRESS。我有KeyListener的代码。

我的按钮当前键绑定:

commandsButton.setMnemonic(KeyEvent.VK_A);

我的按钮监听器:

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

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

4

1 回答 1

2

Depending on what you want to achieve, you could use the Key Bindings API, for example...

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

Now the great thing about this is, you can reuse the Action...

For example...

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

And then...

ConsoleAction consoleAction = new ConsoleAction();
JButton consoleButton = new JButton(consoleAction);
//...
am.put(consoleAction);
于 2013-11-07T03:43:22.817 回答