Java Swing reuse buttons in different tabs

966 views Asked by At

I have a simple question regarding Swing. Ok, so let's say I have an application with two tabs where I can switch from one tab to another. I want to have fields and buttons in those tabs, for example

TAB 1

Tab1;
field1
field2 
AddButton

TAB 2

Tab2;
field1
field2
AddButton

I have actionListeners attached to those buttons and since I'm going to expand the application and make another tabs, I want to use the AddButton many times. However, I want the AddButton to implement different logic, depending on the tab. For example if I press it and i'm on tab1, the logic might be "INSERT field1 INTO TAB1.TABLE", if I'm on tab 2 and press it - "INSERT FIELD1 INTO TAB2.TABLE", etc.

My question is - is there a simple way to reuse the button depending on the pressed tab, or should I make a new button for each new tab (That seems like lots of spaghetti code to me...). Or maybe I should make a generic Buttons interface and then implement it with buttons about each menu?

1

There are 1 answers

2
Sergii Lagutin On

Any swing component might be placed only in one container. So you cannot have same button on different tabs. But you can have few instances of same class e.g. Create own button for every tab is not spaghetti code. Every button response for own action. Sure if action differ with performed sql query better way is encapsulate common methods to superclass and specify query in subclasses or via constructor argument.