How is messaging between Java classes best accomplished?

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);    
    ...

Answers


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)


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.


Need Your Help

Receiving structs through TCP c#

c# c tcp struct

This post is directly related to an earlier post I made

Why is my Rails app trying to send an email in the development environment?

ruby-on-rails actionmailer postfix-mta

I have followed the instructions on this page to get started on ActionMailer. After I tested that it can send emails from a Gmail account, I reset perform_deliveries option to false and sent a few ...