How to remove a component from a JFrame that uses BorderLayout

The container uses BorderLayout. I have a JPanel that I added to CENTER. However, JPanel does not have a variable name for it.

I could do contents.remove (nameofPanel)

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

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

How can I do it?

+4
source share
4 answers

While Carl's answer is probably the best, less pleasant alternative, if for some reason you cannot change the original add () call:

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

Although, if you think you need to do this, you may need to step back and evaluate why you are trying to do this.

+6
source

Your best way is to extract the constructor call into a named variable - perhaps 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); 
+5
source

Or you can list all the elements in the container using the function http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Container.html#getComponents () and search in Panel using another attribute (if you can).

The attribute http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html#getName () is useful for this purpose, for example. you set the name of your panel before pasting, and you can use that name as a search key.

0
source

I highly recommend that you declare a CustomJPanel global variable, create an instance with the first panel, and then add the panel. When you want to delete it, you use the same object. Then you assign the new object to the variable and add it in the same way.

An anonymous object is fine when you don't need to reference them. But you do. Therefore, you should avoid using an anonymous method.

0
source

All Articles