添加自定义 JComponent 时未调用 paintComponent



为什么在添加自定义 JComponent 时不调用paintComponent(Graphics)

public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame("Paint Component Example");
frame.setPreferredSize(new Dimension(750, 750));
frame.setLocationByPlatform(true);
JPanel panel = new JPanel();
panel.add(new CustomComponent());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
public class CustomComponent extends JComponent {
public CustomComponent() {
super();
}
@Override
protected void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(10, 10, 10, 10);
}
}

我知道在这种情况下没有理由创建自定义组件,但它是我无法弄清楚的另一个问题的极其简化的版本。

JPanel panel = new JPanel();
panel.add(new CustomComponent());

JPanel的默认布局管理器是FlowLayoutFlowLayout将遵循添加到其中的任何组件的首选大小。默认情况下,JComponent的首选大小是 (0, 0(,因此没有要绘制的内容,因此永远不会调用 paintComponent(( 方法。

重写CustomComponent类的getPreferredSize()方法以返回组件的首选大小。

此外,不要忘记在方法开始时调用super.paintComponent(...)

阅读有关自定义绘画的 Swing 教程中的部分,以获取更多信息和工作示例。

最新更新