views:

756

answers:

4

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?

+2  A: 

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);
Carl Manaster
+2  A: 

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.

Sbodd
A: 

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

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

A: 

I strongly suggest you declare a global CustomJPanel variable, instantiate it with your first panel, then add the panel. When you want to remove it, you use the same object. Then you assign the new object to the variable, and add it the same way.

Anonymous object are okay when you don't need to refer to them. But you do. So you should avoid using the anonymous way.

Silence