0

您如何获得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); 
     } 
   }
4

1 回答 1

2

我建议您创建一个模型对象,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);
    }
}
于 2012-04-27T16:18:02.590 回答