Luís Ambrozin
Luís Ambrozin

Reputation: 3

Using the same button in multiple frames

I'm studying Java Swing, and I created some JFrame windows, in some of them, I created a button and they have the same solution (like search or save information), however, all the time I've had to create from the begining or use ctrl+c ctrl+v. Is there a way to create a JButton and use the same button in multiple frames?

And for JTextfield, there's a way to create only once and use for multiples frames?

There's an example using a unique button and showing a "Hello World"?

Upvotes: 0

Views: 438

Answers (2)

talex
talex

Reputation: 20542

Well it is possible, but it will be much simpler to have two copy.

To achieve it yo need to create delegate class extending Component and pass all method calls to single instance of button.

You'll have multiple instances of delegate though.

Upvotes: -1

Rob Spoor
Rob Spoor

Reputation: 9175

Swing components can only be contained in one container (JPanel, etc.). However, most Swing components are backed by models, and those models can easily be shared between multiple component instance. In case of JButton there are actually two models: a ButtonModel and an Action. You can use add ActionListeners to the ButtonModel and that should work. However, I've never used that, since I prefer to use Action for buttons.

Upvotes: 2

Related Questions