Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

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

Thank you in advance.

like image 464
Juan Diego Avatar asked Jan 06 '11 22:01

Juan Diego


People also ask

Which component Cannot be added to a container?

JFrame s and JWindow s are the only components that can be displayed without being added or attached to another Container .

How many types of Swing containers are there in Java?

There are three container classes: JFrame. JDialog. JApplet.

Which package is required for Swing components in Java?

The javax. swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.


2 Answers

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.

like image 173
jzd Avatar answered Oct 04 '22 13:10

jzd


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.

like image 42
camickr Avatar answered Oct 04 '22 15:10

camickr