我知道何时为字段和构造函数使用关键字"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!");
}
}
Run Code Online (Sandbox Code Playgroud)
这条线button.addActionListener(this);
意味着:
button
对象上执行的操作添加侦听器SimpleGui
上下文中的当前实例(SimpleGui
恰好实现ActionListener
接口)因此,当单击按钮时,SimpleGui#actionPerformed
应该调用.