2012-01-02 246 views
2

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

回答

4

UI事件,重繪等由單個線程來處理。你正在導致該線程陷入循環;在循環過程中沒有其他事情可以發生(來自UI的事件)。你需要做任何你想在一個單獨的線程中做的事情。

2

Swing使用單線程。長時間使用另一個線程。 通常SwingWorker用於這些任務。