Skip to main content

Adding the same instance of a component to multiple locations

2 replies [Last post]
acechase
Offline
Joined: 2003-12-02
Points: 0

Hi,

I'm wondering why I can not add the same instance of a JComponent to multiple containers in Swing. When I try to do so, it looks like the component is removed from the first place it was added to when it gets added to the second place.

Here's some code demonstrating the issue, if you run it, you'll see that the JPanel with the label saying "hello" only shows up in the second tab.

<br />
public class MyTestClass extends JFrame {<br />
	public MyTestClass(){<br />
		super("My Test");<br />
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />
		JTabbedPane tabbed = new JTabbedPane();<br />
		final JPanel  panel = new JPanel();<br />
		panel.add(new JLabel("hello"));<br />
		JPanel p1 = new JPanel();<br />
		p1.add(panel);<br />
		JPanel p2 = new JPanel();<br />
		p2.add(panel);</p>
<p>		tabbed.insertTab("Tab 1", null, p1, "whatever", 0);<br />
		tabbed.insertTab("Tab 2", null, p2, "whomever", 1);<br />
		this.getContentPane().add(tabbed);<br />
		this.setBounds(400, 400, 400, 400);<br />
		this.setVisible(true);<br />
	}</p>
<p>    public static void main(String[] args) {<br />
    	MyTestClass m = new MyTestClass();<br />
    }<br />
}<br />

Thanks,
Andrew

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
kor_wanderer
Offline
Joined: 2003-08-18
Points: 0

this, thing happens because of Components frame work architecture. Closely the problem'is in the one thing
:
each component has one owner. when you are adding component
to container. His owner is changing automatically. This is
the part of awt sources showing it ...

protected void addImpl(Component comp, Object constraints, int index)
{
.....
/* Reparent the component and tidy up the tree's state. */
if (comp.parent != null)
{
comp.parent.remove(comp);
if (index > ncomponents)
{
throw new IllegalArgumentException("illegal component
position");
}
}
this method is invocated by any awt or swing implementation off add(Component c....)

acechase
Offline
Joined: 2003-12-02
Points: 0

Okay great. That makes sense.

Thanks a lot!