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 ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH EDITION now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.