Java – How to remove component from JFrame that uses BorderLayout


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 Solution

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:


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