0

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);
       }
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I know I am creating a new instance of PopUp because the frame appears in a random location like I am telling it to but it does not display the button – TheMikeCav Feb 21 '14 at 06:54

2 Answers2

0

place the these statements after the try-catch block, and also check the value of the variable gameover.

         p1 = new PopUp(); //keep
         p1.setLocation(((int)(Math.random()*2000)), ((int)(Math.random()*1000)));
         popUpsOpen++;
Balayesu Chilakalapudi
  • 1,386
  • 3
  • 19
  • 43
  • gameover can be ignored for now, and the placement of those lines only matters when its outside the loop or inside the loop. Otherwise, moving those lines doesn't change anything. – TheMikeCav Feb 21 '14 at 06:58
0

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

adt14
  • 76
  • 5