【问题标题】:Why does the addActionListener method need these stages?为什么 addActionListener 方法需要这些阶段?
【发布时间】:2016-06-02 01:15:32
【问题描述】:
b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ea){
            System.exit(0);
        }
    });

我正在学习Java,看到了上面的代码。 我不明白为什么 addActionlisetner 方法需要 Actionlistener 作为参数。 直接使用System.exit(0)不是更简单吗?

【问题讨论】:

    标签: java arguments actionlistener system.exit


    【解决方案1】:

    您有API Java 作为参考来找到您的问题的答案。

    public void addActionListener(ActionListener l)

    向按钮添加一个 ActionListener。

    参数:

    l - 要添加的 ActionListener

    例如,具体类JButton从类javax.swing.AbstractButton继承了方法addActionListener(ActionListener l)

    当你这样做时:

    new ActionListener(){
        public void actionPerformed(ActionEvent ea){
            System.exit(0);
        }
    }
    

    您正在创建 ActionListener 的 anonymous subclass 的实例。

    ActionListener 是一个用于接收动作事件的接口。

    API 说:

    对处理动作事件感兴趣的类实现此接口,使用该类创建的对象使用组件的 addActionListener 方法注册到组件。当动作事件发生时,该对象的 actionPerformed 方法被调用。

    【讨论】:

      【解决方案2】:

      这就是 Java 的工作原理。您需要将匿名类的实例传递给addActionListener() 方法(毕竟它是一个侦听器)。

      这就是您使用 Java 7 或更早版本的方式。但是,使用 Java 8,您可以使用 lambda 表达式来缩短代码(因为ActionListener 是一个函数式接口):

      // You can do this
      b.addActionListener((ActionEvent) ae -> System.exit(0));
      // or this
      b.addActionListener((ActionEvent) ae -> {
          System.exit(0);
      });
      // or even better, this
      b.addActionListener(ae -> System.exit(0));
      

      【讨论】:

        【解决方案3】:

        addActionListener 的参数指定事件处理程序类的实例作为组件的侦听器(在本例中为“b”) 传递匿名类 'ActionListener' 的实例或您自己的类 (b.actionListener(this)) 的实例,两者都可以工作。

        【讨论】:

          【解决方案4】:

          基本上,当你按下一个按钮时,ActionListener 类中的actionPerformed() 方法就会被调用。

          您不能拥有b.addActionListener(System.exit(0));,因为System.exit(0) 是一种方法。在 Java 中,您不能将方法作为参数传递,但可以传递类。

          【讨论】:

            猜你喜欢
            • 2022-01-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多