📄 gridbagapp.java
字号:
import java.awt.*;
import java.awt.event.*;
class GridBagApp extends Frame
{
TextArea txtArea;
TextField txtField;
Button btn1, btn2;
CheckboxGroup cbg;
Checkbox cb1, cb2, cb3, cb4;
GridBagLayout gbLayout;
GridBagConstraints gbc;
public GridBagApp(String title)
{
super(title);
gbLayout = new GridBagLayout();
setLayout(gbLayout);
gbc = new GridBagConstraints();
txtArea = new TextArea("文本区", 5, 10);
txtField = new TextField("请输入你的姓名:");
btn1 = new Button("确定");
btn2 = new Button("取消");
cbg = new CheckboxGroup();
cb1 = new Checkbox("粗体", cbg, false);
cb2 = new Checkbox("斜体", cbg, false);
cb3 = new Checkbox("普通", cbg, true);
cb4 = new Checkbox("粗斜体", cbg, false);
//gbc.ipadx = 50; // 指定单元格最小宽度
//gbc.ipady = 50; // 指定单元格最低高度
//gbc.weightx = 10; // 打开水平自动伸缩
//gbc.weighty = 5; // 打开垂直自动伸缩
gbc.fill = GridBagConstraints.BOTH;
addComponent(txtArea,0,0,4,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(btn1,0,1,1,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(btn2,0,2,1,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(cb1,2,1,1,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(cb2,2,2,1,1);
gbc.anchor = GridBagConstraints.SOUTH; // 放在单元格底部
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(cb3,3,1,1,1);
gbc.fill = GridBagConstraints.HORIZONTAL;
addComponent(cb4,3,2,1,1);
gbc.fill = GridBagConstraints.BOTH;
addComponent(txtField,4,0,1,3);
// 添加关闭窗口事件代码
this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); // 退出应用程序
}
}
);
}
public void addComponent(Component c, int row, int col, int rowspan, int colspan)
{
gbc.gridx = col;
gbc.gridy = row;
gbc.gridwidth = colspan;
gbc.gridheight = rowspan;
gbLayout.setConstraints(c, gbc);
add(c);
}
public static void main(String args[])
{
GridBagApp f=new GridBagApp("测试GridBag布局!");
f.setSize(300,300);
f.setLocation(360,200);
f.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -