GUI编程
GUI简介
GUI(图形用户界面编程)的核心技术: Swing AWT
被淘汰的原因:
-
因为界面不美观
-
需要jre环境
AWT
AWT介绍
-
包含很多类和接口
-
元素:窗口,按钮,文本框 …
-
java.awt 包使用
容器和组件
窗口 Frame
import java.awt.*;
public class TestFrame1 {
public static void main(String[] args) {
//实例化
Frame frame = new Frame("我的第一个Frame!");
//需要设置可见性
frame.setVisible(true);
//设置窗口的大小
frame.setSize(400,400);
//设置背景颜色 color
frame.setBackground(Color.BLUE);
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
import java.awt.*;
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1 = new MyFrame(100,100,200,200,Color.BLUE);
MyFrame myFrame2 = new MyFrame(300,100,200,200,Color.YELLOW);
MyFrame myFrame3 = new MyFrame(100,300,200,200,Color.GREEN);
MyFrame myFrame4 = new MyFrame(300,300,200,200,Color.RED);
}
}
class MyFrame extends Frame{
//封装
static int id = 0;
public MyFrame(int x, int y, int w, int h, Color color) {
super("MyFrame + " + (++id));
setBounds(x,y,w,h);
setBackground(color);
setVisible(true);
}
}
面板Panel
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//Panel 可以看见是一个空间, 但是不能单独存在
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame();
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//设置frame 坐标,宽高,颜色
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(136, 65, 198));
//设置panel 坐标,宽高,颜色
panel.setBounds(50,50,400,400);
panel.setBackground(new Color(139, 237, 73));
//把panel 添加到frame 中
frame.add(panel);
设置可见性
frame.setVisible(true);
//监听事件,监听窗口关闭事件 System.exit(0)
//适配器模式:
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭的时候需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
布局管理器
- 流式布局
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()); //居中对齐
//frame.setLayout(new FlowLayout(FlowLayout.LEFT)); //左对齐
frame.setLayout(new FlowLayout(FlowLayout.RIGHT)); //右对齐
//设置大小
frame.setSize(200,200);
//把按钮添加上去
frame.add(button1);
frame.add(button2);
frame.add(button3);
//显示
frame.setVisible(true);
}
}
- 东西南北中
import java.awt.*;
public class TestBorderLayout {
public static void main(String[] args) {
Frame frame = new Frame();
//组件 - 按钮
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.