Using a JPanel with a null layout

Joel Christophel picture Joel Christophel · Feb 20, 2013 · Viewed 22.8k times · Source

So I have a class called CalendarPanel that extends JPanel. It uses a null layout. How would I use CalendarPanel as a regular component? When I put it in another JPanel and then add it to a window, it disappears. It is only visible when I add it directly to a window.

EDIT: And yes, I realize using a JPanel with a null layout is bad practice. CalendarPanel is actually someone else's code, and I'm trying to use it for my purposes without having to refactor it.

Answer

camickr picture camickr · Feb 20, 2013

It is only visible when I add it directly to a window.

That is because a window uses a BorderLayout by default and will automatically resize the panel to fit in the window.

When I put it in another JPanel and then add it to a window, it disappears.

The is because a JPanel uses a FlowLayout by default and a flow layout respects the preferred size of the components added to it. Since you are using a null layout your panel doesn't have a preferred size so nothing gets painted.

That is why you should NOT use null layout. Instead use layout managers because they do all this extra work for you.