绝对点位布局, 给容器布局管理器设置为 null,然后通过设置组件的坐标和宽高来布置组件。
setLayout(null);
组件设置坐标
void setLocation(int x, int y)
void setLocation(Point p)
组件设置宽高
void setSize(int width, int height)
void setSize(Dimension d)
组件设置界限(坐标和宽高)
void setBounds(int x, int y, int width, int height)
void setBounds(Rectangle rect)
演示代码如下
package com.msh.util;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class DemoNULL {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setTitle("演示绝对定位布局");
jf.setSize(300, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
jp.setLayout(null); //绝对定位布局
JButton btn1 = new JButton("登录");
btn1.setLocation(30, 30); //按钮的坐标
btn1.setSize(100, 30); //按钮的宽高
jp.add(btn1);
JButton btn2 = new JButton("退出");
btn2.setBounds(30, 80, 100, 30); //按钮界限(坐标和宽高)
jp.add(btn2);
JButton btn3 = new JButton("注册");
btn3.setBounds(jf.getWidth()-270, jf.getHeight()-100, 100, 30);
jp.add(btn3);
jf.setContentPane(jp);
jf.setVisible(true);
}
}
运行程式