Dynamically refresh JTextArea as processing occurs? Dynamically refresh JTextArea as processing occurs? multithreading multithreading

Dynamically refresh JTextArea as processing occurs?


Try this:

jTextArea.update(jTextArea.getGraphics());


I ran into the same issue with my application. I had a "Run" button my application that performed some actions and outputted the results to a JTextArea. I had to call the method from a Thread. Here is what I did.

I have several radio buttons of actions that can be done, and then one "Run" button to execute that particular action. I have an action called Validate. So when I check that radio button and click the "Run" button, it calls the method validate(). So I first placed this method into an inner class that implemented Runnable

class ValidateThread implements Runnable {    public void run() {        validate();    }}

I then called this thread in the ActionListener of the "Run" button as so

runButton.addActionListener(new ActionListener() {    public void actionPerformed(ActionEvent ae) {        // Some code checked on some radio buttons        if(radioButton.isSelected()) {            if(radioButton.getText().equals("VALIDATE")) {               Runnable runnable = new ValidateThread();               Thread thread = new Thread(runnable);               thread.start();            }        }    }});

Voila! The output is now sent to the JTextArea.

Now, you will notice that the JTextArea will not scroll down with the text. So you need to set the caret position like

textArea.setCaretPosition(textArea.getText().length() - 1);

Now when the data is added to the JTextArea, it will always scroll down.


As others have said this requires multithreading. Have a look at Concurrency in Swing.

One solution would be to implement the processing using a SwingWorker. The doInBackground method would implement the processing and you would invoke the publish method with the String to be appended as the argument. Your SwingWorker would then override the process method to take a String argument and append it to the text area.