Reputation: 37
Everytime I make code involving a while loop, the GUI freezes up, creating an infinite loop. I want to know how I can prevent this. Here is an example, where I try to make the loop conditional on the state of Jtogglebutton, which freezes up, making the loop infinite:
boolean state = StartStop.getModel().isSelected(); //whether toggle button is on or off
int speed = SpeedSelection.getValue(); //value of the speed selection bar
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
while(state == true){
try {
Status.setText("Running...");
StartStop.setText("Stop");
position += speed;
System.out.println(position);
ScrollPane.getHorizontalScrollBar().getModel().setValue(position);
Thread.sleep(250);
state = StartStop.getModel().isSelected();
speed = SpeedSelection.getValue();
//start scrolling the scroll pane
}
catch (InterruptedException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(state == false){
Status.setText("Paused.");
StartStop.setText("Start");
//stop scrolling
}
Upvotes: 2
Views: 2105
Reputation: 109813
don't use Threa#sleep(int)
during EDT, that reason why your GUI freeze, you have three choices
use SwingWorker
use Runnable@Thread
Upvotes: 3
Reputation: 1448
Swing uses single thread. Use another thread for long time tasks. Usually SwingWorker is used for these tasks.
Upvotes: 2
Reputation: 76898
UI events, repainting, etc is handled by a single thread. You're causing that thread to get stuck in a loop; nothing else can happen (events from the UI) while it's looping. You need to do whatever it is you're trying to do in a separate thread.
Upvotes: 4