Why is paint()/paintComponent() never called?

One of the reasons the paintComponent() doesn’t get invoked in the original code is because the component has a “zero size” and the RepaintManger is smart enough not to try and paint something with no size.

The reason the reordering of the code works is because when you add the component to the frame and then make the frame visible the layout manager is invoked to layout the component. By default a frame uses a BorderLayout and by default a component is added to the center of the BorderLayout which happens give all the space available to the component so it gets painted.

However, you change the layout manager of the content pane to be a FlowLayout, you would still have a problem because a FlowLayout respects the preferred size of the component which is zero.

So what you really need to do is assign a preferred size to you your component so layout managers can do their job.

Leave a Comment