Java-GUI

  • GUI(Graphical User Interface) 即图形用户界面,更方便更直接

AWT简介

  • 在Java的早期版本中,GUI组件由名为AWT(Abstract Window Toolkit,抽象窗口工具包)的标准库来提供。

继承关系图

事件监听机制

  • 组成
    • 事件源
    • 事件
    • 监听器
    • 处理方式

简易代码演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class MouseAndKeyDemo {

private Frame f;
private TextField tf;
private Button but;

public MouseAndKeyDemo() {
init();
}

private void init() {

f = new Frame("演示鼠标和键盘监听");
f.setBounds(400,200,500,400);
//设置流式布局
f.setLayout(new FlowLayout());

tf = new TextField(35);
but = new Button("一个按钮");

f.add(tf);
//将按钮添加到窗体中。
f.add(but);

myEvent();
//可视化
f.setVisible(true);
}


private void myEvent() {
//给文本框添加键盘监听。
tf.addKeyListener(new KeyAdapter() {

@Override
public void keyPressed(KeyEvent e) {

System.out.println("key run..."+ KeyEvent.getKeyText(e.getKeyCode())
+"::::"+e.getKeyCode());
int code = e.getKeyCode();
if(!(code>=KeyEvent.VK_0 && code<=KeyEvent.VK_9)){
System.out.println("必须是数字");
//非数字字符无法显示在文本框
e.consume();
}
}
});

f.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
//终止程序
System.exit(0);
}

});

but.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
// System.out.println("action run.....");
}
});

//在按钮上添加一个鼠标监听.
but.addMouseListener(new MouseAdapter() {

private int count = 1;
@Override
public void mouseEntered(MouseEvent e) {
System.out.println("mouse enter..."+count++);
}
@Override
public void mouseClicked(MouseEvent e) {
//双击
if(e.getClickCount()==2)
tf.setText("mouse double click..."+count++);
}
});
}
}

public class test{
public static void main(String[] args) {
new MouseAndKeyDemo();
}
}

Swing

  • Swing都是图形化的,很多代码都可以系统自动生成,就不详细说了
  • Swing不是线程安全的