Java Swing KeyBindings仅在Mac上停止工作

2022-09-04 22:40:45

我正在使用 Swing 开发一款游戏,并且我正在使用 KeyBindings 从键盘进行输入。

我遇到了密钥绑定停止响应的问题。每次我运行应用程序时都会发生这种情况,但据我所知,这不是某个事件链发生的时候。键绑定只是停止接收来自键盘的输入。我也使用鼠标输入,它继续工作,所以我知道它与一般的输入无关。

我尝试过一些事情:

  • 确保我的对象未被垃圾回收
  • 寻找问题发生的某种原因(例如:经过一定时间,按下某个组合键),我找不到
  • 尝试改用KeyListener

这些都不起作用。

然后,我将项目(不更改任何代码)复制到Windows计算机,经过测试后,我无法让问题发生一次。我没有在这里粘贴代码,因为我99%肯定这与我的代码无关,但与它运行的操作系统有关。

这是macOS的问题,还是Mac版JDK的问题,还是我不知道的其他问题?

我使用的是JDK版本8更新112,计算机运行的是macOS Sierra版本10.12.2。

似乎其他人也有我现在遇到的同样的问题,但他们从来没有得到答案。

编辑

下面是出现问题的代码示例:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

//an example of the problem where the keyboard stops receiving input randomly
public class ProblemExample extends JPanel {
    private static final long serialVersionUID = 1L;

    private int xPos = 200, yPos = 200;
    private boolean wKey, aKey, sKey, dKey;
    private BufferedImage image; //sprite

    public ProblemExample() {
        JFrame frame = new JFrame();
        frame.add(this);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //makes the sprite a red square
        image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
        int[] redPixels = new int[50 * 50];
        for (int i = 0; i < redPixels.length; i++) {
            redPixels[i] = 0xffff0000;
        }
        image.setRGB(0, 0, 50, 50, redPixels, 0, 50);
        initializeKeys();
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(800, 600);
    }

    //sets up Key Bindings
    private void initializeKeys() {
        final String W = "W",
                     A = "A", 
                     S = "S", 
                     D = "D",
                     PRESSED = "PRESSED",
                     RELEASED = "RELEASED";

        InputMap inputMap = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = this.getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), W + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), A + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), S + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), D + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, true), W + RELEASED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, true), A + RELEASED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, true), S + RELEASED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, true), D + RELEASED);

        Action wActionPressed = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                wKey = true;
            }
        };
        Action aActionPressed = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                aKey = true;
            }
        };
        Action sActionPressed = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sKey = true;
            }
        };
        Action dActionPressed = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dKey = true;
            }
        };
        Action wActionReleased = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                wKey = false;
            }
        };
        Action aActionReleased = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                aKey = false;
            }
        };
        Action sActionReleased = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sKey = false;
            }
        };
        Action dActionReleased = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dKey = false;
            }
        };

        actionMap.put(W + PRESSED, wActionPressed);
        actionMap.put(A + PRESSED, aActionPressed);
        actionMap.put(S + PRESSED, sActionPressed);
        actionMap.put(D + PRESSED, dActionPressed);
        actionMap.put(W + RELEASED, wActionReleased);
        actionMap.put(A + RELEASED, aActionReleased);
        actionMap.put(S + RELEASED, sActionReleased);
        actionMap.put(D + RELEASED, dActionReleased);
    }

    public void loop() {
        if (wKey) yPos -= 5;
        if (aKey) xPos -= 5;
        if (sKey) yPos += 5;
        if (dKey) xPos += 5;
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, xPos, yPos, null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ProblemExample example = new ProblemExample();
                Timer timer = new Timer(60, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        example.loop();
                    }
                });
                timer.start();
            }
        });
    }

}

答案 1

您可能会认为这是MAC中的一个错误,而它不是因为MAC具有辅助密钥的功能
由于您是MAC的用户,我希望您知道此功能。此功能可能是导致问题的原因
MAC的辅助键功能:用于按住字母键将显示该字母的变体,例如按住“u”以获得“ü”。这在拼写非英语单词时派上用场。

有一种简单的方法可以控制和更改长按键的行为,以满足您的需求。

打开终端应用并编写:

defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false

然后重新启动要在其中激活此设置的任何打开的应用。

恢复原状: 只是,只需添加代替上一个命令,如下所示:truefalse

defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool true

更新:
您可以加快按键重复的速度或降低按住的键开始重复之前的延迟,方法是转到“系统偏好设置”,然后在键盘标题下进行更改。


答案 2

除了Tahir Hussain Mir关于更改Mac密钥设置的建议之外,我发现问题在于循环,以事件驱动的方式实现它会更有效,我冒昧地更改了一下你的代码。与侯赛因·米尔一起建议的解决方案,它应该解决你的问题。

您也可以自己处理重复按键,例如,在按键时启动计时器并在按键释放时停止它,但是Windows和Mac之间的按键行为会有所不同,这并不是您想要的方式。

package swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

//an example of the problem where the keyboard stops receiving input randomly
public class SOMacKeyBindings extends JPanel
{
    private BufferedImage image; //sprite
    private Point point = new Point(200, 200);
    private int steps = 5;

    private class KeyAction extends AbstractAction
    {
        private Runnable runnable;

        public KeyAction(Runnable runnable)
        {
            this.runnable = runnable;
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            runnable.run();
        }
    }

    public SOMacKeyBindings()
    {
        JFrame frame = new JFrame();
        frame.add(this);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        //makes the sprite a red square
        image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
        int[] redPixels = new int[50 * 50];
        for (int i = 0; i < redPixels.length; i++)
        {
            redPixels[i] = 0xffff0000;
        }
        image.setRGB(0, 0, 50, 50, redPixels, 0, 50);
        initializeKeys();
    }

    @Override
    public Dimension getPreferredSize()
    {
        return new Dimension(800, 600);
    }

    //sets up Key Bindings
    private void initializeKeys()
    {
        final String W = "W",
                A = "A",
                S = "S",
                D = "D",
                PRESSED = "PRESSED";

        InputMap inputMap = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
        ActionMap actionMap = this.getActionMap();

        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0, false), W + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0, false), A + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0, false), S + PRESSED);
        inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), D + PRESSED);

        actionMap.put(W + PRESSED, new KeyAction(() -> { point.y -= steps; repaint(); }));
        actionMap.put(A + PRESSED, new KeyAction(() -> { point.x -= steps; repaint(); }));
        actionMap.put(S + PRESSED, new KeyAction(() -> { point.y += steps; repaint(); }));
        actionMap.put(D + PRESSED, new KeyAction(() -> { point.x += steps; repaint(); }));
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawImage(image, point.x, point.y, null);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() -> new SOMacKeyBindings());
    }
}

推荐