Setting Up Components to Be Heard
After you have implemented the interface needed for a particular component, you must set that component to generate user events. The ActionListener
interface listens for action events, such as a button-click or the press of the Enter key. To make a JButton
object generate an event, employ the addActionListener()
method, as in the following:
Note
The this
keyword confuses a lot of readers when they are first introduced to it. this
refers to the object in which the keyword appears. So, if you create a LottoMadness
class and use this
in a statement inside that class, it refers to the LottoMadness
object executing the code.
JButton fireTorpedos = new JButton("Fire torpedos");fireTorpedos.addActionListener(this ...
Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.