ravisvi
ravisvi

Reputation: 159

Ensure that a Swing GUI is kept in sync with an underlying data structure

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.

Upvotes: 2

Views: 229

Answers (2)

ravisvi
ravisvi

Reputation: 159

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

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  • 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:

Upvotes: 1

Related Questions