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");
fireTorpedos.addActionListener(this);

This code creates the fireTorpedos ...

Get SAMS Teach Yourself Programming with Java™ in 24 Hours, FOURTH 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.