1

I am using the javax.swing packages to construct a gui, and have a while loop running forever with an if statement inside, to see if a button has been pressed. For some reason unbeknownst to me, this code only works if I print to the console inside the while loop.

Here is the algorithm structure:

while(true){
   System.out.println(" ");
   if (startOver && playPressed) {//set to true on JButton press
    //do stuff
   }
}

Possibly this is some sort of threading issue? Has anyone ever encountered such a problem before? Is there a method of waiting for a JButton to be pressed that doesn't involve an infinite while loop?

Thanks in advance!

mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

2

Swing is event-based. You're not supposed to have infinite loops waiting for a button to be pressed. The loop is implemented by Swing internally. What you're supposed to do is to add an action listener to the event, which will be called by the button when it's clicked:

button.addActionListener(new ActionListener() {
    @Override 
    public void actionPerformed(ActionEvent e) {
        System.out.println("The button has been clicked!");
        // do stuff
    }
}

This is fundamental stuff when dealing with Swing. You should read the swing tutorial.

Any infinite loop in the swing event dispatch thread will freeze the GUI forever.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • The problem with this is that whenever I press the button, other buttons need to be pressed while the "//do stuff" is being done. So if I put the "//do stuff" inside the actionperformed override, the button remains pressed down, and I am unable to interract with any of the other buttons. I realize that swing is event-based, my question was "why does this only work whenever I print to console?" –  Apr 10 '13 at 00:47
  • If you want to do stuff in the background, and still be able to use your GUI while this stuff is being done, then use a SwingWorker. Everything you do in the event dispatch thread freezes the GUI. – JB Nizet Apr 10 '13 at 05:47
0

The only way I was able to overcome this problem without an infinite loop was by creating a new thread for the "//do stuff" portion of the algorithm.

very strange, and I still don't understand why I had to print to console to make it work within the while loop.