Search code examples
javaswingoopjtextfieldobserver-pattern

Using OO Observer pattern without updating object from which change originated


I'm building an application which contains a GUI and a Model. I'm using the Observer pattern (using java's built in interfaces) to update the GUI when fields in the model are changed.

This is generally working fine, but I have a situation in which a particular String variable in the model (specifically the url of a file) can be changed by two separate JTextFields (swing) the contents of which actually reflects the value of the model variable in question.

The issue I am having comes from the fact that an change in one of these JTextFields needs to cause an update to the state of the model, and the contents of the other JTextField. My Model ensures that notifications are sent to observers only in the case that the state of the model has changed. However, the process by which JTextFields are modified involves blanking it's text content then reseting it.

Without going into too much detail, the upshot of this is that the update / notification process gets stuck in an infinte loop. I have temporarily hacked around this by setting aside the observer pattern for this particular problem, but I was wondering if anyone could suggest a neat way of ensuring that a particular component is not "updated" by a change which originated from the same component.

Any help appreciated.


Solution

  • As discussed in Java SE Application Design With MVC, this is one of several Issues With Application Design. The suggested approach relies on a PropertyChangeListener, illustrated here. The PropertyChangeEvent includes both old & new values for reference.