2012-01-02 75 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用于这些任务。