添加自定义JComponent时未调用paintComponent

Adr*_*der 1 java swing awt

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

cam*_*ckr 5

JPanel panel = new JPanel();
panel.add(new CustomComponent());
Run Code Online (Sandbox Code Playgroud)

a的默认布局管理器JPanel是a FlowLayout.A FlowLayout将尊重添加到其中的任何组分的优选大小.默认情况下,a的首选大小JComponent为(0,0),因此无需绘制任何内容,因此paintComponent()方法永远不会被调用.

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

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

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