自定义布局:
1.取消布局器
contentPane.setLayout(null);//取消布局器
2.使用setBounds()对子控件手动布局 new Rectangle(x,y,宽,高)
jLabel1.setBounds(new Rectangle(0,0,200,200)); jLabel2.setBounds(new Rectangle(100,100,200,100));
package com.java.gui10;
import javax.swing.*;
import java.awt.*;
/**
* @author zyx
* @create 2021-06-04 9:11
*
* 自定义布局
*/
public class MyJFrame extends JFrame {
public MyJFrame(String title) {
super(title);
Container contentPane = this.getContentPane();
contentPane.setLayout(null);//取消布局器
JLabel jLabel1 = new JLabel("1");
JLabel jLabel2 = new JLabel("2");
jLabel1.setBackground(Color.yellow);
jLabel2.setBackground(Color.blue);
//设置控件位置
jLabel1.setBounds(new Rectangle(0,0,200,200));//控件1会覆盖掉部分控件二
jLabel2.setBounds(new Rectangle(100,100,200,100));
jLabel1.setOpaque(true);//设置控件是否透明,true:不透明
jLabel2.setOpaque(true);
contentPane.add(jLabel1);
contentPane.add(jLabel2);
}
}
package com.java.gui10; import javax.swing.*; /** * @author zyx * @create 2021-06-04 9:19 */ public class CustomLayoutTest { public static void main(String[] args) { MyJFrame jFrame = new MyJFrame("Custom Layout Test"); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.setSize(400,300); jFrame.setVisible(true); } }