Java教程-Java事件处理

Java事件处理
改变对象状态被称为事件。例如,点击按钮、拖动鼠标等。java.awt.event 包提供了许多事件类和监听器接口来进行事件处理。
Java事件类和监听器接口
事件类 | 监听器接口 |
---|---|
ActionEvent | ActionListener |
MouseEvent | MouseListener and MouseMotionListener |
MouseWheelEvent | MouseWheelListener |
KeyEvent | KeyListener |
ItemEvent | ItemListener |
TextEvent | TextListener |
AdjustmentEvent | AdjustmentListener |
WindowEvent | WindowListener |
ComponentEvent | ComponentListener |
ContainerEvent | ContainerListener |
FocusEvent | FocusListener |
执行事件处理的步骤
执行事件处理需要以下步骤:
将组件与监听器注册
注册方法
为了将组件与监听器注册,许多类提供了注册方法。例如:
Button
- public void addActionListener(ActionListener a){}
MenuItem
- public void addActionListener(ActionListener a){}
TextField
- public void addActionListener(ActionListener a){}
- public void addTextListener(TextListener a){}
TextArea
- public void addTextListener(TextListener a){}
Checkbox
- public void addItemListener(ItemListener a){}
Choice
- public void addItemListener(ItemListener a){}
List
- public void addActionListener(ActionListener a){}
- public void addItemListener(ItemListener a){}
Java事件处理代码
我们可以将事件处理代码放在以下位置之一:
- 类内部
- 其他类
- 匿名类
通过实现 ActionListener 进行 Java 事件处理
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//创建组件
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//注册监听器
b.addActionListener(this);//传递当前实例
//添加组件并设置大小、布局和可见性
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
上面的示例中使用了 public void setBounds(int xaxis, int yaxis, int width, int height) 方法,该方法设置了组件(可以是按钮、文本字段等)的位置。
2)通过外部类进行 Java 事件处理
import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
3)通过匿名类进行 Java 事件处理
import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}