我实际上正在尝试修复 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/