2013-08-06 18 views
0

我有一個JNI函數,可能需要一段時間才能完成,並且我想要一個JProgress欄處於不確定模式,並在完成該函數時運行。我已閱讀了Oracle提供的教程,但其教程的性質似乎並沒有幫助我理解如何去做。我意識到我應該在後臺線程中運行這個函數,但我不太確定如何去做。JProgress Bar不確定模式不更新

這是相關的代碼。我有一個按鈕(runButton),將調用函數,mainCpp(),按下時:

public class Foo extends javax.swing.JFrame 
         implements ActionListener, 
            PropertyChangeListener{ 

    @Override 
    public void actionPerformed(ActionEvent ae){ 
     //Don't know what goes here, I don't think it is necessary though because I do not intend to use a determinate progress bar 
    } 

    @Override 
    public void propertyChange(PropertyChangeEvent pce){ 
     //I don't intend on using an determinate progress bar, so I also do not think this is necassary 
    } 

class Task extends SwingWorker<Void, Void>{ 

    @Override 
    public Void doInBackground{ 
     Foo t = new Foo(); 
     t.mainCpp(); 

     System.out.println("Done..."); 
    } 
    return null; 
} 

/*JNI Function Declaration*/ 
public native int mainCpp(); //The original function takes arguments, but I have ommitted them for simplicity. If they are part of the problem, I can put them back in. 

...//some codes about GUI 

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) { 

    ProgressBar.setIndeterminate(true); 
    Task task = new Task(); 
    task.execute();  
    ProgressBar.setIndeterminate(false); 

} 


/*Declarations*/ 
private javax.swing.JButton runButton; 
} 

任何幫助,將不勝感激。

編輯:編輯嘗試做什麼kiheru建議,但仍然無法正常工作。

+0

你在doInBackround()中運行它的假設是正確的。 SwindWorkers只需要一個'execute()'調用就可以開始運行,所以如果你事先準備好工作者,你可以在按鈕操作中調用它。或者,您可以創建SwingWorker並執行該操作。 – kiheru

+0

你能否詳細說明你的意思是「提前準備工人」? –

回答

0

假設你有一個這樣的的SwingWorker:

class Task extends SwingWorker<Void, Void>{ 
    @Override 
    public Void doInBackground() { 
     // I'm not sure of the code snippets if you are already in a 
     // Foo instance; if this is internal to Foo then you obviously do 
     // not need to create another instance, but just call mainCpp(). 
     Foo t = new Foo(); 
     t.mainCpp(); 
     return null; 
    } 

    @Override 
    public void done() 
     // Stop progress bar, etc 
     ... 
    } 
} 

你可以保留一個實例中包含的對象的字段,然後用它的工作是這樣的:

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) { 
    // Start progress bar, disable the button, etc. 
    ... 
    // Task task has been created earlier, maybe in the constructor 
    task.execute(); 
} 

,或者你可以創建一個工作人員:

private void runButtonActionPerformed(java.awt.event.ActionEvent evt) { 
    // Start progress bar, disable the button, etc. 
    ... 
    new Task().execute(); 
} 
+0

我相信這是我試圖(檢查我的編輯),但進度欄不動。 –

+0

@SeanSenWang不要停止runButtonActionPerformed()中的進度條 - 這將立即完成。而是在SwingWorker的'done()'中做。還要注意關於'new Foo()'的註釋(不應該破壞任何東西,但可能不需要) – kiheru

+0

啊,我需要在action事件之外設置'indeterminate(false)'。非常感謝你! –