2013-12-19 51 views
0

我試圖做一個程序,它將幫助可視化氣泡排序算法。該腳本正確排序數組,但它不允許JFrame打開,直到它完成。是否有辦法在繼續進行分類之前使其重新着色所有按鈕?下面發佈是目前處理排序和着色的類。泡沫分類模擬JButton着色

public class SortStart { 

    private JButton[] list; 
    private int[] randomList; 

    public SortStart(JButton[] list, int[] randomList){ 
     this.list = list; 
     this.randomList = randomList; 
    } 

    public void run(){ 

     String str = ""; 
     int temp = 0; 
     int k = 0; 
     boolean swapped = true; 

     //Sort the colors 
     while(swapped){ 
      swapped = false; 
      k ++; 
      for(int i = 0; i < randomList.length - k; i ++){ 
       if(randomList[i] > randomList[i+1]){ 
        temp = randomList[i]; 
        randomList[i] = randomList[i+1]; 
        randomList[i+1] = temp; 
        swapped = true; 
        for(int l = 0; l < randomList.length; l++){ 
         System.out.print(randomList[l] + ", "); 
        } 
        System.out.println(); 
        for(int j = 0; j < randomList.length; j++){ 
         list[j].setBackground(new java.awt.Color(randomList[j],randomList[j],255)); 
        } 
       } 
      } 
     } 
    } 
} 
+1

認爲後臺線程。認爲SwingWorker。搜索這個細節。 –

回答

-1

的SwingWorker只能執行一次,而不是使用一個PropertyChangeListener以反映視圖的變化讓一個線程的實例,用一個Runnable類。 你正在使用視圖的線程來運行你的代碼,所以沒有其他人可以執行(重繪),直到完成。 在你的Runnable類中,你應該定義一個綁定到被修改對象的PropertyChangeSupport對象。並添加方法addPropertyChangeListener(然後在您的視圖中定義一個PropertyChangeListener),如下所示:

private PropertyChangeSupport mPcs = 
    new PropertyChangeSupport(this); 

public void setMouthWidth(int mw) { 
    int oldMouthWidth = mMouthWidth; 
    mMouthWidth = mw; 
    mPcs.firePropertyChange("mouthWidth", oldMouthWidth, mw); //the modification is "published" 
} 

public void 
addPropertyChangeListener(PropertyChangeListener listener) { 
    mPcs.addPropertyChangeListener(listener); 
} 

public void 
removePropertyChangeListener(PropertyChangeListener listener) { 
    mPcs.removePropertyChangeListener(listener); 
} 
+0

我看你在做什麼,但unfortunatley我沒有使用線程的經驗(我是一名初學Java的學生),所以我對你實際描述的內容仍然有點遺憾。 – daemor

+0

您使用實現Runnable接口的類創建一個Thread,該接口有一個名爲run()的方法,您可以在其中放置代碼或執行調用。一旦創建了線程,您需要調用start()方法來運行Runnable:D。線程t =新線程(Runnable) - >然後 - > t.start() – Typo

+0

所以你說我可以在運行方法中放置代碼,使顏色的按鈕?或者那是我將腳本分類的地方? – daemor