簡體   English   中英

在游戲循環之前或之中運行時未顯示Swing組件

[英]Not showing Swing component when running before or in the game loop

我實際上是在嘗試解決JFrame組件的問題,這些問題在我運行游戲循環時不想出現(請參閱代碼后的問題)。 我已經盡可能地減少了代碼,以便您快速理解我的意思:

Run.class

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

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

Frame.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() ,則窗口將顯示該按鈕。 而且我不明白為什么?

我已經嘗試了幾天以找出答案。 我需要一些幫助。 恐怕我自己找不到。

若要通過運行較長的進程來阻塞事件調度線程 ,可以使用swing 計時器 ,它可以為您處理“循環”:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM