[英]JPanel inside another
I have a problem with a JPanel inside another one. 我在另一个JPanel中遇到问题。 I don't know why, but the result is a simple square, but the dimensions aren't correct.
我不知道为什么,但结果是一个简单的方形,但尺寸不正确。 Why is that?
这是为什么?
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();
}
}
您还需要将panel3的布局设置为null,否则使用默认的FlowLayout
:
panel3.setLayout(null);
A couple of additional recommendation. 一些额外的建议。 Learn to use LayoutManagers.
学习使用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
很好的教程: http : //download.oracle.com/javase/tutorial/uiswing/layout/using.html
Also according to the Java Standards, class names should start with a capital letter. 同样根据Java标准,类名应以大写字母开头。 Doing this will help others read your code better.
这样做可以帮助其他人更好地阅读您的代码。
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. 更好的方法是避免使用null布局和setBounds / setSize,而是让布局管理器帮助您布局GUI。 You can read up on them here: Laying out components in a container
您可以在此处阅读它们: 在容器中布置组件
Set the layout of painel3 to null before adding the painel5 panel. 在添加painel5面板之前,将painel3的布局设置为null。
painel3.setLayout(null); painel3.setLayout(NULL); painel3.add(painel5);
painel3.add(painel5);
I recommend to use LayoutManagers. 我建议使用LayoutManagers。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.