Java ".addActionListener(this)"
If I add a Action Listener then I always use the "thi开发者_开发知识库s" between the brackets. But what does this "this" stand for ?!
The addActionListener method takes the current class object as a parameter. The "this" key word simply means "this object I'm working in right now". If you are using netbeans, you can type "this" and put a period after it to see all the methods defined in "this" class. It should list all the methods that are defined in your class including any inherited methods.
In order to fully understand what "this" means, you must first understand the relationship between classes and objects.
If you want to be technical about it, "this" is a reference to the current object.
"this" stands for the current class instance that you are inside.
It will work as long as the class implements the ActionListener interface.
You can use a completely different object if you like, e.g. creating an anonymous inner class that implements the ActionListener interface:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello!!!");
}
});
This is helpful if you want to have multiple different action listeners but don't want to create separate classes for each.
If you look at the tutorial then you will see...
To write an Action Listener, follow the steps given below:
Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface.
For example:
public class MyClass implements ActionListener {
Register an instance of the event handler class as a listener on one or more components.
For example:
someComponent.addActionListener(instanceOfMyClass);
Include code that implements the methods in listener interface.
For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
The this represents an implemented and instantiated ActionListener, which happens to be your class. You could very well pass any class that implements the ActionListener interface.
That way when a button is pressed the your actionPerformed method will be called
精彩评论