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?
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.
Your best way is to extract the constructor call into a named variable - probably a field, actually - and then reduce to the previous case.
contents.add(new CustomJPanel(), BorderLayout.CENTER);
becomes
nameOfPanel = new CustomJPanel();
contents.add(nameOfPanel, BorderLayout.CENTER);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With