【问题标题】:Java AWT Stops listening to input after random lengths of timeJava AWT 在随机时间长度后停止监听输入
【发布时间】:2020-03-26 06:11:40
【问题描述】:

(抱歉,我无法获得该问题的有效示例,我需要帮助!)

我正在创建自定义游戏引擎,但遇到了一个问题,即在游戏运行时 - 游戏停止接受输入

我检查过,程序似乎继续在后台运行。它似乎也不会因不同的机器而异 (我的主要设备是 Mac Book Pro 2011)

import java.awt.event.*;
import java.io.IOException;
import java.awt.*;
import javax.swing.*;

public class Focus extends JFrame implements KeyListener {   
    private static final long serialVersionUID = 1L;
        char currKey = '\0';
        public static void main(String[] args) throws IOException {
            SwingUtilities.invokeLater(new Runnable() {public void run() {new UIManager();}});
        }
        public Focus() throws IOException {     
            Container contentPane = getContentPane();
            contentPane.add(new DrawCanvas());
            addKeyListener(this);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setFocusable(true);
            setVisible(true);
        }    
        private class DrawCanvas extends JPanel {                   
            private static final long serialVersionUID = 1L;   
            public void paintComponent(Graphics pen) {
                //Drawloop
                if(currKey == 'k') {
                    //This is the code that randomly stops running
                    System.out.println("Yo");
                }
                try {
                    Thread.sleep(10);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
                repaint();
            }
        }
        @Override
        public void keyTyped(KeyEvent e) {
            currKey = e.getKeyChar();
        }
        @Override
        public void keyPressed(KeyEvent e) {
            currKey = '\0';
        }
        @Override
        public void keyReleased(KeyEvent e) {   
        }
}

代码在我看来是正确的(但它总是如此),唯一可能的触发点是 AWT 在 Main 中实例化,在 UIManager 中运行,并且移动代码驻留在播放器中,尽管我对 AWT 了解不足知道是否会出现这种情况,并且在备份中重新定位代码会导致程序崩溃。任何帮助将不胜感激。

【问题讨论】:

  • 你能创建一个显示问题的小型 MVCE 吗?

标签: java awt


【解决方案1】:

原来这是 Java 和 MacOS 密钥重复的问题 - 在较新的 Java 版本中已修复

修复更新java

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2016-04-26
    • 2023-03-14
    • 2021-12-20
    • 2013-03-13
    相关资源
    最近更新 更多