Search code examples
javaswingjframethread-sleep

JFrame not Displaying JButton in a loop


I am making a simple PopUp game where the code below calls a new instance of a class called PopUp. PopUp is a Jframe with a button on it. When the constructor is called inside the loop the button is not displayed. However when the loop is removed the button is displayed just fine. Please help me. Thank you.

public void game() {
    PopUp p1;
    while(!gameover) { 
        try {
            //If block to set the difficulty of the game
            if(diff==0)
                TimeUnit.MILLISECONDS.sleep(1000);
            else if(diff==1)
                TimeUnit.MILLISECONDS.sleep(750);
            else if(diff==2)
                TimeUnit.MILLISECONDS.sleep(500);
            else if(diff==3)
                TimeUnit.MILLISECONDS.sleep(250);
            else if(diff==4)
                TimeUnit.MILLISECONDS.sleep(100);
             p1 = new PopUp(); //keep
             p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
             popUpsOpen++;
       } catch (InterruptedException ex) {
            Logger.getLogger(PopUpGame.class.getName()).log(Level.SEVERE, null, ex);
       }
    }
}

Solution

  • Try to call Game constructor with different Thread.

    Thread queryThread = new Thread() {
      public void run() {
        new game();
      }
    };
    queryThread.start();
    

    and in Game constructor show the popup with UI thread

    SwingUtilities.invokeAndWait(new Runnable() {
      public void run() {
        p1 = new PopUp(); //keep
             p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
             popUpsOpen++;
      }
    });
    

    i think the button is not displaying because the UI thread busy with looping,so the button doesnt get chance to rendered by UI thread