How to remove all child components of a container?

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

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

my questions:

  • How to remove all components inside a container without knowing which component to remove?

  • Is it possible to remove all components and create other components and insert them correctly in the view port?

+6
source share
2 answers

The direct answer to your question is simply to call removeAll() on the container. However, the best answer (since I think your question is an example of an XY problem) is to use CardLayout and just replace the components through this layout.

+7
source

See Removeall () Method

Removes all components from this container. This method also notifies the layout manager to remove components from this container layout using the removeLayoutComponent method.

+4
source

Source: https://habr.com/ru/post/946305/


All Articles