Updating jTextArea in while loop

1.2k views Asked by At

I am having a problem writing/updating the textarea. I am getting a value from the readtemp function, and i can see the result after calling the system out function, but nothing appears in the Textarea. What could be the problem?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    URL temp;
    try 
    {
            temp = new URL("http://192.168.1.25/status.xml");
            while (true)
            {
                System.out.println("Homerseklet: " + readtemp(temp));
                jTextArea1.append(readtemp(temp));
            }                   
    } 
    catch (MalformedURLException ex) 
    {
        Logger.getLogger(Download.class.getName()).log(Level.SEVERE, null, ex);
    }
}                                        
4

There are 4 answers

0
Rahel Lüthy On BEST ANSWER

Correction: This won't help since the infinite loop will still block the EDT forever... Nevermind!

Your while loop is a really bad idea, but if you insist, you can at least give the EDT a chance to update the UI by dispatching your append asynchronously:

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        jTextArea1.append(readtemp(temp));    
    }
});
0
Kristjan Veskimäe On

Are you doing IO and graphics in separate threads as it's supposed to be done? You should only do updating UI in the event dispatch thread, so when retrieving results from external place has completed you submit the update to event dispatch thread.

0
Krzysztof Kosmatka On

The problem exists because of the infinite loop while (true). Because the function jButton1ActionPerformed never ends, Swing has no chance to rerender the jTextArea1 component (I assume that this method is called in AWT Thread).

2
bratkartoffel On

As mentioned in the previous answers it's a bad idea to handle long-running operations inside the swing thread. As a solution i'd replace your "textfield.append()"- Line with the following code snippet:

Java 8 way:

SwingUtilities.invokeLater(() -> jTextArea1.append(readtemp(temp)));

Pre-Java 8:

 SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        jTextArea1.append(readtemp(temp));
    }
 });

Source and some explanation: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html