事件处理

事件和事件源

事件类和事件监听接口

实例

TestActionListener

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
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class TestActionListener extends JFrame implements ActionListener {
public TestActionListener() {
this.setBounds(100, 200, 100, 200);
JButton btnOk = new JButton("打开");
btnOk.addActionListener(this);
this.getContentPane().add(btnOk);
}

public void actionPerformed(ActionEvent e) {
JFileChooser fchooser = new JFileChooser(new File("."));
if (fchooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File file = fchooser.getSelectedFile();
try {
BufferedReader fir = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String aline;
while ((aline = fir.readLine()) != null) {
System.out.println(aline);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

public static void main(String[] args) {
TestActionListener frame = new TestActionListener();
frame.setVisible(true);
}
}

TestActionEvent

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
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestActionEvent {
public static void main(String args[]) {

Frame f = new Frame("Test");
Button b = new Button("Press Me!");

//Monitor bh = new Monitor();

b.addActionListener(new Monitor());


f.add(b,BorderLayout.CENTER);

f.pack();
f.setVisible(true);
}
}


class Monitor implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("a button has been pressed");
}
}

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
import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TestActionEvent2 {

public static void main(String args[]) {

Frame f = new Frame("Test");
Button b1 = new Button("Start");
Button b2 = new Button("Stop");

Monitor2 bh = new Monitor2();

b1.addActionListener(bh);

b2.addActionListener(bh);

//b2.setActionCommand("game over");

f.add(b1,"North");

f.add(b2,"Center");

f.pack();

f.setVisible(true);
}
}

class Monitor2 implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("a button has been pressed," +
"the relative info is:\n " + e.getActionCommand());

}

}