Here’s the situation :
My understanding is that when providing the argument to a method ( in this case, it will be the “addActionListener” method, from the “AbstractButton” class ), the object provided needs to be either of the type required ( ie: “ActionListener” for “addActionListener” ) or of a class implementing the class of the required type ( ie: a class implementing “ActionListener” interface ).
Also, according to my understanding, “this” refers to the class instance whose method is currently being called, or the containing class otherwise.
Now here’s some simple code :
public class Window extends JFrame implements ActionListener {
public Window () {
...
private JRadioButton btn = new JRadioButton("Option");
btn.addActionListener(this);
}
public actionPerformed ( ActionEvent e ) {
...
...
}
}
So here is my question : this bit of code works as it should : the “this” keyword refers to the instance of the object whose method is being called ( “btn” ) , the button acts as its own listener (this is what is intended ) , and the actionPerformed method is called, as expected, when the button is clicked. However, I don’t understand why this is the case because of the following :
- addActionListener asks for an ActionListener as an argument
- “btn” is of type JRadioButton
- JRadioButton is NOT of type ActionListener
- JRadioButton DOES NOT implement ActionListener ( nor do the parent classes )
Can someone clear up the fact that addActionListener accepts this argument which to me seems to be of the wrong type ?
Note : I understand that the Window class in this example does implement ActionListener, but I don’t see how this interacts with the type of the btn variable and the type requested by addActionListener.
Thanks for your time,
Jay
The
thisinstance here refers to the instance of your classWindowand not theJRadioButton.As the class
WindowimplementsActionListener, so its implementation ofactionPerformedcan serve as the concrete implementation for theJRadioButtoncomponent providing interaction between the 2 classes.