Java - KeyBinds stop working after holding down a key

断了今生、忘了曾经 提交于 2019-12-24 06:48:39

问题


*Update - I took my project from my MacBook and moved it to a windows computer (Same exact code) and the code works just as it is supposed to! Does anyone know why this would happen?

This is my first question here on Stack Overflow so I will try me best to do the correct formatting.

I am making a simple Pong program that needs a paddle to move up and down on key events (A & Z). The key events work perfect when I simply type a key but when I hold down a key for too long for some reason the key events stop working entirely, meaning that even the typing of the keys won't register anything anymore until I restart the program.

I have searched for the answer for over 2 hours with no avail. Every question that seems similar ends up with an answer of the focus being the problem and adding JComponent.WHEN_IN_FOCUSED_WINDOW inside the InputMap. However I have tried this and it does not help or fix my problem at all.

Here is my code:

public class ColorPanel extends JPanel implements ActionListener{
    public ColorPanel(Color backColor, int width, int height){

   //Non Relavent coding removed

    //Code for KeyBinding

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

    im.put(KeyStroke.getKeyStroke(65, 0, false), "actionName");
    im.put(KeyStroke.getKeyStroke(65, 0, true), "actionName");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 0, true), "actionName");
    im.put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, 0, false), "actionName");

    am.put("actionName", new AbstractAction("actionName") {
          public void actionPerformed(ActionEvent e) {
            //System.out.println("---" + e.getActionCommand() + "---");
            if(e.getActionCommand().equals("a")){
                System.out.println("a!");
            }else if (e.getActionCommand().equals("z")){
                System.out.println("z!");
            }
          }
        });


}

回答1:


You need to disable the macOS accent popup that usually appears when you hold down a key. For some reason this is confusing Java. See here: http://www.techradar.com/how-to/computing/apple/easy-mac-hacks-disable-the-pop-up-accent-window-when-typing-1305618




回答2:


I experience the exact same issue on a mac and as stated here the culprit is the mac's popup window for accented keys . Here is a not-so-perfect workaround:

Whenever the issue happens and the keys stop working, first click on any "text field" in the frame to make it focused, then hold any one of those keys with accent popup (e.g. "a" key), until the popup show. Then hit escape key and from there after all the keys start working again.

(reference: https://stackoverflow.com/a/49783514/8371761)



来源:https://stackoverflow.com/questions/40335285/java-keybinds-stop-working-after-holding-down-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!