什么addActionListener方法呢? [英] What addActionListener does?

查看:1348
本文介绍了什么addActionListener方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

JButton button = new JButton("Clear");
button.addActionListener(this);

据我了解,我创建的,它是写清除按钮。然后,我必须用此按钮的动作(如按钮pressed会发生什么)相关联,它是由 addActionListener方法完成。是不是?

但我不明白的是指定的操作位置。按钮的preSS应该清除文本区域,而且据我了解,应该有一个地方code从而清除文本区域。但是,在给定的示例中,只有本中的参数在 addActionListener方法()

But what I do not understand is where the action is specified. The press of the button should clear text area and, as far as I understand, there should be somewhere a code which clear the text area. But in the given example there is only "this" in the arguments of the addActionListener().

程序如何知道,当按钮pssed $ P $应该清除文本区域?

How the program knows that it should clear the text area when the button is pressed?

如果需要的话,满code给出<一个href=\"http://java.sun.com/docs/books/tutorial/uiswing/examples/events/KeyEventDemoProject/src/events/KeyEventDemo.java\"相对=nofollow>这里。

If it is needed, the full code is given here.

推荐答案

这是<一个href=\"http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html\"><$c$c>ActionListener是一个回调的机制。当它被添加到火灾的的ActionEvent 公共无效的actionPerformed(ActionEvent的五)方法将被调用的控制。

An ActionListener is a callback mechanism. Whenever a control it is added to fires an ActionEvent, the public void actionPerformed(ActionEvent e) method will be invoked.

我不明白的是,其中的actionPerformed被调用。我看到它是在类中定义但没有地方调用此方法。

What I do not understand is where the actionPerformed is called. I see that it is defined within the class but there is no place where this method is called.

这是由UI组件的内部机制调用。从概念上讲,你能想到的code的看起来有点像这样:

This is called by the internal mechanisms of the UI component. Conceptually, you can think of the code looking a bit like this:

public class Button {
  private final List<ActionListener> listeners = new ArrayList<ActionListener>();

  public void addActionListener(ActionListener l) {
    listeners.add(l);
  }

  public void click() {
    ActionEvent event = new ActionEvent(this, 0, "click");
    for (ActionListener l : listeners) {
      l.actionPerformed(event);
    }
  }
}

这篇关于什么addActionListener方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆