Separate Logic Thread From Event Dispatch Thread

不打扰是莪最后的温柔 提交于 2019-12-04 02:49:42

This is how it can look like. You'll need to call the following code somewhere in EDT or through Swing Timer. I'm assuming here that your "huge" task will need to update a text field, but it can be any other UI control as well. All of that, just to demonstrate an idea. Do not treat it as a tested code.

//javax.swing.JTextField jfield; The field that needs to be updated. Take it from your Panel
String text = ""; // just a place holder
Object params [] = new Object []{jfield, text}; 
HugeTaskRunner ht = new HugeTaskRunner(params, new CallBack());

HugeTaskRunner is derived from AbstractTaskRunner, which looks like follows:

public abstract class AbstractTaskRunner extends Thread {


CallBack callBack = null;
Object [] params = new Object[0];

public AbstractTaskRunner (Object [] params, CallBack callBack) {
    this.params = params;
    this.callBack = callBack;

}
public abstract void doTask ();
@Override
public void run() {
    doTask();
    if (callBack != null) {
        callBack.doCall(new Object[]{"DONE"});
    }
}

}

HugeTaskRunner:

public class HugeTaskRunner extends AbstractTaskRunner {

public HugeTaskRunner(Object[] params, CallBack callBack) {
    super(params, callBack);
    // TODO Auto-generated constructor stub
}

@Override
public void doTask() {
    // HERE YOU'LL HAVE TO DO SOME HUGE TASK ACTIONS
    // THEN YOU'LL NEED TO CALL callBack.doCall(params) to update GUI 
    String newText = "Image #1 has been loaded";
    params[params.length -1] = newText; // assuming that the last param is for updated text
    callBack.doCall(params);

}

}

CallBack class:

public class CallBack {
public void doCall (Object [] params) {
    javax.swing.SwingUtilities.invokeLater(new GUIUpdater(params, null));
}
}

GUIUpdater class:

public class GUIUpdater extends AbstractTaskRunner {

public GUIUpdater(Object[] params, CallBack callBack) {
    super(params, callBack);
}

@Override
public void doTask() {
    // UPDATE YOUR GUI HERE TAKING Swing UI objects from params, e.g.
    if (params.length == 1 && params[0].equals("DONE")) {
        // HUGE TASK IS COMPLETED, DO SOMETHING IF YOU NEED TO
    }
    else if (params.length == 2) { // It's a request to update GUI
        javax.swing.JTextField txt = (javax.swing.JTextField) this.params[0];
        txt.setText((String)this.params[1]);
    }
    else {
        // UNKNOWN REQUEST
    }

}

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!