为什么 AWT/Swing 在将组件添加到容器时不自动重新绘制?
Why doesn't AWT/Swing repaint automatically when adding a component to a container?
我们有一些代码实现如下:
@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
只是一个JPanel
,CardPanel
只是我们自己的接口之一,但是所有的卡片面板都只是使用普通的Swing组件。
这条评论令人费解,因为据我所知,Container#add
应该会在添加子项时自动重绘自身。然而,如果我删除该行,我确实看到在添加子项时它不会重新绘制其内容。
Container
这样做有什么特别的原因吗?对我来说,这似乎违反了 "principle of least surprise"...
Is there some particular reason why Container behaves this way?
默认情况下,所有 Swing 组件的默认大小为 (0, 0),因此没有可绘制的内容。
组件在布局管理器被调用时被赋予一个大小(和位置)。由于您可以向面板添加多个组件,因此在添加每个组件时持续调用布局管理器是没有意义的。
因此,当您完成向面板添加组件后,您可以:
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // not always needed, but will ensure the panel is repainted.
我们有一些代码实现如下:
@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
只是一个JPanel
,CardPanel
只是我们自己的接口之一,但是所有的卡片面板都只是使用普通的Swing组件。
这条评论令人费解,因为据我所知,Container#add
应该会在添加子项时自动重绘自身。然而,如果我删除该行,我确实看到在添加子项时它不会重新绘制其内容。
Container
这样做有什么特别的原因吗?对我来说,这似乎违反了 "principle of least surprise"...
Is there some particular reason why Container behaves this way?
默认情况下,所有 Swing 组件的默认大小为 (0, 0),因此没有可绘制的内容。
组件在布局管理器被调用时被赋予一个大小(和位置)。由于您可以向面板添加多个组件,因此在添加每个组件时持续调用布局管理器是没有意义的。
因此,当您完成向面板添加组件后,您可以:
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // not always needed, but will ensure the panel is repainted.