27

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!

So, can't a Swing component be added to multiple containers?

Thank you in advance.

Juan Diego
  • 861
  • 1
  • 10
  • 22

4 Answers4

47

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.

jzd
  • 23,019
  • 7
  • 51
  • 76
  • I checked for the exact wording and edited my answer at the same time you posted. I guess I should have refreshed first. – jzd Jan 06 '11 at 22:31
6

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.

camickr
  • 308,339
  • 18
  • 152
  • 272
4

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.
Juan Diego
  • 861
  • 1
  • 10
  • 22
1

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.

npinti
  • 50,175
  • 5
  • 67
  • 92