AWT介绍![](https://img-blog.csdnimg.cn/20191205133918344.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0Nva2V6,size_16,color_FFFFFF,t_70)
组件和容器
- 容器------Frame
创建Frame会实现一个窗口界面,可使用Frame中的方法来调节大小,颜色,初始位置等。
package org.ming.lesson01;
import java.awt.*;
public class TestFrame {
public static void main(String[] args) {
//Frame,JDK, 看源码!
Frame frame = new Frame("Frame窗口");
//设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(200,200);
//设置背景颜色
frame.setBackground(new Color(30, 150, 40));
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);//不可更改大小
}
}
使用AWT创建窗口需要些鉴定窗口关闭事件,否则点击窗口"X“”按钮不会关闭窗口,只能手动终止程序。
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
//关闭
System.exit(0);
}
});
- 组件------button(按钮)
流式布局
package org.ming.lesson01;
import java.awt.*;
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
//组件-按钮
Button button1 = new Button("button1");
Button button2 = new Button("button2");
Button button3 = new Button("button3");
//设置流式布局
frame.setLayout(new FlowLayout(FlowLayout.RIGHT));
frame.setSize(200,200);
//添加按钮
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.setVisible(true);
}
}
- 练习
代码实现
package org.ming.lesson01;
import java.awt.*;
public class ExDemo {
public static void main(String[] args) {
//总 Frame
Frame frame = new Frame();
frame.setSize(400,300);
frame.setLocation(300,400);
frame.setBackground(Color.BLACK);
frame.setVisible(true);
frame.setLayout(new GridLayout(2,1));
//4个面板
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2,2));
p1.add(new Button("East-1"),BorderLayout.EAST);
p1.add(new Button("West-1"),BorderLayout.WEST);
p2.add(new Button("p2-btn-1"));
p2.add(new Button("p2-btn-2"));
p1.add(p2,BorderLayout.CENTER);
//下面
p3.add(new Button("East-2"),BorderLayout.EAST);
p3.add(new Button("West-2"),BorderLayout.WEST);
//中间4个
for (int i = 0; i < 4; i++) {
p4.add(new Button("for-"+i));
}
p3.add(p4,BorderLayout.CENTER);
frame.add(p1);
frame.add(p3);
}
}
总结:
- Frame是一个顶级窗口
- Panel 无法单独显示,必须添加到某个容器中。
- 布局管理器
- 流式
- 东西南北中
- 表格
- 大小,定位,背景颜色,可见性,监听!