Question

What is de difference between remove and removeAll in the java swing library? I have one control panel and a panel which can be changed with the control panel. This changing is done in the parent frame object. When I use the code:

public void showNextPanel(){
        if(hasNextPanel()){
            getSelectedPanel().setVisible(false);
            getContentPane().removeAll();
            getContentPane().add(controlPanel);
            selectedPanel++;
            getContentPane().add(getSelectedPanel());
            getSelectedPanel().setVisible(true);
            revalidate();
            repaint();
        }else{
            System.exit(0);
        }
    }

Then everything works exactly as expected. When I change the removeAll in the remove statement, this selected panel becomes gray, but still visible. When resizing my frame, the new frame is visible, you can see it is hiding behind the previous selected panel. Then my code is:

public void showNextPanel(){
        if(hasNextPanel()){
            getSelectedPanel().setVisible(false);
            getContentPane().remove(getSelectedPanel());
            selectedPanel++;
            getContentPane().add(getSelectedPanel());
            getSelectedPanel().setVisible(true);
            revalidate();
            repaint();
        }else{
            System.exit(0);
        }
    }

Why does my JPanel disappear when using removeAll but not when using remove?

Was it helpful?

Solution

The method names are a big hint, and the definitive answer is in the javadocs:

For Container.remove(Component):

"Removes the specified component from this container."

For Container.removeAll():

"Removes all the components from this container."

As to what is causing the difference in behaviour, my guess is that there is some other component in the panel that is getting removed in the first case, but not in the second case.

Try calling and logging / printing getComponentCount() after the "remove" in both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top