user2309944
user2309944

Reputation:

How to remove all children components of a container?

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?

Upvotes: 7

Views: 7542

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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.

Upvotes: 8

Suresh Atta
Suresh Atta

Reputation: 121998

Have a look at Removeall() method

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

Upvotes: 3

Related Questions