Search code examples
javamultithreadingjtextareaswingworker

How I append text to textarea with using swingworker class?


I want to append text in loop with swingworkerclass in java. for ex :

while(true)
{
     mytextarea.append("sometext");
     if(some_condition)
     {break;}
}

I want this with swingworker because I want to see every uptade on textarea. For this code I only see update when my proccess done.

I dont want swingworker samples for another situations. Please give me some code here.Thanks.


Solution

  • SwingWorker is not right here. Your code is not running in the EDT so you doesn´t see updates. You can use SwingUtilities.invokeLater(...) to execute your code in the EDT. But do not execute the whole while-loop in the EDT because this will block it and no updates / events (repaints, Mouseclicks). Here is a simply code-example:

        while(true) {
            SwingUtilities.invokeLater(new Runnable{
                public void run() {
                    textfield.setText(....);
                }
             });
             if(condition) break;
         }
    

    For more Information look at http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html or this book: http://filthyrichclients.org