【问题标题】:How to pass the message from working thread to GUI in java如何在java中将消息从工作线程传递到GUI
【发布时间】:2011-10-31 04:22:56
【问题描述】:

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

【问题讨论】:

  • 指的是哪个 GUI 库?它有所作为。

标签: java


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以使用 SwingWorker 类,它旨在解决这种情况: http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

    【讨论】:

      【解决方案3】:

      发送事件。见this tutorial

      【讨论】:

        【解决方案4】:

        您必须使用SwingUtilities.invokeLater,因为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();
            }
        }
        

        【讨论】:

          【解决方案5】:

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

          可以在此处找到有关此类设计的详细说明: Is there a recommended way to use the Observer pattern in MVP using GWT?

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

          【讨论】:

            猜你喜欢
            • 2011-11-18
            • 1970-01-01
            • 2021-08-06
            • 1970-01-01
            • 2019-09-16
            • 1970-01-01
            • 1970-01-01
            • 2021-03-27
            • 2015-07-31
            相关资源
            最近更新 更多