I have often come across this way of registering an action listener.
Though I have been using this method recently but I don't understand how's and why's of this
Here is one :{
submit=new JButton("submit");
submit.addActionListener(new ActionListener(){ // line 1
public void actionPerformed(ActionEvent ae) {
submitActionPerformed(ae);
}
}); //action listener added
} Method that is invoked :
public void submitActionPerformed(ActionEvent ae) {
// body
}
In this method, I don't need to implement ActionListener. Why?
Also, please explain what the code labeled as line 1
does.
Please explain the 2 snippets clearly.
You technically did implement ActionListener. When you called addActionListener
:
submit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ae) {
submitActionPerformed(ae);
}
});
You created an instance of an anonymous class , or a class that implements ActionListener
without a name.
In other words, the snippet above is essentially like if we did this with a local inner class :
class MyActionListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
submitActionPerformed(ae);
}
}
submit.addActionListener(new MyActionListener());
For your example, the anonymous class just calls one of your member methods, submitActionPerformed
. This way, your method can have a slightly more descriptive name than actionPerformed
, and it also makes it usable elsewhere in your class besides the ActionListener.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.