java事件处理机制
时间: 2023-12-18 16:30:17 浏览: 67
Java事件处理机制是一种基于委派事件模型的机制。当事件发生时,产生事件的对象会将事件的信息传递给事件的监听者进行处理。事件的信息实际上是由java.awt.event事件类库中的某个类创建的对象。
以下是几种Java事件处理的方式:
1. 使用Action和ActionListener机制:
```java
import java.awt.*;
import java.awt.event.*;
public class MyButton extends Frame {
private Button button;
public MyButton() {
button = new Button("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
add(button);
setSize(300, 200);
setVisible(true);
}
public static void main(String[] args) {
new MyButton();
}
}
```
2. 使用普通方法调用:
```java
import java.awt.*;
import java.awt.event.*;
public class MyButton extends Frame {
private Button button;
public MyButton() {
button = new Button("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonClicked();
}
});
add(button);
setSize(300, 200);
setVisible(true);
}
public void buttonClicked() {
System.out.println("Button clicked");
}
public static void main(String[] args) {
new MyButton();
}
}
```
3. 使用回调函数:
```java
import java.awt.*;
import java.awt.event.*;
public class MyButton extends Frame {
private Button button;
public MyButton() {
button = new Button("Click me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonClicked(new ButtonEvent());
}
});
add(button);
setSize(300, 200);
setVisible(true);
}
public void buttonClicked(ButtonEvent event) {
System.out.println("Button clicked");
}
public static void main(String[] args) {
new MyButton();
}
}
class ButtonEvent {
// Event data
}
```
4. 使用观察者模式:
```java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class MyButton extends Frame {
private Button button;
private List<ActionListener> listeners;
public MyButton() {
button = new Button("Click me");
listeners = new ArrayList<ActionListener>();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (ActionListener listener : listeners) {
listener.actionPerformed(e); }
}
});
add(button);
setSize(300, 200);
setVisible(true);
}
public void addActionListener(ActionListener listener) {
listeners.add(listener);
}
public static void main(String[] args) {
MyButton myButton = new MyButton();
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
});
}
}
```
阅读全文