《Java编程思想第四版》学习笔记42--关于“动态绑定事件”
  2BeoiZ3vpCmu 2023年11月25日 22 0
//: 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() {
        setLayout(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();
    }
} ///:~

                                                                                                                                                       P.431

该例程中单击多次Button 1在Button 2上添加多个CountListener接收器后,单击Button 2一次,Button 2上的所有CountListener接收器都会列出来。

《Java编程思想第四版》学习笔记42--关于“动态绑定事件”_sed

不知道为什么,求大神赐教!

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月25日 0

暂无评论

推荐阅读
  2Vtxr3XfwhHq   2024年05月17日   53   0   0 Java
  Tnh5bgG19sRf   2024年05月20日   107   0   0 Java
  8s1LUHPryisj   2024年05月17日   46   0   0 Java
  aRSRdgycpgWt   2024年05月17日   47   0   0 Java
2BeoiZ3vpCmu