java - 如何将SwingWorker的publish委托(delegate)给其他方法

标签 java swingworker

我的“问题”可以用以下描述。假设我们有一个密集的进程,我们希望在后台运行它并让它更新一个 Swing JProgress 条。解决方案很简单:

import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;


/**
 * @author Savvas Dalkitsis
 */
public class Test {

    public static void main(String[] args) {
        final JProgressBar progressBar = new JProgressBar(0,99);
        SwingWorker<Void, Integer> w = new SwingWorker<Void, Integer>(){

            @Override
            protected void process(List<Integer> chunks) {
                progressBar.setValue(chunks.get(chunks.size()-1));
            }

            @Override
            protected Void doInBackground() throws Exception {

                for (int i=0;i<100;i++) {
                    publish(i);
                    Thread.sleep(300);
                }

                return null;
            }

        };
        w.execute();
        JOptionPane.showOptionDialog(null,
                new Object[] { "Process", progressBar }, "Process",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, null, null);
    }

}

现在假设我有各种需要很长时间的方法。例如,我们有一个从服务器下载文件的方法。或者另一个上传到服务器的。或者任何真的。将发布方法委托(delegate)给这些方法以便它们可以适本地更新 GUI 的正确方法是什么?

到目前为止我发现的是这个(例如假设方法“aMethod”驻留在其他一些包中):

import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;


/**
 * @author Savvas Dalkitsis
 */
public class Test {

    public static void main(String[] args) {
        final JProgressBar progressBar = new JProgressBar(0,99);
        SwingWorker<Void, Integer> w = new SwingWorker<Void, Integer>(){

            @Override
            protected void process(List<Integer> chunks) {
                progressBar.setValue(chunks.get(chunks.size()-1));
            }

            @SuppressWarnings("serial")
            @Override
            protected Void doInBackground() throws Exception {

                aMethod(new AbstractAction() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        publish((Integer)getValue("progress"));
                    }
                });

                return null;
            }

        };
        w.execute();
        JOptionPane.showOptionDialog(null,
                new Object[] { "Process", progressBar }, "Process",
                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, null, null);
    }

    public static void aMethod (Action action) {
        for (int i=0;i<100;i++) {
            action.putValue("progress", i);
            action.actionPerformed(null);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

它有效,但我知道它缺少一些东西。有什么想法吗?

最佳答案

(我正在更新我的答案以使其更加清晰和概括)

虽然您已经成功地分离了逻辑和表示,但它并没有以有助于代码重用的方式完成。 Java 的 PropertyChangeSupport通过实现 bound properties 可以很容易地将逻辑与表示分离,并得到一些实质性的重用。这个想法是使用事件处理程序而不是操作对象。

首先,将抽象概念化。后台工作需要间歇性的向GUI“喊出来”(发布),GUI需要监听。两个通用类将编纂这个想法:

/**
 * Wrapper for the background logic.
 *
 * <T> return type
 * <S> intermediary type (the "shout out")
 */
public static abstract class LoudCall<T, S> implements Callable<T> {

    private PropertyChangeSupport pcs;
    private S shout;

    public LoudCall() {
        pcs = new PropertyChangeSupport(this);
    }

    public void shoutOut(S s) {
        pcs.firePropertyChange("shoutOut", this.shout, 
                this.shout = s);
    }

    public void addListener(PropertyChangeListener listener) {
        pcs.addPropertyChangeListener(listener);
    }

    public void removeListener(PropertyChangeListener listener) {
        pcs.removePropertyChangeListener(listener);
    }

    @Override
    public abstract T call() throws Exception;
}

/**
 * Wrapper for the GUI listener.
 *
 * <T> return type
 * <S> intermediary type (the "shout out" to listen for)
 */
public static abstract class ListenerTask<T, S> extends SwingWorker<T, S> 
        implements PropertyChangeListener {

    private LoudCall<T, S> aMethod;

    public ListenerTask(LoudCall<T, S> aMethod) {
        this.aMethod = aMethod;
    }

    @Override
    protected T doInBackground() throws Exception {
        aMethod.addListener(this);
        return aMethod.call();
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        if ("shoutOut".equals(evt.getPropertyName())) {
            publish((S)evt.getNewValue());
        }
    }

    @Override
    protected abstract void process(List<S> chunks);
}

这些类可用于所有 Swing 小部件。对于 ProgressBar,“喊出来”将是一个 Integer,返回类型是 Void:

public class ProgressExample {  
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {

        // 1. setup the progress bar
        final JProgressBar progressBar = new JProgressBar(0, 99);

        // 2. Wrap the logic in a "Loud Call"
        LoudCall<Void, Integer> aMethod = new LoudCall<Void, Integer>() {
            @Override
            public Void call() throws Exception {
                for (int i = 0; i < 100; i++) {
                    // "i have an update for the GUI!"
                    shoutOut(i);
                    Thread.sleep(100);
                }
                return null;
            }
        };

        // 3. Run it with a "Listener Task"
        (new ListenerTask<Void, Integer>(aMethod) {
            @Override
            protected void process(List<Integer> chunks) {
                progressBar.setValue(chunks.get(chunks.size() - 1));
            }
        }).execute();

        // 4. show it off!
        JOptionPane.showOptionDialog(null,
            new Object[] { "Process", progressBar }, "Process",
            JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
            null, null, null
        );
    }
        });
    }
}

只有监听者需要知道有关 GUI 细节的任何信息,后台逻辑仍然可以控制发布(间接地,通过“喊叫”)。此代码更简洁、可读且可重用。

我意识到这个问题现在已经很老了,但希望它能对某人有所帮助!

关于java - 如何将SwingWorker的publish委托(delegate)给其他方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2908306/

相关文章:

java - @ResponseBody 使用 ArrayLists 序列化错误

java - 窗口 8 上的进度条卡住

java - 尽管我们从另一个线程更新 GUI 组件,但没有遇到任何 GUI 卡住问题

java - SwingWorker 更新多面板中的多个组合框

java - 使用java保存带有对话框的图像文件

installation - 需要安装 JRE 方面的帮助吗?

java - 使用 url android studio (Java) 设置壁纸

java - 在 Java 中单击时尝试删除屏幕上的对象不起作用

java - SwingWorker doInBackground() 不起作用

java - SwingWorker 完成后挂起 : Is it bad practise to start and run a thread pool from a SwingWorker?