如何在Java中将消息从工作线程传递到GUI [英] How to pass the message from working thread to GUI in java

查看:50
本文介绍了如何在Java中将消息从工作线程传递到GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将消息从工作线程传递到Java中的GUI?我知道在Android中这可以通过处理程序和Messages类来实现.但是我希望Java中的同一件事可以帮助任何人.提前致谢.Ranganath.tm

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. Ranganath.tm

推荐答案

您必须使用

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

此方法的javadoc包含指向有关线程的Swing教程的链接.点击此链接.

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

这是一个例子:

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

这篇关于如何在Java中将消息从工作线程传递到GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆