Java 向 JPanel 添加额外的 JPanel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/913139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding additional JPanels to a JPanel
提问by Peter C.
Rather basic question here guys.
相当基本的问题,伙计们。
Basically I have code like this:
基本上我有这样的代码:
public SuperPanel() {
setLayout(new BorderLayout());
add(panel1(), BorderLayout.NORTH);
add(panel2(), BorderLayout.CENTER);
add(panel3(), BorderLayout.SOUTH);
}
And that all works well and good. The problem is that I have another part I wish to add to the center. Just using add(newPanel(), BorderLayout.CENTER)
doesn't work, obviously. But you can add JPanel
s in JPanel
s, correct?
这一切都很好。问题是我还有另一部分要添加到中心。add(newPanel(), BorderLayout.CENTER)
显然,仅仅使用是行不通的。但是您可以在JPanel
s 中添加JPanel
s,对吗?
So I made the following change:
所以我做了以下改动:
public SuperPanel() {
setLayout(new BorderLayout());
add(panel1(), BorderLayout.NORTH);
add(supersweetpanel(), BorderLayout.CENTER);
add(panel3(), BorderLayout.SOUTH);
}
With supersweetpanel()
being:
随着supersweetpanel()
:
public JPanel supersweetpanel() {
JPanel sswp = new JPanel();
setLayout(new BorderLayout());
add(panel2(), BorderLayout.NORTH);
return sswp;
}
Now it overrides panel1
! If I set it to anything else (CENTER
, SOUTH
, what have you), the first two panels disappear entirely. Help is much appreciated.
现在它覆盖了panel1
!如果我将其设置为其他任何内容(CENTER
, SOUTH
,你有什么),前两个面板将完全消失。非常感谢帮助。
采纳答案by Michael Myers
SuperPanel
is likely a subclass of JPanel
, right? You are accidentally adding panel2
to this
(the SuperPanel
), not sswp
. Try:
SuperPanel
很可能是 的子类JPanel
,对吗?您不小心添加panel2
到this
(the SuperPanel
),而不是sswp
. 尝试:
public JPanel supersweetpanel() {
JPanel sswp = new JPanel();
sswp.setLayout(new BorderLayout());
sswp.add(panel2(), BorderLayout.NORTH);
return sswp;
}