2012-01-02 15 views
2

whileループを含むコードを作成するたびに、GUIがフリーズし、無限ループが作成されます。どのように私がこれを防ぐことができるか知りたい。ここで私はループが無限になって、フリーズJtogglebuttonの状態、上のループを条件付きにしようとする例、されています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

スイングはシングルスレッドを使用します。長時間の作業には別のスレッドを使用します。 通常、これらのタスクにはSwingWorkerが使用されます。