简体   繁体   中英

Why doesn't AWT/Swing repaint automatically when adding a component to a container?

We have some code implemented as follows:

@Override
public void showPanel(CardPanel panel)
{
    cardPanel.removeAll();
    cardPanel.add((Component) panel);

    // Even though you'd think adding a component should automatically repaint,
    // it turns out that it doesn't.
    cardPanel.repaint();
}

cardPanel is just a JPanel and CardPanel is just one of our own interfaces, but all card panels are just using normal Swing components.

This comment was baffling because, as far as I knew, Container#add was supposed to automatically repaint itself if a child was added. Yet, if I delete the line, indeed I do see that it doesn't repaint its contents when the child is added.

Is there some particular reason why Container behaves this way? To me, it seems to violate the "principle of least surprise"...

Is there some particular reason why Container behaves this way?

By default all Swing components have a default size of (0, 0) so there is nothing to paint.

Components are given a size (and location) when the layout manager is invoked. Since you could be adding multiple components to the panel it doesn't make sense for the layout manager to continually be invoked as each component is added.

So when you finish adding components to the panel you do:

panel.revalidate(); // to invoke the layout manager
panel.repaint(); // not always needed, but will ensure the panel is repainted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM