Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

confused by 'this' 1

Status
Not open for further replies.

welldefined

Programmer
Mar 9, 2006
62
0
0
GB
Hi,

In text1.addActionListener(this); what 'this' for? I remember sometimes 'this' is for the whole class.
 
this references the object that is calling the method - in this instance it is a reference to the object "text1"

-kaht

[small] <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
[banghead] [small](He's back)[/small]
 
You have to lookup the javadocs to find out, that text1.addActionListener (something) is expecting an ActionListener as Argument.

Then you look how an ActionListener is defined.

Well - it is defined as interface, which offers a method 'public void actionPerformed (ActionEvent ae)'.

Now you validate that 'this' is declared to implement an ActionListener, and look for that implementation.
That method is in general what is published by 'this'.

seeking a job as java-programmer in Berlin:
 
kaht,

Thank you. Why your explanation looks not the same as stefanwagner? Perhaps I misunderstood something?
 
stefanwagner,

Thank you. Did you mean this refers to ActionListener?
 
Kaht,
Sorry, your explanation is not correct.

'this' does not refer to 'text1' in the poster's example.

'this' refers to the object instance of your class.

Often, Swing classes will implement ActionLister, and register themselves as the class listening for events (as per the example).

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
sedj,

Thank you.

Can I use some instance object of another class to replace 'this' in text1.addActionListener(this);
 
Yes, the class you place in there has to implement ActionListener.

 
Define two classes :

Code:
public class MyListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
      //stuff
   }
}
public class SwingClass {

...
MyListener l = new MyListener();
text1.addActionListener(l);
}
[/code]

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Thanks a lot.
I think I understand method addActionListener() now!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top