java的动态绑定事件_java中的AWT动态绑定事件

新AWT事件模型给我们带来的一个好处就是灵活性。在老的模型中我们被迫为我们的程序动作艰难地编写代码。但新的模型我们可以用单一方法调用增加和删除事件动作。下面的例子证明了这一点:

f27df44984d0138cf73dcbc5ecefd21e.png

//: DynamicEvents.java

// The new Java 1.1 event model allows you to

// change event behavior dynamically. Also

// demonstrates multiple actions for an event.

import java.awt.*;

import java.awt.event.*;

import java.util.*;

public class DynamicEvents extends Frame {

Vector v = new Vector();

int i = 0;

Button

b1 = new Button("Button 1"),

b2 = new Button("Button 2");

public DynamicEvents() {

sayout(new FlowLayout());

b1.addActionListener(new B());

b1.addActionListener(new B1());

b2.addActionListener(new B());

b2.addActionListener(new B2());

add(b1);

add(b2);

}

class B implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("A button was pressed");

}

}

class CountListener implements ActionListener {

int index;

public CountListener(int i) { index = i; }

public void actionPerformed(ActionEvent e) {

System.out.println(

"Counted Listener " + index);

}

}

class B1 implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("Button 1 pressed");

ActionListener a = new CountListener(i++);

v.addElement(a);

b2.addActionListener(a);

}

}

class B2 implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("Button 2 pressed");

int end = v.size() -1;

if(end >= 0) {

b2.removeActionListener(

(ActionListener)v.elementAt(end));

v.removeElementAt(end);

}

}

}

public static void main(String[] args) {

Frame f = new DynamicEvents();

f.addwindowListener(

new WindowAdapter() {

public void windowClosing(WindowEvent e){

System.exit(0);

}

});

f.setSize(300,200);

f.show();

}

} ///:~

这个例子采取的新手法包括:

(1) 在每个按钮上附着不少于一个的接收器。通常,组件把事件作为多造型处理,这意味着我们可以为单个事件注册许多接收器。当在特殊的组件中一个事件作为单一造型被处理时,我们会得到TooManyListenersException(即太多接收器异常)。

(2) 程序执行期间,接收器动态地被从按钮B2中增加和删除。增加用我们前面见到过的方法完成,但每个组件同样有一个removeXXXListener()(删除XXX接收器)方法来删除各种类型的接收器。

这种灵活性为我们的编程提供了更强大的能力。

我们注意到事件接收器不能保证在命令他们被增加时可被调用(虽然事实上大部分的执行工作都是用这种方法完成的)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值