In my editor I have a LayersManager and a LayersView class. The LayersManager class holds all the layers that the user is currently using (think Photoshop layers). The LayersView is a JPanel that lists the layers contained in the LayersManager.
What I would like to do is to update the LayersView JPanel by adding or removing a LayerComponent from the JPanel’s container whenever the add(Layer) or remove(Layer) methods are called from the LayersManager.
In other words, what I want is a reverse ChangeListener where whenever a change is made in the LayersManager, the LayersView is automatically contacted, adds or removes a LayerComponent from it’s container and invalidates itself.
So my questions are: Is there a standard built in listener to do this? Are listeners the right way to go? Or should I just include a reference to the LayersView inside the LayersManager and manually call the required methods (I suspect this is bad design)? I can’t think of a nice (design wise) way of implementing my own listeners.
Any help appreciated!
You can use the Observer pattern. Java has built-in support for this pattern in the form of the Observable and Observer classes.
Basically, your
LayersManagerwould extendObservableand yourLayersViewwould implementObserver. You would then calladdObserveron theLayersManagerand pass in yourLayersView.Once that is in place you can call the following methods on your
LayersManagerwhenever a change occurs that you want to notify theLayersViewabout:The
notifyObserversmethod can take an object as a parameter if you want theObserverlisteners to receive some data. OncenotifyObserversis called, yourLayersViewwill have theupdatemethod called.