Java – How to remove component from JFrame that uses BorderLayout

javajframejpanelswing

The container uses a BorderLayout. I have a JPanel that I added to the CENTER. However the JPanel doesn't have a variable name for it.

I could do contents.remove(nameofPanel)

But since I added it like this contents.add(new CustomJPanel(), BorderLayout.CENTER);

Now I'm trying to remove the current CustomJPanel and add a new one.

How do I do this?

Best Answer

While Carl's answer is probably the best one, a less-pleasant alternative if for some reason you can't modify the original add() call:

contents.remove(((BorderLayout)getLayout()).getLayoutComponent(BorderLayout.CENTER));
contents.add(someNewPanel);

Though if you think you need to do this, you may want to step back and evaluate why you're trying to do it.