事件源:
文本框,按钮,菜单项,密码框,单选按钮
注册监视器:
能够触发ActionEvent事件的组件使用方法
addActionListener(ActionListener listener)
处理事件接口:
ActionListener接口中只有一个方法
public void actionPerformed(ActionEvent e)
事件触发ActionEvent事件后,监视器调用接口中的方法actionPerformed(ActionEvent e)对发生的事件做出处理
ActionEvent类中的方法:
ActionEvent类有如下常用方法
public Object getSource() 可以获取发生ActionEvent事件的事件源对象的引用
public String getActionCommand() 和该事件相关的一个“命令”字符串,对于文本框,当发生ActionEvent事件是,默认的“命令”字符串是文本框中的文本
主类
public class Example9_6 {
public static void main(String args[]) {
WindowActionEvent win=new WindowActionEvent();
win.setBounds(100,100,310,260);
win.setTitle("处理ActionEvent事件");
}
}
实现监视器的类
import java.awt.*;
import java.awt.event.*;
public class ReaderListen implements ActionListener{
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
System.out.println(str+":"+str.length());
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class WindowActionEvent extends JFrame {
TextField text;
ActionListener listener;
public WindowActionEvent() {
setLayout(new FlowLayout());
init();
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
void init() {
text = new TextField(10);
listener = new ReaderListen();
text.addActionListener(listener);
this.add(text);
}
}
public class Example9_7 {
public static void main(String args[]) {
WindowActionEvent win=new WindowActionEvent();
PoliceListen police = new PoliceListen();//创建监视器
win.setMyCommandListener(police);//窗口组合监视器
win.setBounds(100,100,310,260);
win.setTitle("处理ActionEvent事件");
}
}
import javax.swing.*;
import java.awt.event.*;//实现这些事件处理必须要有这个包event
public interface MyCommandListener extends ActionListener{
public void setTextField(JTextField text);
public void setJTextArea(JTextArea area);
}
import javax.swing.*;
import java.awt.event.*;
public class PoliceListen implements MyCommandListener{
JTextField textinput;
JTextArea textshow;
public void setTextField(JTextField text)
{
textinput=text;
}
public void setJTextArea(JTextArea area)
{
textshow=area;
}
public void actionPerformed(ActionEvent e)
{
String str = textinput.getText();
textshow.append(str+":"+str.length()+"\n");
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class WindowActionEvent extends JFrame {
JTextField text;//文本区
JTextArea textshow;//用于输出的文本框
JButton button;
MyCommandListener listener;//监视器
public WindowActionEvent() {
init();
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
void init() {
setLayout(new FlowLayout());//设置布局
text = new JTextField(10);
textshow = new JTextArea(9,30);
button = new JButton("确定");
this.add(text);
this.add(new JScrollPane(textshow));//设置为滚动窗格
this.add(button);
}
void setMyCommandListener(MyCommandListener listener)
{
this.listener=listener;
listener.setTextField(text);
listener.setJTextArea(textshow);
text.addActionListener(listener);
//text是事件源,listener是监视器
button.addActionListener(listener);
//button是事件源,listener是监视器
}
}