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