J2EE中基于监听方式的事件处理机制

来源:互联网 发布:淘宝代运营 编辑:程序博客网 时间:2024/06/06 01:13

Action及ActionListener机制分析

一般地,面向对象分析与设计中存在三种事件处理的机制,除了普通的方法调用外,常常用到回调函数,而J2EE中还提供了一种基于监听方式的事件处理机制,请查阅资料,对Action以及ActionListener的机制进行分析,完成一个分析示例

概述

Java中UI控件上可以添加ActionListener进行Action事件监听,而ActionListener接收到的Action事件是ActionEvent,派生列表如下

java.lang.Object
|— extended by java.util.EventObject
|—|— extended by javax.faces.event.FacesEvent
|—|—|— extended by javax.faces.event.ActionEvent

ActionListener的实现事件处理的步骤

  • 定义一个处理事件的类MyClass,并指定该类是实现ActionListener接口或者继承一个实现ActionListener接口的类
public class AL implements ActionListener{}
  • 实例化类AL,作为一个或多个组件的事件监听器
someComponent.addActionListener(instanceOfAL);
  • 编写ActionListener接口中的actionPerformed方法的具体内容
public void actionPerformed(ActionEvent e) {     ...//code that reacts to the action... }

通常,一个程序必须通过实现ActionListener接口来检测屏幕上的按钮的鼠标点击事件,当用户使用鼠标点击按钮时,将会触发一个action event,通过ActionEvent传递该事件的信息以及来源到AL类中,调用actionPerformed()方法,从而对鼠标点击做出最终响应。

下面是一个点击Button,在旁边的文本框内显示点击次数的示例代码AL.java

import java.awt.*;import java.awt.event.*;public class AL extends Frame implements WindowListener,ActionListener {    TextField text = new TextField(20);    Button a;    private int numClicks=0;    public static void main(String[] args) {        AL myWindow = new AL("My first window");        myWindow.setSize(350,100);        myWindow.setVisible(true);    }    public AL (String title){        super(title);        setLayout(new FlowLayout());        addWindowListener(this);        a=new Button("Click me");        add(a);        add(text);        a.addActionListener(this);    }    public void actionPerformed(ActionEvent e){        numClicks++;        text.setText("Button Clicked "+numClicks+" times");    }    public void windowClosing(WindowEvent e){        dispose();        System.exit(0);    }    public void windowOpened(WindowEvent e){}    public void windowActivated(WindowEvent e){}    public void windowIconified(WindowEvent e){}    public void windowDeiconified(WindowEvent e){}    public void windowDeactivated(WindowEvent e){}    public void windowClosed(WindowEvent e){}}

运行结果截图

截图

参考资料

  1. How to Write an Action Listener
  2. java里的ActionListener监听的是什么事件?
  3. Java 8 API
原创粉丝点击