添加自定义 JComponent 时未调用 paintComponent

paintComponent not called when adding custom JComponent

为什么添加自定义 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 class 的 getPreferredSize() 方法重写为 return 组件的首选大小。

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

阅读有关 Custom Painting 的 Swing 教程部分,了解更多信息和工作示例。