简体   繁体   English

不同选项卡中的Java Swing重用按钮

[英]Java Swing reuse buttons in different tabs

I have a simple question regarding Swing. 我有一个关于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 标签1

Tab1;
field1
field2 
AddButton

TAB 2 标签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. 我将actionListeners附加到这些按钮上,并且由于我将扩展应用程序并创建另一个选项卡,因此我想多次使用AddButton However, I want the AddButton to implement different logic, depending on the tab. 但是,我希望AddButton根据选项卡实现不同的逻辑。 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. 例如,如果我按它并且我在tab1 ,则逻辑可能是"INSERT field1 INTO TAB1.TABLE" ,如果我在选项卡2上并按它- "INSERT FIELD1 INTO TAB2.TABLE""INSERT FIELD1 INTO TAB2.TABLE"

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? 还是我应该创建一个通用的Buttons接口,然后使用有关每个菜单的按钮来实现它?

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 eg 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. 确保操作是否与执行的SQL查询不同,更好的方法是封装通用方法以超类并在子类中或通过构造函数参数指定查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM