Setting Up Components to Be Heard

After you have implemented the interface needed for a particular component, you have to set that component to generate user events. A good example is the use of JButton objects as components. When you use a button in an interface, something has to happen in response to the click of the button. The program that should respond to the button-click must implement the ActionListener interface. This 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:

JButton fireTorpedos = new JButton("Fire torpedos");

This code creates the fireTorpedos button and then calls the button's addActionListener() method. The this statement used as an argument to the addActionListener() method indicates that the current object will receive the user event and handle it as needed.

By the way

Reader mail for past versions indicates that this throws a lot of people when they are introduced to it for the first time. The this keyword refers to the object in which the keyword appears. So if you create a LottoMadness class and use this in a statement, it's the LottoMadness object executing the statement.