问题描述
如果我在 doInBackground() 中有一个属于其他类的方法,是否可以根据外部类的其他方法中发生的更改来设置 setProgess()?
If I had a method inside the doInBackground() that belongs to other class is it possible to set setProgess() based on changes that happen in that other method of an outside class?
推荐答案
你说:
但是当我将 setProgess() 放在另一个类的方法中时,它告诉我需要创建该方法.
这与 SwingWorker 无关,而与基本的 Java 相关.没有类可以调用另一个类的实例(非静态)方法,除非在类的有效实例上这样做.要使您的代码工作,其他"方法必须在 SwingWorker 的实例上调用 setProgress(...)
,因此您必须将 SwingWorker 的引用传递给该其他类.于是把SwingWorker(SwingWorker里面的this
)传入另一个类,然后就可以愉快的调用它的方法了.同样,这与线程、Swing 或 SwingWorkers 无关,而是 Java 的基本面包和黄油.
This has nothing to do with SwingWorker and all to do with basic Java. No class can call another classes instance (non-static) methods without doing so on a valid instance of the class. For your code to work, the "other" method must call setProgress(...)
on an instance of the SwingWorker, and so you must pass a reference of the SwingWorker to that other class. So pass the SwingWorker (this
inside of the SwingWorker) into the other class, and then you can happily call its methods. Again, this has nothing to do with threading, Swing, or SwingWorkers, but rather is basic bread and butter Java.
由于 setProgress 是受保护的和最终的,您的 SwingWorker 将必须有一个其他类可以调用的公共方法,并且在此方法中,SwingWorker 将需要调用自己的 setProgress(...)
方法.
since setProgress is protected and final, your SwingWorker will have to have a public method that the other class can call, and in this method the SwingWorker will need to call its own setProgress(...)
method.
例如
MyWorker 类
public class MyWorker extends SwingWorker<Integer, Integer> {
private OtherClass otherClass;
public MyWorker() {
otherClass = new OtherClass(this);
}
@Override
protected Integer doInBackground() throws Exception {
otherClass.otherMethod();
return null;
}
// public method that exposes setProgress
public void publicSetProgress(int prog) {
setProgress(prog);
}
}
其他类:
class OtherClass {
MyWorker myWorker;
public OtherClass(MyWorker myWorker) {
this.myWorker = myWorker;
}
public void otherMethod() {
for (int i = 0; i < 100; i++) {
myWorker.publicSetProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {}
}
}
}
这篇关于java - 进度条 - 是否可以在 doInBackground() 方法之外使用进度条的 setProgess()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!