java JPanel里面另一个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4749725/
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
JPanel inside another
提问by anvd
I have a problem with a JPanel inside another one. I don't know why, but the result is a simple square, but the dimensions aren't correct. Why is that?
我在另一个 JPanel 中遇到了问题。我不知道为什么,但结果是一个简单的正方形,但尺寸不正确。这是为什么?
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class jj extends JFrame {
private JPanel painel3;
private JPanel painel5;
private Container container;
public jj() {
container = getContentPane();
container.setLayout(null);
painel5 = new JPanel();
painel5.setBackground(Color.red);
painel5.setBounds(120, 110, 100, 120);
painel3 = new JPanel();
painel3.setBackground(Color.white);
painel3.add(painel5);
painel3.setBounds(50, 50, 290, 220);
container.add(painel3);
// frame
setSize(1000, 900);
setLocation(200, 50);
setResizable(false);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new jj();
}
}
采纳答案by Jonas
You need to set the layout for panel3 also to null otherwise the default FlowLayout
is used:
您还需要将 panel3 的布局设置为 null,否则使用默认值FlowLayout
:
panel3.setLayout(null);
panel3.setLayout(null);
回答by jzd
A couple of additional recommendation. Learn to use LayoutManagers. They might have a slight learning curve but it will definitely be worth it. Nice tutorial: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
一些额外的建议。学习使用 LayoutManager。他们可能有一个轻微的学习曲线,但这绝对是值得的。不错的教程:http: //download.oracle.com/javase/tutorial/uiswing/layout/using.html
Also according to the Java Standards, class names should start with a capital letter. Doing this will help others read your code better.
同样根据 Java 标准,类名应该以大写字母开头。这样做将帮助其他人更好地阅读您的代码。
回答by Hovercraft Full Of Eels
Even better though is to avoid use of null layouts and setBounds/setSize but rather let layout managers help you in laying out your GUI. You can read up on them here: Laying out components in a container
更好的是避免使用空布局和 setBounds/setSize,而是让布局管理器帮助您布局 GUI。您可以在此处阅读它们:在容器中布置组件
回答by Miguel
Set the layout of painel3 to null before adding the painel5 panel.
在添加painel5面板之前将painel3的布局设置为null。
painel3.setLayout(null); painel3.add(painel5);
painel3.setLayout(null); painel3.add(painel5);
I recommend to use LayoutManagers.
我建议使用 LayoutManagers。