Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

java - Using a JPanel with a null layout

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...