首页 > 解决方案 > 在游戏循环之前或之中运行时不显示 Swing 组件

问题描述

我实际上是在尝试解决JFrame在我运行游戏循环时不想出现的组件的问题(请参阅代码后面的问题)。我已尽可能减少代码,以便您快速了解我的意思:

运行类

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

游戏类

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
    }
}

框架类

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

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

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

我已经尝试了几天来弄清楚。我需要一些帮助。恐怕我一个人不会发现。

标签: javaswingcomponentsevent-dispatch-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。


推荐阅读