javaswinglayoutgrouplayoutborder-layout

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


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!


Solution

  • 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);