Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all children components of a container?

Tags:

java

swing

jpanel

I have a swing application with a JPanel, which acts as a view port for my application. I want my application to remove all the components inside the view port when user clicks on a menu item or button and creates the new components inside it. I know how to remove a component from within a container, it is not clear which component is inside the view port currently, So I think I can't use below code:

viewport.remove(component);
viewport.revalidate();
viewport.repaint();

my questions:

  1. How to remove all the components inside a container without knowing which component to remove?

  2. Is this way of removing all the components and creating other components and inserting them to the view port correct?

like image 927
jacksparrow92 Avatar asked Jun 01 '13 06:06

jacksparrow92


Video Answer


1 Answers

The direct answer to your question is to simply call removeAll() on the container. The better answer though (since I think that your question is an example of an XY problem) is to use a CardLayout and simply swap components via this layout.

like image 192
Hovercraft Full Of Eels Avatar answered Oct 20 '22 18:10

Hovercraft Full Of Eels