Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my JTextArea not updating?

I have code as follows:

class SimplifiedClass extends JApplet {

    private JTextArea outputText;
    // Lots of methods
    public void DoEverything() {
        String output = "";
        for(int i = 0; i <= 10; i++) {
            output += TaskObject.someLongTask(i);
            outputText.setText(output);
        }
    }
}

However, instead of updating the text area after each iteration of the loop when setText is called, it appears to only update the text when all the runs of the task are done. Why does this happen, and how can I resolve it?

like image 969
Macha Avatar asked Jul 21 '11 10:07

Macha


2 Answers

private JTextArea outputText = new JTextArea();

public void DoEverything() {
    String output = "";
    for(int i = 0; i <= 10; i++) {
        output += TaskObject.someLongTask(i);
        appendNewText(output);
    }
}

public void appendNewText(String txt) {
  SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        outputText.setText(outputText.getText + txt);
       //outputText.setText(outputText.getText + "\n"+ txt); Windows LineSeparator
     }
  });
}
like image 65
mKorbel Avatar answered Sep 20 '22 15:09

mKorbel


You're probably using the Swing thread which is waiting for your code to execute before it can update the UI. Try using a separate thread for that loop.

public void DoEverything() {
  SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      String output = "";
      for(int i = 0; i <= 10; i++) {
        output += TaskObject.someLongTask(i);
        outputText.setText(output);
      }
    }
  });
}
like image 34
Mika Tähtinen Avatar answered Sep 24 '22 15:09

Mika Tähtinen