I want a swing text area to be updated during my program running. My program does a lot of complex file processing.
In my program I have a text area that I can update using writeText("text") for example (method shown below). In the writeText() method I do this with a simple textArea.append() with a swing worker but it doesn't update the text until after all the processing happens in my main class. How do I make this work properly by actually updating the text area in real time like how System.out.println() can send text to the console at any time.
public static void writeText(String text) {
System.out.println("SWING WORKER");
worker = new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
publish(" " + text + "\n");
return null;
}
@Override
protected void process(List<String> chunks) {
textArea.append(chunks.get(chunks.size() - 1));
frame.repaint();
}
@Override
protected void done() {
//textArea.append(" test done\n");
}
};
worker.execute();
}
I have tried threading and now using swing worker but both attempts only updated the text after the main complex method ran (copying and renaming and subimaging out files that kinda stuff, basically I just want the text area to be updated with an append() so the user knows whats happening while the program runs)
It sounds like something else is blocking the main thread, but it's impossible to know what without more context.
It's important that what ever long running work you are doing is done within the
doBackgroundmethod, so as to prevent the event dispatching thread from been blocked (and unable to process new events, including paint request).The following example simply reads a text file, line by line, and with a random delay, publishes the line, so it can be added to the
JTextAreaYou should also be sure to read through Worker Threads and SwingWorker