Reputation:
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:
How to remove all the components inside a container without knowing which component to remove?
Is this way of removing all the components and creating other components and inserting them to the view port correct?
Upvotes: 7
Views: 7542
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
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