java - one object updating another
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 vari开发者_如何转开发able value change?
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.
精彩评论