我有一个JFrame和以下组件.
JButton = jButton1 Progress Bar = progressBar及其公共静态JLabel = status及其公共静态
按钮单击时,执行不同的语句.我希望在每个语句后更新我的进度条.这是我的代码
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Task pbu = new Task(25, "Step 1....");
pbu.execute();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
pbu = new Task(50, "Step 2....");
pbu.execute();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
pbu = new Task(75, "Step 3....");
pbu.execute();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
pbu = new Task(100, "Done");
pbu.execute();
}
Run Code Online (Sandbox Code Playgroud)
这是我使用SwingWorker扩展的Task类
public class Task extends SwingWorker{
private int progress;
private String stat;
public Task(int pr, String st) {
progress = pr;
stat = st;
}
@Override
protected Object doInBackground() throws Exception {
NewJFrame1.progressBar.setValue(progress);
NewJFrame1.status.setValue(stat);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
不知道怎样才能解决这个问题?
@Override
protected Object doInBackground() throws Exception {
NewJFrame1.progressBar.setValue(progress);
NewJFrame1.status.setValue(stat);
return null;
}
Run Code Online (Sandbox Code Playgroud)
您不希望从Swing线程更新GUI组件. SwingWorker提供了用于在事件调度线程上执行操作的挂钩,这就是它的设计目的.publish从增量更新调用方法doInBackground并覆盖process到详细信息.或者,如果您只需要在完成后更新GUI,请覆盖该done()方法.
一个非常简单的例子:
//...in some concrete implementation of SwingWorker<Void, Integer>
protected Void doInBackground() throws Exception {
//do 10% of task
doLongOp();
publish(10);
//do another 20% of task
doAnotherLongOp();
publish(20);
return null;
}
protected void process(List<Integer> pieces) {
for (Integer percent : pieces ) {
progressBar.setValue(progressBar.getValue() + percent);
}
}
Run Code Online (Sandbox Code Playgroud)
@mKorbel提出了一个很好的观点,为了使上述工作,它需要扩展SwingWorker<Void, Integer>... Void作为整体返回值类型(在这种情况下表示没有返回值)并且Integer是增量更新的类型.
如果工人产生实际的最终结果(将被检索get()),则可以使用该类型代替Void.我遗漏了这些细节,因为我没有包括课程声明.
| 归档时间: |
|
| 查看次数: |
6792 次 |
| 最近记录: |