2010-08-06 71 views
1

我正在嘗試使用線程在後臺運行一個簡單的操作並更新UI。 這裏就是我想要做的事:Java線程問題 - 更新GUI

  1. 上點擊一個按鈕,顯示popupjframe一條消息「插入到數據庫」
  2. 創建一個新的線程插入條目1000到數據庫中。
  3. 插入的條目時,我希望popupjframe消失和上點擊是按鈕,顯示與是一個的JOptionPane,沒有按鈕
  4. 我想顯示與報告的另一幀/約插入過程
細節

這裏是我的代碼:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
//display popupframe first 

jFrame1.pack(); 
jFrame1.setVisible(true); 
jFrame1.setLocationRelativeTo(getFrame()); 
Thread queryThread = new Thread() { 
public void run() { 
runQueries(); 
}}; 
queryThread.start(); 
} 

//runqueries method inserts into DB

private void runQueries() { 
for (int i = 0; i <= 50000; i++) { 
insertintoDB(); 
updateProgress(i); 
} 
} 

//update the popupjframe 
private void updateProgress(final int queryNo) { 
SwingUtilities.invokeLater(new Runnable() { 
public void run() { 
if (queryNo == 50000) { //means insertion is done 
jFrame1.setVisible(false); 

int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION); 

if (n == 1) { //NO option was selected 
return;} 
else 
//display another popupframe with details/report of inserting process 
}}); 
} 
  1. 我的方法是否正確?
  2. 如何以及何時我停止/中斷「queryThread」?
  3. 如果我在runqueries方法本身中創建popupjframe(在for循環之後)並顯示joptionpane?

在此先感謝。

+0

在你runQueries()方法,您呼叫的UpdateProgress()50000次,每次創建一個新的線程,而只有最後一個一個人需要做任何有用的工作。它可能並不重要,但它是不必要的開銷,並且最好是誤導性的代碼。 ILMTitan是正確的:SwingWorker是去這裏的正確途徑。 – 2010-08-06 18:53:48

回答

4

查看SwingWorker的文檔。它完全正是你想要做的。創建一個子類,然後從doInBackground()調用runQueries,然後在done()中執行你的可運行子程序(減去if queryNo檢查)。如果你不使用java 1.6,這個類有第三方版本。

class DbSwingWorker extends SwingWorker<Void, Integer> { 

    @Override 
    protected Void doInBackground() throws Exception { 
     for (int i = 0; i <= 50000; i++) { 
      insertintoDB(); 
      publish(i); //if you want to do some sort of progress update 
     } 
     return null; 
    } 

    @Override 
    protected void done() { 
     int n = JOptionPane.showConfirmDialog(getFrame(), menuBar, null, JOptionPane.YES_NO_OPTION); 

     if (n == 1) { //NO option was selected 
      return; 
     } else { 
      //display another popupframe with details/report of inserting process 

     } 
    } 
} 

原來,非1.6版本可以在這裏找到:https://swingworker.dev.java.net/

+0

另請參閱。 – 2010-08-06 18:55:49