📄 gridbaglayouttest.java
字号:
//GridBagLayoutTest.java
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest extends JFrame {
GridBagLayout gb = null; //布局管理对象
GridBagConstraints gbc = null; //布局辅助对象
Container cp = null; //当前容器
JLabel lblTitle = null; //标题标签
JLabel lblUser = null;
JLabel lblPwd = null;
JTextField txtUser = null; //用户名文本框
JPasswordField txtPwd = null; //密码框
JButton btnOK = null; //确定按钮
public GridBagLayoutTest() {
super("GridBagLayout Test");
gb = new GridBagLayout(); //创建布局管理器
cp = this.getContentPane(); //取得当前容器
cp.setLayout(gb); //设置当前容器的布局管理器
gbc = new GridBagConstraints(); //创建辅助对象
//创建每个组件
lblTitle = new JLabel("用户登录");
lblUser = new JLabel("用户名:");
lblPwd = new JLabel("密 码:");
txtUser = new JTextField(10);
txtPwd = new JPasswordField(10);
btnOK = new JButton("确定");
//设置当前填充模式为水平拉伸
gbc.fill = GridBagConstraints.HORIZONTAL;
//调用自定义函数addComponent()来把标题标签添加到容器中
addComponent(lblTitle,0,1,1,1);
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
addComponent(lblUser,1,0,1,1);
addComponent(lblPwd,2,0,1,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(txtUser,1,1,1,2);
addComponent(txtPwd,2,1,1,2);
addComponent(btnOK,3,1,1,1);
}
/* 自定义函数,用来把组件c添加到当前容器中,参数含义如下:
* c - 要加入的组件
* row - 该组件所处的网格开始行(从0开始编号)
* col - 该组件所处的网格开始列(从0开始编号)
* nrow - 该组件宽要占的网格单元格数目
* ncol - 该组件高要占的网格单元格数目
*/
public void addComponent(Component c,int row, int col, int nrow, int ncol) {
gbc.gridx = col; //给辅助对象赋值
gbc.gridy = row;
gbc.gridwidth = ncol;
gbc.gridheight = nrow;
gb.setConstraints(c,gbc); //设置组件的属性
cp.add(c); //添加组件c到容器cp中
}
public static void main(String[]ars) {
GridBagLayoutTest gbt = new GridBagLayoutTest();
gbt.setSize(300,180);
gbt.setDefaultCloseOperation(EXIT_ON_CLOSE);
gbt.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -