每当我编写涉及while循环的代码时,GUI会冻结,创建一个无限循环。我想知道我可以如何防止这种情况。下面是一个例子,在这里我尽量让在JToggleButton中,这冻结了状态的循环条件,使循环无限:While While循环期间主动更新
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
}