开发者

How to pass the message from working thread to GUI in java

How to pass the message from working thread to GUI in java? I know in Android this can be achieved through handlers and Messages Class. But I want the same thing in Java can any one help me. Thanks in advance. Ra开发者_C百科nganath.tm


You must use SwingUtilities.invokeLater, because Swing components must only be accessed from the event dispatch thread.

The javadoc of this method has a link to the Swing tutorial about threads. Follow this link.

Here's an example:

public class SwingWithThread {
    private JLabel label;

    // ...

    public void startBackgroundThread() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    // simulate some background work
                    Thread.sleep(5000L);
                }
                catch (InterruptedException e) {
                    // ignore
                }

                // update the label IN THE EDT!
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        label.setText("Background thread has stopped");
                    }
                });
            };
        };

        new Thread(r).start();
    }
}


I think that the best way to do so is to use EventBus & MVP design for your GUI components. "Working thread" fires event by sending it to bus, and Presenters which are handlers for particular type of event, are notified about it.

Nice description of such design can be found here: Is there a recommended way to use the Observer pattern in MVP using GWT?

...although question is about GWT answer is applicable to all applications designed according to MVP.


Send events. See this tutorial


We do it like this on FrostWire, through this utility function we can check if the runnable/thread you're using is being invoked already from the GUI thread

/**
 * InvokesLater if not already in the dispatch thread.
 */
public static void safeInvokeLater(Runnable runnable) {
    if (EventQueue.isDispatchThread()) {
        runnable.run();
    } else {
        SwingUtilities.invokeLater(runnable);
    }
}


You can use SwingWorker class, its designed to address this case: http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜