简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM