gpt4 book ai didi

java - 如何获取当前正在运行代码的 SwingWorker?

转载 作者:行者123 更新时间:2023-12-02 07:49:50 26 4
gpt4 key购买 nike

如何获取代码当前运行的SwingWorker?您可以使用 Thread.currentThread() 来获取 Thread 实例,但我需要 SwingWorker 实例。

代码来自评论

private static void loadFeaturesForSym(final SeqSymmetry optimized_sym, 
final GenericFeature feature)
throws OutOfMemoryError {
final CThreadWorker<Boolean, Object> worker =
new CThreadWorker<Boolean, Object>("Loading feature " + feature.featureName) {
@Override
protected Boolean runInBackground() {
try {
return loadFeaturesForSym(feature, optimized_sym);
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
};
ThreadHandler.getThreadHandler().execute(feature, worker);
}
}

最佳答案

我建议您创建一个模型对象,SwingWorker 可以监听该模型对象并将这些更新发送到发布和处理方法。您的其他对象不应该了解 SwingWorker,它们应该只了解自己的进度并将其发布给任何想听的人。这就是所谓的解耦。这是实现这一目标的一个想法,它使用接近 MVC 的东西。我没有编译这段代码,但它有助于解释我在说什么。

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class ProcessStatus {
public static final String PROGRESS = "Progress";

private PropertyChangeSupport propertyChangeSupport;

private int progress = 0;

public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}

protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
}

public void setProgress(int progress) {
int oldProgress = progress;
this.progress = progress;
firePropertyChange(PROGRESS, oldProgress, progress);
}

public int getProgress() {
return progress;
}
}

public class SomeWorker extends SwingWorker implements PropertyChangeListener {
public void doInBackground() {
ProcessStatus status = new ProcessStatus();
status.addPropertyChangeListener(this);
ProcessorThingy processor = new ProcessorThingy(status);
processor.doStuff();
}

public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(ProcessStatus.PROGRESS)) {
publish((Integer) evt.getNewValue());
}
}
}

public class ProcessorThingy {
private ProcessStatus status;

public ProcessorThingy(ProcessStatus status) {
this.status = status;
}

public void doStuff() {
//stuff part 1
status.setProgress(10);
//stuff part 2
status.setProgress(50);
//stuff part 3
status.setProgress(100);
}
}

关于java - 如何获取当前正在运行代码的 SwingWorker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com