2013-08-06 39 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)'。非常感谢你! –