Timothy Kodes
Timothy Kodes

Reputation: 456

What is the keyword "this" referring to if it is given as an argument

I know when to use the keyword "this" for fields and constructors but I'm not sure when it is passed as an argument

    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!");
    }
}

Upvotes: 1

Views: 130

Answers (3)

This is a keyword which means the instance of the class, in your class

 public class SimpleGui implements ActionListener {

this is an instance of the SimpleGui, it could be as well an object (any) that is implementing the actionListener

If you call a method that accepts this, it is because this argument is an object of the SimpleGui class, or even better, is an object (no matter which one) that implements the ActionListener.

Upvotes: 0

JTeam
JTeam

Reputation: 1505

Whenever a button is presses to get a callback, we need to attach a listener to that button, here in your example that is done using following line,

button.addActionListener(this);

addActionListener() requires to pass a instance which implements ActionListener interface.

And here SimpleGui is a ActionListener as it implements that interface. Hence in SimpleGui you are writing,

button.addActionListener(this);

where this is instance of SimpleGui which implements ActionListener

Upvotes: 1

Mena
Mena

Reputation: 48404

The line button.addActionListener(this); means:

  • Add a listener to actions performed on the button object
  • Make the listener the current instance of SimpleGui within context (SimpleGui happens to implement the ActionListener interface)

So when the button is clicked, SimpleGui#actionPerformed should be invoked.

Upvotes: 6

Related Questions