How to remove a specific element from a JPanel using BorderLayout/GroupLayout?

zw324 picture zw324 · Jun 10, 2011 · Viewed 7.8k times · Source

I need to remove the Component in the Center of the JPanel, but after some tries no prevail.

I tried the method here:

Removing the CENTER element from a JPanel using BorderLayout

But the answer's method produces a compile time error:

Type mismatch: cannot convert from LayoutManager to BorderLayout

Am I interpreting the answer wrong?

In addition, I am also curious if I can update just a single component from a GroupLayout. Could somebody tell me how to do it?

EDIT: @mre: Here's the code:

BorderLayout layout = panel.getLayout();
panel.remove(layout.getLayoutComponent(BorderLayout.CENTER));

Which is basically the same as in the link.

Thank you all!

Answer

JB Nizet picture JB Nizet · Jun 10, 2011

You have to downcast the layout manager to BorderLayout :

BorderLayout layout = (BorderLayout) panel.getLayout();

But if you know which component is in the center, you can just remove it :

panel.add(myComponent, BorderLayout.CENTER);
...
panel.remove(myComponent);