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

独自空忆成欢 提交于 2019-11-26 16:39:56

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

Each GUI component can be contained only once. 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 button1 = new JButton( someAction ); JButton button2 = new JButton( someAction );

Read the section from the Swing tutorial on How to Use Actions for more information.

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.

Each GUI component can be contained only once. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!