JProgress Bar Indeterminate模式未更新



我有一个JNI函数,它可能需要一段时间才能完成,我希望JProgress条在完成该函数时以不确定模式运行。我已经阅读了Oracle提供的教程,但它们的教程性质似乎并不能帮助我理解如何做到这一点。我意识到我应该在后台线程中运行这个函数,但我不太确定如何做到。

这是相关代码。我有一个按钮(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;
}

如有任何帮助,我们将不胜感激。

编辑:试图按照基赫鲁的建议进行编辑,但仍然不起作用。

假设你有一个像这样的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();
}

最新更新