如果关键字 "this" 作为参数给出,它指的是什么
What is the keyword "this" referring to if it is given as an argument
我知道何时对字段和构造函数使用关键字 "this" 但我不确定何时将其作为参数传递
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui implements ActionListener {
JButton button;
public static void main (String[] args) {
SimpleGui gui = new SimpleGui();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked!");
}
}
行button.addActionListener(this);
表示:
- 为在
button
对象上执行的操作添加侦听器
- 使侦听器成为上下文中
SimpleGui
的当前实例(SimpleGui
恰好实现了 ActionListener
接口)
所以当按钮被点击时,SimpleGui#actionPerformed
应该被调用。
这是一个关键字,表示class的实例,
在你的 class
public class SimpleGui implements ActionListener {
this
是 SimpleGui 的实例,它也可以是实现 actionListener[=22] 的对象(任何) =]
如果你调用一个接受this
的方法,那是因为
这个参数是 SimpleGui class 的一个对象,或者更好的是,是一个实现 ActionListener.
的对象(无论哪个)
每当按下按钮以获取回调时,我们需要将侦听器附加到该按钮,在您的示例中使用以下行完成,
button.addActionListener(这个);
addActionListener()需要传递一个实现了ActionListener接口的实例。
这里的 SimpleGui 是一个 ActionListener,因为它实现了该接口。因此在 SimpleGui 中你正在写,
button.addActionListener(这个);
这是实现 ActionListener 的 SimpleGui 实例
我知道何时对字段和构造函数使用关键字 "this" 但我不确定何时将其作为参数传递
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui implements ActionListener {
JButton button;
public static void main (String[] args) {
SimpleGui gui = new SimpleGui();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked!");
}
}
行button.addActionListener(this);
表示:
- 为在
button
对象上执行的操作添加侦听器 - 使侦听器成为上下文中
SimpleGui
的当前实例(SimpleGui
恰好实现了ActionListener
接口)
所以当按钮被点击时,SimpleGui#actionPerformed
应该被调用。
这是一个关键字,表示class的实例, 在你的 class
public class SimpleGui implements ActionListener {
this
是 SimpleGui 的实例,它也可以是实现 actionListener[=22] 的对象(任何) =]
如果你调用一个接受this
的方法,那是因为
这个参数是 SimpleGui class 的一个对象,或者更好的是,是一个实现 ActionListener.
每当按下按钮以获取回调时,我们需要将侦听器附加到该按钮,在您的示例中使用以下行完成,
button.addActionListener(这个);
addActionListener()需要传递一个实现了ActionListener接口的实例。
这里的 SimpleGui 是一个 ActionListener,因为它实现了该接口。因此在 SimpleGui 中你正在写,
button.addActionListener(这个);
这是实现 ActionListener 的 SimpleGui 实例