Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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?

like image 246
user69514 Avatar asked Dec 18 '22 06:12

user69514


2 Answers

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.

like image 180
Sbodd Avatar answered Dec 19 '22 19:12

Sbodd


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);
like image 33
Carl Manaster Avatar answered Dec 19 '22 20:12

Carl Manaster