Search code examples
javaswingjtextfieldobserver-pattern

Java Swing GUI freezes - observer pattern


For a program I am creating I have used the observer pattern, yet whilst my Observable sends data almost constantly, simulated with a loop here because the actual code is hooked up to a device and measures the data, my update(); method runs as it should but swing doesn't.

Swing only updates the JTextField AFTER the loop has finished, yet when I use System.out.println() it iterates nicely each update.

Observable code:

public void collectData()
{

    for(int i = 0; i < 10; i++)
    {
        currRandom = (Math.random() * 10);
        for(Observer o : observers)
        {
            notify(o);
        }

    }
}

Observer (SWING) code:

public void update()
{
    jRecievedData.setText(jRecievedData.getText() + "\n" + Double.toString(PVC.pc.getCurr()));
    jlAverage.setText("Average: " + PVC.getAverage());
    jlMin.setText("Minimum: " + PVC.getMin());
    jlMax.setText("Maximum: "+ PVC.getMax());

    // setText updates slow
}

Any help would be greatly appreciated! (I have the feeling this is going to be a threading problem , but I'm not sure and if it is, I still don't know how to do that with swing)


Solution

  • Instead of looping through your observers explicitly, let Observable do it, as shown here.

    this.setChanged();
    this.notifyObservers();
    

    Also, verify that you are not blocking the event dispatch thread. If so, consider using SwingWorker, which greatly simplifies Swing threading.