Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中如何将消息从工作线程传递到GUI_Java - Fatal编程技术网

java中如何将消息从工作线程传递到GUI

java中如何将消息从工作线程传递到GUI,java,Java,如何在java中将消息从工作线程传递到GUI?我知道在Android中,这可以通过处理程序和消息类来实现。但是我想要Java中的同样东西,任何人都可以帮助我。 提前谢谢。 tm我认为最好的方法是对GUI组件使用EventBus和MVP设计。工作线程通过将事件发送到总线来触发事件,并且作为特定类型事件处理程序的演示者将收到关于该事件的通知 有关此类设计的详细说明,请参见: …尽管问题是关于GWT的,但答案适用于所有根据MVP设计的应用程序。您必须使用,因为Swing组件只能从事件调度线程访问 此

如何在java中将消息从工作线程传递到GUI?我知道在Android中,这可以通过处理程序和消息类来实现。但是我想要Java中的同样东西,任何人都可以帮助我。 提前谢谢。
tm

我认为最好的方法是对GUI组件使用EventBus和MVP设计。工作线程通过将事件发送到总线来触发事件,并且作为特定类型事件处理程序的演示者将收到关于该事件的通知

有关此类设计的详细说明,请参见:

…尽管问题是关于GWT的,但答案适用于所有根据MVP设计的应用程序。

您必须使用,因为Swing组件只能从事件调度线程访问

此方法的javadoc有一个指向Swing线程教程的链接。点击这个链接

下面是一个例子:

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();
    }
}

发送事件。请参见

您可以使用SwingWorker类,该类旨在解决这种情况:

我们在FrostWire上这样做,通过这个实用程序函数,我们可以检查您正在使用的runnable/线程是否已经从GUI线程调用

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

你指的是哪个GUI库?这很重要。