我有这段代码:
frame = new JFrame();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
isRunning = false;
}
});
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.setSize(width * scale, height * scale);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
panel.setFocusable(true);
panel.requestFocusInWindow();
// KeyBinds
KeyManager.start(panel);
在KeyManager中:
public static void start(JComponent comp) {
comp.requestFocus();
comp.requestFocusInWindow();
comp.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "w");
comp.getActionMap().put("w", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
pressedKeys.put(KeyStroke.getKeyStroke("w"), true);
}
});
但我的代码有时只能运作。某处有问题吗?我需要添加一行代码吗?
答案 0 :(得分:0)
好吧,我解决了这个问题。我使用hashmap(Keystroke,Boolean)来存储键值。我读到使用KeyStroke.getKeyStroke(String key)不是一个好主意,所以我将hashmap更改为使用(Integer,Boolean),整数为KeyEvent.VK_(key)。它现在有效:)