Java GUI编程lesson05-Button
程序员文章站
2022-07-06 11:04:11
...
Button组件
顾名思义就是按钮,提到button组件就还要涉及到布局管理器
布局管理器Layout
Frame布局管理器的三种布局:
- 流式布局
- 环绕性布局
- 表格布局
布局的使用
1.流式布局(FlowLayout)
public class TestFlowLayout {
public static void main(String[] args) {
//new一个Frame窗口
Frame frame = new Frame();
//new button按钮组件
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//设置为流式布局
frame.setLayout(new FlowLayout());//默认为居中
// frame.setLayout(new FlowLayout(FlowLayout.LEFT));//靠左
// frame.setLayout(new FlowLayout(FlowLayout.RIGHT));//靠右
// frame.setLayout(new FlowLayout(FlowLayout.LEADING));//行首
// frame.setLayout(new FlowLayout(FlowLayout.TRAILING));//行末
//设置窗口大小
frame.setSize(200, 200);
//设置窗口可见
frame.setVisible(true);
//添加button组件
frame.add(button1);
frame.add(button2);
frame.add(button3);
//监听窗口关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
效果展示:
2.环绕性布局(BorderLayout)
public class TestBorderLayout {
public static void main(String[] args) {
//new Frame窗口
Frame frame = new Frame("TestBorderLayout");
//new button按钮
Button east = new Button("East");
Button west = new Button("West");
Button south = new Button("South");
Button north = new Button("North");
Button center = new Button("Center");
//环绕型布局的五个位置:东,西,南,北,中
frame.add(east, BorderLayout.EAST);
frame.add(west, BorderLayout.WEST);
frame.add(south, BorderLayout.SOUTH);
frame.add(north, BorderLayout.NORTH);
frame.add(center, BorderLayout.CENTER);
//窗口可见性
frame.setVisible(true);
//窗口初始化大小
frame.setSize(400,400);
//窗口关闭监听事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
效果展示:
3.表格布局(GirdLayout)
public class TestGridLayout {
public static void main(String[] args) {
//new Frame窗口
Frame frame = new Frame("TestBorderLayout");
//new button按钮
Button btn1 = new Button("btn1");
Button btn2 = new Button("btn2");
Button btn3 = new Button("btn3");
Button btn4 = new Button("btn4");
Button btn5 = new Button("btn5");
Button btn6 = new Button("btn6");
//设置布局为表格布局三行两列
frame.setLayout(new GridLayout(3, 2));
//添加按钮
frame.add(btn1);
frame.add(btn2);
frame.add(btn3);
frame.add(btn4);
frame.add(btn5);
frame.add(btn6);
//设置可见性
frame.setVisible(true);
//pack()函数可以自动适应布局
frame.pack();
//设置窗口关闭监听器
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
效果展示:
下一篇: 汇编语言程序设计实验一