简体   繁体   English

不能将Swing组件添加到多个容器中吗?

[英]Can't a Swing component be added to multiple containers?

I'm trying (testing something else) to add one JButton reference into two JPanels to test it, and it disappears from the first panel it was added to! 我正在尝试(测试其他东西)将一个JButton引用添加到两个JPanels进行测试,并且它从添加到其中的第一个面板中消失了!

So, can't a Swing component be added to multiple containers? 那么,Swing组件不能添加到多个容器中吗?

Thank you in advance. 先感谢您。

From: http://download.oracle.com/javase/tutorial/uiswing/components/toplevel.html : 来自: http : //download.oracle.com/javase/tutorial/uiswing/components/toplevel.html

Each GUI component can be contained only once. 每个GUI组件只能包含一次。 If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second. 如果某个组件已经在容器中,并且您尝试将其添加到另一个容器中,则该组件将从第一个容器中删除,然后添加到第二个容器中。

As you've discovered, you can't share components. 如您所知,您无法共享组件。 However there are other approaches you can use. 但是,您可以使用其他方法。

In the case of a JButtons you can share an Action: 如果是JButton,则可以共享一个Action:

JButton button1 = new JButton( someAction ); JButton button1 =新的JButton(someAction); JButton button2 = new JButton( someAction ); JButton button2 =新的JButton(someAction);

Read the section from the Swing tutorial on How to Use Actions for more information. 阅读Swing教程中有关如何使用动作的部分, 获取更多信息。

In other cases you might want to share the model: 在其他情况下,您可能希望共享模型:

DefaultTableModel model = new DefaultTableModel( ... );
JTable table1 = new JTable( model );
JTable table2 = new JTable( model );

The solution depends on your requirement. 解决方案取决于您的要求。

Solved. 解决了。

Checking at the UI-Swing section of the Java Tutorial, it says. 它说,检查Java教程的UI-Swing部分。

Each GUI component can be contained only once. 每个GUI组件只能包含一次。 If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second. 如果某个组件已经在容器中,并且您尝试将其添加到另一个容器中,则该组件将从第一个容器中删除,然后添加到第二个容器中。

I do not think that is possible. 我认为这是不可能的。 What you can do, is have is multiple components sharing the same event handler. 您所能做的就是让多个组件共享同一个事件处理程序。 SO basically, in your case, declare two buttons and use the same event handler method. 因此,基本上,在您的情况下,声明两个按钮并使用相同的事件处理程序方法。

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

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