Results 1 to 4 of 4
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default What does "this" refer to in this context?

    Hi guys:

    Here is my code:

    Java Code:
    package myPackage;
    public class TestClass {
    	public static void main(String[] args) {
    		FrameClass newFrame = new FrameClass();
    		newFrame.createFrame();
    	}
    }
    package myPackage;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;

    Java Code:
    import javax.swing.JButton;
    import javax.swing.JFrame;
    public class FrameClass implements ActionListener{
    	public void createFrame()
    	{
    		JFrame newFrame = new JFrame();
    		newFrame.setVisible(true);
    		newFrame.setSize(250, 250);
    		newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		JButton myButton = new JButton();
    		myButton.setText("I am a button!");
    		newFrame.getContentPane().add(myButton);
    		myButton.addActionListener(this);
    	}
    	@Override
    	public void actionPerformed(ActionEvent e) {
    		// TODO Auto-generated method stub
    	}
    }
    My question is:
    myButton.addActionListener(this);

    What does (this) do here?

    Does it create a new object of Class FrameClass ?

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,608
    Rep Power
    23

    Default Re: What does "this" refer to in this context?

    "this" is a reference variable that points at the object for the currently executing code.
    The "this" on line 13 refers to an instance of the FrameClass.

  3. #3
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: What does "this" refer to in this context?

    Thanks for the reply.

    "this" refers to an instance of the FrameClass. Which istance is it ?

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,608
    Rep Power
    23

    Default Re: What does "this" refer to in this context?

    It will be the one that the method that is executing belongs to.

Similar Threads

  1. Replies: 4
    Last Post: 03-14-2011, 12:05 AM
  2. Replies: 3
    Last Post: 10-12-2010, 04:21 PM
  3. Replies: 1
    Last Post: 01-21-2010, 09:20 AM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •