使用具有null布局的JPanel [英] Using a JPanel with a null layout
问题描述
所以我有一个名为 CalendarPanel
的类,它扩展了 JPanel
。它使用null布局。我如何使用 CalendarPanel
作为常规组件?当我把它放在另一个 JPanel
中,然后将其添加到窗口时,它就会消失。它只有在我直接添加到窗口时才可见。
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.
编辑:
是的,我意识到使用 JPanel 带有空布局的code>是不好的做法。
CalendarPanel
实际上是别人的代码,我正在尝试将它用于我的目的,而不必重构它。
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.
推荐答案
仅当我将其直接添加到窗口时才可见。
It is only visible when I add it directly to a window.
这是因为默认情况下窗口使用BorderLayout并会自动调整面板大小以适应窗口。
That is because a window uses a BorderLayout by default and will automatically resize the panel to fit in the window.
我把它放在另一个JPanel中,然后将它添加到一个窗口,它就消失了。
When I put it in another JPanel and then add it to a window, it disappears.
这是因为默认情况下JPanel使用FlowLayout,流布局会考虑添加到其中的组件的首选大小。由于您使用的是null布局,因此面板没有首选大小,因此不会绘制任何内容。
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.
这就是为什么不应该使用null布局。而是使用布局管理器,因为它们会为您完成所有这些额外工作。
That is why you should NOT use null layout. Instead use layout managers because they do all this extra work for you.
这篇关于使用具有null布局的JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!