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);

This code creates the fireTorpedos button and calls the button’s addActionListener() method. The this keyword used as an argument to the addActionListener() method indicates the current object receives the user event and handles it as needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157