GUI编程
简介:
图形用户界面(Graphical User Interface,简称 GUI,又称图形用户接口)是指采用图形方式显示的计算机操作用户界面。
GUI的核心技术: Swing AWT
缺点:
- 界面不美观
- 需要在jre环境下运行
学习GUI可以了解MVC架构,了解监听!
AWT
AWT(Abstract Window Toolkit),抽象窗口工具包,该包提供了一套与本地图形界面进行交互的接口,是Java提供的用来建立和设置Java的图形用户界面的基本工具。
组件和容器
1. 窗体Frame
public class TestFrame {
public static void main(String[] args) {
Frame frame = new Frame("我的第一个Java图形界面窗口");
//需要设置可见性
frame.setVisible(true);
//设置窗口大小
frame.setSize(400,400);
//设置背景颜色 Color
frame.setBackground(Color.white);
//弹出的初始位置
frame.setLocation(200,200);
//设置大小固定
frame.setResizable(false);
}
}
问题:窗口无法关闭
尝试将生成窗口的方法进行封装
public class TestFrame2 {
public static void main(String[] args) {
//展示多个窗口
MyFrame myFrame1=new MyFrame(100,100,200,200,Color.black);
MyFrame myFrame2=new MyFrame(300,100,200,200,Color.darkGray);
MyFrame myFrame3=new MyFrame(100,300,200,200,Color.cyan);
MyFrame myFrame4=new MyFrame(300,300,200,200,Color.BLUE);
}
}
class MyFrame extends Frame{
//封装
static int id=0;//可能存在多个窗口,需要一个计数器
public MyFrame(int x, int y,int w,int h,Color color){
super("Myframe"+(++id));
setVisible(true);
setBounds(x, y, w, h);
setBackground(color);
setResizable(false);
} ;
}
2. 面板Panel
解决了窗体关闭事件!
public class Testpanel {
//面板
public static void main(String[] args) {
// Panel 可以看成是一个空间,但是不能单独存在
Frame frame = new Frame();
//生成面板
Panel panel = new Panel();
//设置布局
frame.setLayout(null);
//frame设置
frame.setBounds(300, 300, 500, 500);
frame.setBackground(Color.LIGHT_GRAY);
//panel 设置坐标,相对于frame
panel.setBounds(50, 50, 400, 400);
panel.setBackground(Color.darkGray);
//frame.add(panel)
frame.add(panel);
frame.setVisible(true);
//监听事件,监听窗口关闭事件 System.exit(0)
//适配器模式:
frame.addWindowListener(new WindowAdapter() {
//窗口点击关闭的时候需要做的事情
@Override
public void windowClosing(WindowEvent e) {
//结束程序
System.exit(0);
}
});
}
}
3. 布局管理器
- 流式布局
//组件-按钮
Button Button1=new Button("button1");
Button Button2=new Button("button2");
Button Button3=new Button("button3");
//设置为流式布局
//frame.setLayout(new FlowLayout()); //默认为center
frame.setLayout(new FlowLayout(FlowLayout.LEFT));
frame.setSize(200, 200);
frame.setVisible(true);
frame.add(Button1);
frame.add(Button3);
frame.add(Button2);
- 东西南北中
Frame frame = new Frame("TestBorderLayout");
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(north,BorderLayout.NORTH);
frame.add(south,BorderLayout.SOUTH);
frame.add(center,BorderLayout.CENTER);
- 表格式布局
Frame frame = new Frame("TestBorderLayout");
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);
frame.pack(); //自动布局