1

我有一個JFrame與進度條和我的代碼應該在後臺運行它顯示進度條中的進度。java中的多線程,我想同時執行UI和代碼

我在我的Progressbar類中實現了runnable並啓動了線程。但是進度條框架沒有顯示完整......並且在我的代碼完全執行後,即在主線程關閉後它卡住並顯示完整。

我知道這是一些基本的錯誤。

public class ProgressScriptUI extends JFrame implements Runnable{ 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     setTitle("Progressing to Generate DDL Scripts"); 
     setBounds(400, 250, 850, 400); 
     getContentPane().setLayout(null); 
     JProgressBar progressBar= new JProgressBar(0,100); 
     progressBar.setBounds(200, 100, 500, 20); 
     add(progressBar); 
     setVisible(true); 

     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

} 

//I am calling the below code in some other class 
ProgressScriptUI progress = new ProgressScriptUI(); 


Thread uiThread = new Thread(progress);            
uiThread.start(); 
oracleValidateOLDorNEW.execute(); //Code that I need to call in back ground 
+1

向我們展示一些代碼。 – Manish 2013-04-29 06:56:51

+0

公共類ProgressScriptUI延伸的JFrame實現Runnable { \t \t @Override \t公共無效的run(){ \t \t // TODO自動生成方法存根 \t \t的setTitle( 「進展爲生成DDL腳本」); \t \t setBounds(400,250,850,400); \t \t getContentPane()。setLayout(null); \t \t JProgressBar progressBar = new JProgressBar(0,100); \t \t progressBar.setBounds(200,100,500,20); \t \t add(progressBar); \t \t setVisible(true); \t \t \t \t setVisible(true); \t \t setDefaultCloseOperation(EXIT_ON_CLOSE); \t} \t \t } – 2013-04-29 06:59:57

+0

您可以編輯您的文章並粘貼代碼 – sanbhat 2013-04-29 07:00:37

回答

5

我相信你正在使用Swing進行UI。對於任何長時間運行的任務使用SwingWorkers

6

所有UI代碼必須在事件分派線程的上下文中執行。這使得在保持UI更新的同時在後臺執行工作有點棘手。

請查看Concurrency in Swing以獲取解決方案的建議和建議。

也許最簡單的辦法是使用一個SwingWorker使其同步回至美國東部時間以及進度回調

你可以看看

由於一些例子....