views:

135

answers:

2

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);    
    ...
+2  A: 

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)

aperkins
The `process()` method of `SwingWorker` runs on the EDT, so no there's need to use `invokeLater()`: http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html
trashgod
The JScrollPane is updated by a background task in another class, or from the JFrame that it lives in. Writing to the JScrollPane seems ot be responsive, but the background task has a lot to do, which is why it is needed.
JackN
@trashgod you are correct - I forgot about that. I was thinking of a normal thread.
aperkins
@JackN Swing is not thread safe - if you update from a thread other than the UI thread, you can cause problems in the UI. That is why I am recommending either a SwingWorkerThread or SwingUtilities.invokeLater calls. We have had to do just what you are talking about - have the work run in a background thread and update the UI when it is finished - and this is considered the appropriate solution to this problem.
aperkins
+2  A: 

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.

trashgod
I had never read that part - huh. I have always avoided doing UI updates except on the event dispatch thread as a matter of principle, and to make sure I never hit a problem. Good to know about append though.
aperkins