1

我是 Java/Android 新手。我不明白 addActionListener(this) 中的“this”。我读过很多书和论坛,但我仍然混淆以下内容:

有人解释:“this”是对当前对象的引用”

将事件处理程序类的实例注册为一个或多个组件的侦听器。someComponent.addActionListener(instanceofMyClass);

好的,我明白了,它是一个类的对象。

然而,有人解释说:“this”代表了一个实现和实例化的ActionListener,它恰好是你的类。

所以“this”可以是一个类的对象,也可以是一个“类”。这是我不明白的。

谁能给我解释清楚。谢谢!

4

4 回答 4

2

This总是引用当前对象,它不是一个类。有时人们在他们的意思是对象时错误地说类,仅此而已。

于 2013-10-13T02:39:05.773 回答
2

“this”指的是当前对象,因为 Java 使用方法来更改对象。所以,当你在 Activity 中调用“this”时,你就是在给你的方法一些改变。

您的代码“someComponent.addActionListener(instanceofMyClass);” 正在做同样的事情。您正在获取对象“someComponent”并使用方法“addActionListener”。然后 ActionListener 会想知道它将从哪里获取侦听器代码,并且您声明您希望从“instanceofMyClass”中调用它,它可以与“this”交换

您可以在这里找到另一种代码解释:Java 中“this”的含义是什么?

于 2013-10-13T02:40:25.560 回答
1

这就是发生的事情。在下面的示例中,SomeClass 实现了 ActionListener 接口,该接口只有一个需要实现的方法(actionPerformed,它将 ActionEvent 对象作为参数)。然而,为了实现这个方法,你需要一个对象。“this”指的是SomeClass的一个对象。

    public class SomeClass implements ActionListener{

    SomeClass(){
    Button aButton  = new Button("Click Me");
    aButton.addActionListener(this);
    }

     public static void main(String[] args) {
       SomeClass object = new SomeClass();
     }

    public void actionPerformed(ActionEvent e) {
     //do Something when user clicks the button
    }
}
于 2013-10-13T03:04:56.753 回答
1

在您的情况下,“this”既是“对当前对象的引用”又是“实现 ActionListener 接口的实现”。这意味着封闭类(“this”代表)应该实现接口 ActionListener。因此,当单击 someComponent(或其他操作)时,将调用封闭类来处理事件。

您可以参考下面的代码来了解这个想法:“this”代表 YourClass 的一个实例,它实现了 ActionListener

public YourClass implements ActionListener
{
  private someComponent;
  public YourClass ()
   {
   someComponent = new Component();
   someComponent.addActionListener(this);
   }

  public void actionPerformed()
  {
    //add code to process the event
  }
}
于 2013-10-13T02:47:34.270 回答