geo
geo

Reputation: 527

More that one components "linked" to each other

It is vary usual to have 2 swing components doing the same job. For example we can have a button in a toolbar used as a "save" button, and a JMenuItem (File-save...) doing the same.

My question is:
Is there a way to keep one component "linked" to another so we don't have to repeat code?

Of course we can simply create a single method and call it from both components, but I am learning java now and I would like to ask if it is possible to do it another way.

Upvotes: 1

Views: 69

Answers (2)

JB Nizet
JB Nizet

Reputation: 691685

If your goal is simply to have the same code called when the button/item is clicked, then you simply need to define a single ActionListener instance, and add it to the button and to the menu item.

If, in addition, you want, for example, to disable both the button and the item based on the same condition, or to associate the same label or icon to both components, then define a single Action, and construct the button and the item using this action. Then interact with the Action, and the button and item state will reflect the changes.

Upvotes: 3

Amila
Amila

Reputation: 5213

Just write your logic (eg. for saving) in a separate method and call that method from different UI elements.

Upvotes: 0

Related Questions