2

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)

nbro
  • 15,395
  • 32
  • 113
  • 196
Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49

1 Answers1

3

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    Thank you, I have used SwingWorker and once I had figured out how to get that working with my pattern mess it worked like a charm! – Dylan Meeus Oct 27 '13 at 01:59