1

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 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.