Reputation: 39
I'm learning java and despite a bit of googling and reading various threads on here I'm still not entirely clear on event handling. See below and apologies if this appears obvious but I'm self-taught and so would appreciate not being down marked for this ---you were learners once too!!
Consider the following code:
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(this);
fileMenu.add(openItem);
In the above, i'm creating a menu item and passing an object of the current class i'm writing as a parameter represented by the 'this'. This then triggers the interface 'Action Listener' which I've implemented in my class, so this in turn fires off the actionPerformed method with an event parameter of type ActionEvent that provides details about the event that has occurred. My questions are:
I can't find the addActionListener method in the JMenuItem class, where is this? and does this method call the ActionListener interface which results in the actionPerformed method?
Many thanks!
Upvotes: 0
Views: 1187
Reputation: 181932
I can't find the addActionListener method in the JMenuItem class, where is this?
When you say you can't find it, I suppose you must mean you can't find it in the class's API docs. If you look a little further down in the docs, you will find it listed among the methods inherited from this class's superclass, javax.swing.AbstractButton
. The method is documented there, though you'll find that particular doc not to be very illuminating.
and does this method call the ActionListener interface which results in the actionPerformed method?
Not directly, no. It records a reference to the argument (an instance of your class in this case), so that that object's actionPerformed()
method can be invoked later, when the menu item is selected.
Overall, if you're trying to write a GUI with Swing then you should probably take the Swing trail in the Java Tutorial. It has lots of information about these and similar questions you will likely have.
Upvotes: 1
Reputation: 15634
I can't find the addActionListener method in the JMenuItem class, where is this?
You're observing one of the main features of OOP: inheritance
JMenuItem inherits the addActionListener
method from AbstractButton As you can see in the public API documentation: https://docs.oracle.com/javase/8/docs/api/javax/swing/JMenuItem.html
and does this method call the ActionListener interface which results in the actionPerformed method?
Yes it does.
Upvotes: 0