0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • You can place any instance of buttons, textfields, etc. in multiple places. But you have to consider context when doing so. If you have the same save or edit button in multiple locations, what is it your are saving or editing? But the same instances will have the same event handler and you won't be able to easily determine which instance fired the event `(i.e. via getSource())`. – WJS Mar 03 '22 at 18:30
  • ok @WJS There's a simple example here in the forum or a youtube tutorial? For now, I just want to see how it works for future projects, I appreciate for your comment – Luís Ambrozin Mar 03 '22 at 19:22
  • There should rarely, if ever, be more than one `JFrame` in an app. See the answers to [this question](https://stackoverflow.com/q/9554636/418556) for the many downsides of having multiple frames, and [my answer](https://stackoverflow.com/a/9554657/418556) in particular, for alternatives. **As to the concept of using a particular 'button'** in multiple places, it seems you'd be best served by creating a common `Action` which can be used to create a button or a menu item, or added to a `JToolBar` or .. whatever, as needed. – Andrew Thompson Mar 03 '22 at 21:17
  • @AndrewThompson, thanks for the answer, I saw the question about using multiple jFrames and i'm gonna make this solution, and with my searches and all the answers here, seems it's not a great idea to use multiple buttons for same action, however, for jTextfields or jFormattedfield, there's a way to formatted and use the same field in a jFrame and jDialog? – Luís Ambrozin Mar 07 '22 at 19:53

1 Answers1

2

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.

Rob Spoor
  • 6,186
  • 1
  • 19
  • 20