简体   繁体   English

Java键绑定无效

[英]Java Key Binding Not Working

I have this code: 我有以下代码:

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

And in KeyManager: 在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);
        }
    });

But my code only works sometimes. 但是我的代码有时只能工作。 Is there a problem somewhere? 哪里有问题吗? Is there a line of code I need to add? 是否需要添加一行代码?

Well, I fixed the problem. 好吧,我解决了这个问题。 I used a hashmap (Keystroke, Boolean) to store the key values. 我使用了一个哈希图(击键,布尔值)来存储键值。 I read that using KeyStroke.getKeyStroke(String key) is not a good idea, so I changed the hashmap to using (Integer, Boolean) with the integer being KeyEvent.VK_(key). 我读到使用KeyStroke.getKeyStroke(String key)并不是一个好主意,所以我将哈希映射更改为使用(Integer,Boolean),整数为KeyEvent.VK_(key)。 It works now :) 现在可以工作了:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM