0

I dont understand what this refers to in the statement button.addActionListener(this); Is it referring to the recent object created, that is, 'button'? I've tried to put button as an argument instead of 'this' keyword, to test, but it gives an error. That means im not correct. Please enlighten me.

public class MainGUI implements ActionListener{

public static void main(String[] args) {
    // TODO Auto-generated method stub

    MainGUI gui = new MainGUI();
    gui.go();

}

public void go()
{
    JFrame frame = new JFrame("Hello World");
    JButton button = new JButton("Click Me");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    button.addActionListener(this);

    frame.getContentPane().add(button);
    frame.setSize(300, 300);
    frame.setVisible(true); 
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    button.setText("I've been clicked");
}

}

Farooq Khan
  • 305
  • 1
  • 3
  • 10
  • 1
    No, it's referring to whatever class encloses the `go()` method. Can you update your example to show that class? – markspace Oct 21 '15 at 17:20
  • 1
    @markspace it's not referring to the class, it's referring to the current object reference. – Luiggi Mendoza Oct 21 '15 at 17:21
  • @LuiggiMendoza, well, yes, but that's harder to describe. I think if the OP were to add the extra code I asked for, it would be easier to show them. – markspace Oct 21 '15 at 17:22
  • @markspace it may be harder but that's what it is, as explained in the first line of the accepted answer. – Luiggi Mendoza Oct 21 '15 at 17:22

0 Answers0