Let's say I have a jframe class that contains a button and a label. Label displays number of times I've clicked the button. I created 2 objects of this class. Now, I want the first object to update both its own label, and the second object's label immediately as I press the button. How would I go about doing that? Is it possible to make a static variable and some kind of variable listener which would update the label on variable value change?
1 Answer
You may want to take a look at the Observer pattern.
You can attach two different observers, one for each label, to an Observable instance tied to the click event of your button. This way, each time you click the button, the two observers will be notified and will be able to change the value of the labels.
You can look in the Javadoc for the Observer interface and the Observable class or implements your own version of the pattern.
Hope I'm clear.
1 Comment
Hovercraft Full Of Eels
Great suggestion (1+). Swing is based on the Observer Pattern among others, and this can be easily implemented in Swing without using the formal Observer/Observable interface/class by judicious use of listeners, here an ActionListener.