每當我編寫涉及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
}