java - 在游戏循环之前或之中运行时不显示 Swing 组件

标签 java swing components event-dispatch-thread

我实际上正在尝试修复 JFrame 组件的问题,该组件在运行游戏循环时不想显示(请参阅代码后面的问题)。我已经尽可能减少了代码,以便您能够快速理解我的意思:

运行.class

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Game game = new Game();
            game.loop();
        }
    });
}

游戏.class

private Frame frame;
private HashMap<String,ActionListener> actions;
private HashMap<String,Image> ressources;

public Game() {
    this.setActions();
    this.setRessources();
    frame = new Frame(actions,ressources);
}
public void loop() {
    double FPS = 60;
    double UPS = 60;
    long initialTime = System.nanoTime();
    final double timeU = 1000000000 / UPS;
    final double timeF = 1000000000 / FPS;
    double deltaU = 0, deltaF = 0;
    int frames = 0, ticks = 0;
    long timer = System.currentTimeMillis();
    boolean running = true;
    boolean RENDER_TIME = false;

    while (running) {
        ...code for update, render, with a fps control
    }
}

框架.class

public Frame(HashMap<String,ActionListener> actions, HashMap<String,Image> ressources) {

    this.setTitle(Constants.GAME_NAME);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(Constants.GAME_SIZE_X, Constants.GAME_SIZE_Y);
    this.setLayout(new FlowLayout());

    JButton myButton = new JButton("My Button");
    this.add(myButton);

    this.revalidate();
    this.repaint();
    this.setVisible(true);
}

这不是完整的代码,因为我不想给出无用的东西。所以在这里,我的问题是:

如果我运行此代码,按钮将不会显示在框架中。但是如果我在 Run.class 中注释 game.loop() ,窗口就会显示该按钮。我不明白为什么?

这几天我一直在尝试解决这个问题。我需要一些帮助来解决这个问题。恐怕我一个人也找不到答案。

最佳答案

热衷于阻止 Event Dispatching Thread通过运行较长的进程,您可以使用 swing Timer它可以为您处理“循环”:

ActionListener animate = e -> {
    game.oneFrame();
    panel.repaint();  
};
timer = new Timer(50, animate); 
timer.start(); 

public void oneFrame(){
   //update what is needed for one "frame"
}

如需更多帮助,请发布 mcve。

关于java - 在游戏循环之前或之中运行时不显示 Swing 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53826330/

相关文章:

java - 我们如何在java中创建一个像Object类的类

java - JPA - 注入(inject)或实例化自定义属性/对象以进行 JSF 写访问?

java - 如何找出当前具有焦点的对象

java - 什么是可用于 Swing 的数据绑定(bind)库?

Angular 将父组件的多个服务实例用于子组件

delphi - 为什么我在 IDE 中得到了另一个尺寸的组件?

java - Greenfoot - isKeyDown() 似乎保持其值(value)

java - 我试图在中间画一条线。我尝试了不同的坐标

iphone - 如何将 NSString 的每个字符添加到 NSArray 中?

java - Android 应用程序可监控 Google AI Platform 模型的训练状态