Java 类之间的消息传递如何最好地完成?

发布于 2024-09-24 08:24:22 字数 644 浏览 0 评论 0原文

我有多个类和线程需要写入 Java Swing JScrollPane。在Android/Eclipse环境中我使用了android.os.Message。 NetBeans/Windows 环境中是否有类似的东西?这是我想从以下位置发送消息的位置:

public class PrintStatusTask extends Thread {
    PrintStatusTask(String name) {
        this.name = name;
    }
    private void sendMessage(String s) {
        // TODO: send message to jTextArea
    }
    public void run() {
        ...
        sendMessage("Any message");
        ...

这是从 JFrame 所在的 JScrollPane 写入 JScrollPane 的示例:

public class Controller extends javax.swing.JFrame implements Observer {
    ...
    jTextArea.append(s);    
    ...

I have multiple classes and threads that need to write to a Java Swing JScrollPane. In the Android/Eclipse environment I used android.os.Message. Is there something similar in the NetBeans/Windows environment? Here is where I would like to send the message from:

public class PrintStatusTask extends Thread {
    PrintStatusTask(String name) {
        this.name = name;
    }
    private void sendMessage(String s) {
        // TODO: send message to jTextArea
    }
    public void run() {
        ...
        sendMessage("Any message");
        ...

Here is an example of writing to the JScrollPane from the JFrame it lives in:

public class Controller extends javax.swing.JFrame implements Observer {
    ...
    jTextArea.append(s);    
    ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

病毒体 2024-10-01 08:24:22

如果您要写入窗格本身(即更改视图上的数据),那么最好的方法是使用 swing 工作线程,并稍后执行它:(

SwingUtilities.executeLater(myThread);

语法可能略有偏差 - 我是从内存中执行的)

If you are writing to the pane itself (i.e. changing the data on the view) then the best way is to use a swing worker thread, and execute it later:

SwingUtilities.executeLater(myThread);

(Syntax might be slightly off - I am doing it from memory)

墨离汐 2024-10-01 08:24:22

我会赞同aperkins建议使用SwingWorker 作为更强大的通用解决方案。

append():“此方法是线程安全的,尽管大多数 Swing 方法都不是。”这是使用另一个线程的方法的简单示例

I'll second aperkins' suggestion to use SwingWorker as a more robust, general purpose solution.

In the particular case of append(): "This method is thread safe, although most Swing methods are not." Here is a simple example of using the method from another thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文