1.概念
GUI:图像对象接口
CLI:命令行用户接口
Awt:抽象窗口工具包。调用本地系统方法实现,重量级。
Swing:图形界面系统。在Awt基础上完全由java实现,轻量级
2.GUI继承图
Component左边Container是容器,右边是组件。
容器可以通过Add方法添加组件。
3.容器中组件的排列方式:布局
FlowLayout:流式布局管理器(Panel的默认布局方式)
BorderLayout:边界布局管理器(Window的默认布局方式)
GridLayout:网格布局管理器
GridBagLayout:网格包布局管理器
CardLayout:卡片布局管理器
4.事件监听机制
(1).将监听器绑定到事件源上
(2).当监听器监听到对应的动作作用在事件源上
(3).生成事件对象
(4).交给监听器的事件处理方式处理
注:当同一个监听器监听多个事件的时候,用适配器来生成事件监听方式
5.实例:
public static void main(String[] args){
Frame f = new Frame();
f.setSize(400,500);
f.setLocation(400,200);
Button b = new Button("My Button");
f.add(b);
f.setVisible(true);
}
//按钮绑定事件监听
b.addActionListener(new ActionListener(){
public void actionPerform(ActionEvent e){
System.exit(0);
}
}
);
//按钮绑定鼠标事件
b.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
super.mouseClicked(e);
if(e.getClickCount == 2){
System.out.println("鼠标被点了2次");
}
}
}
);
//窗口点击X绑定关闭窗口
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
);
//绑定键盘
TextField tf = new TextFiele(40);
tf.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
super.keyPressed(e);
char key = e.getKeyChar();
int code = e.getKeyCode();
if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){
System.out.println("必须是数字");
e.consume();//不运行
}
if(e.isControlDown() && code == KeyEvent.VK_ENTER){
System.out.println("ctrl+enter run");
}
}
}
);