Adrian Elder
Adrian Elder

Reputation: 2071

paintComponent not called when adding custom JComponent

Why is paintComponent(Graphics) not called when adding a custom 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);
    }
}

I know there is no reason for creating a custom component in this instance of but it is an extremely simplified version of another issue I can't figure out.

Upvotes: 1

Views: 148

Answers (1)

camickr
camickr

Reputation: 324088

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

The default layout manager of a JPanel is a FlowLayout. A FlowLayout will respect the preferred size of any component added to it. By default the preferred size of a JComponent is (0, 0) so there is nothing to paint so the paintComponent() method never gets called.

Override the getPreferredSize() method of your CustomComponent class to return the preferred size of your component.

Also, don't forget to invoke super.paintComponent(...) at the start of the method.

Read the section from the Swing tutorial on Custom Painting for more information and working examples.

Upvotes: 5

Related Questions