什么是关键字"this"指的是它是否作为参数给出

tim*_*thy 1 java this keyword

我知道何时为字段和构造函数使用关键字"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)

Men*_*ena 6

这条线button.addActionListener(this);意味着:

  • 为在button对象上执行的操作添加侦听器
  • 使监听器成为SimpleGui上下文中的当前实例(SimpleGui恰好实现ActionListener接口)

因此,当单击按钮时,SimpleGui#actionPerformed应该调用.