jacknad
jacknad

Reputation: 13739

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

Upvotes: 2

Views: 401

Answers (2)

trashgod
trashgod

Reputation: 205825

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.

Upvotes: 2

aperkins
aperkins

Reputation: 13124

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)

Upvotes: 2

Related Questions