2

How to ensure that a Swing GUI is kept in sync with an underlying data structure which may change at any time?

Let's assume that we have a data structure which is modified at any point of time, now I want my GUI, which shows the contents of the data structure, to reflect these changes automatically. How do I keep them in sync?

I'm trying to implement a contact Book here using a HashMap to store the contacts. The GUI displays the contents of the the contact book.

In class ContactBook, I have the map along with methods to add or remove the entries.

GUI initially loads the contents from the contact book. But when the hashMap is modified I want the GUI to be updated.

ravisvi
  • 149
  • 2
  • 9
  • 4
    Take a look at the [observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) – Brian Jul 08 '13 at 15:10
  • 2
    It depends if the one can listen to the data structure for changes. If so, if the database can notify you of changes, then yes, an observer pattern would work well. Otherwise you may be forced to poll the data structure. – Hovercraft Full Of Eels Jul 08 '13 at 15:12
  • 2
    What is changing the data structure, and how is it obtained by the GUI? – Andrew Thompson Jul 08 '13 at 15:15

2 Answers2

1
  • Give the ContactBook class, your model, a SwingPropertyChangeSupport object that is initialized with this.
  • Give the same class add and remove PropertyChangeListener methods that pass the listener to the support object.
  • In any method of ContactBook that changes the data, notify the listeners by firing the support object.
  • Have your GUI add a PropertyChangeListener to the model that allows it to respond to notifications.

For example:

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Thank you all for the answers and advice, I went ahead and used Guava EventBus, to notify the GUI to update.

ravisvi
  • 149
  • 2
  • 9