'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"?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rob Spoor