Sams Teach Yourself Java 2 in 24 Hours

Sams Teach Yourself Java 2 in 24 Hours

By Rogers Cadenhead

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, use the addActionListener() method, as in the following:

JButton fireTorpedos = new JButton("Fire torpedos"); 
fireTorpedos.addActionListener(this); 

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.

Share ThisShare This

Informit Network