2011-03-26 109 views
1

我使用這個代碼實現多線程:如何實現多線程的JFrame的

class Progress extends JFrame implements Runnable { 
    Thread t; 
JProgressBar current; 
JTextArea out; 
JButton find; 
Thread runner; 
JFrame tframe; 
int num = 0; 

public Progress() { 
    t=new Thread(this,"Thread1"); 
    t.start(); 


} 
public void run() 
{ 
     tframe=new JFrame("Please wait"); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JPanel pane = new JPanel(); 

    pane.setLayout(new FlowLayout()); 
    current = new JProgressBar(); 
    //current.setValue(0); 
    current.setStringPainted(true); 
    current.setIndeterminate(true); 

    pane.add(current); 
    setContentPane(pane); 
    tframe.add(pane); 
    tframe.pack(); 
    tframe.setSize(300,100); 

    tframe.setResizable(false); 
    tframe.setAlwaysOnTop(true); 
    tframe.setLocation(300,300); 
    tframe.setVisible(true); 

} 
public void stop() 
{ 
    tframe.dispose(); 
} 

,當我需要啓動線程,我使用

 Progress t=new Progress(); . 

這顯示幀,並停止我使用t.stop();但是,我沒有得到所需的多線程效果。只顯示框架,而不是無生命的進度條。請注意,當用作單個線程時會顯示進度條;

這裏必須做些什麼?請幫忙,提前致謝

+0

爲了更快得到更好的幫助,請發佈[SSCCE](http://pscode.org/sscce.html)。我猜測所有源代碼都需要成爲SSCCE,是一個'main(String [])'方法和一些導入。 – 2011-03-26 07:13:27

回答

2

這是完全錯誤的。 Swing是單線程的。每個與swing組件的交互都必須在單個事件派發線程中完成。仔細閱讀this tutorial。它解釋了在使用多線程時必須完成的事情。另請閱讀this tutorial on progress bars and progress monitors

+0

-1:我是一個非常稀疏的downvoter(超過1100票中只有27票),但你的回答是嚴重誤導。 「這是完全錯誤的」這並非完全錯誤。可能存在缺陷,但並不完全錯誤。 「Swing是單線程的」我不知道從哪裏開始。這只是...錯了! Swing本質上是多線程的,支持許多類型的其他非必需線程。 – corsiKa 2011-03-26 07:32:06

+1

從http://download.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading:「除非另有說明,否則必須在事件中訪問所有Swing組件和相關類調度線程「。我沒有說別的,我將OP指向官方的swing教程,講解如何使用多線程。關於這個問題所涉及的多線程方面,OP的代碼確實是完全錯誤的。這可能聽起來很刺耳,但這是事實。我的回答完全沒有誤導,因爲它將OP引向適當的文檔。 – 2011-03-26 07:46:07