Concepts of Programming Languages

(Sean Pound) #1

658 Chapter 14 Exception Handling and Event Handling


itemStateChanged, which is the handler for ItemEvent events. So, to pro-
vide an action that is triggered by a radio button click, the interface Item-
Listener must be implemented, which requires a definition of the method,
itemStateChanged.
As stated previously, the connection of a component to an event listener
is made with a method of the class that implements the listener interface.
For example, because ItemEvent is the class name of event objects created
by user actions on radio buttons, the addItemListener method is used to
regis ter a listener for radio buttons. The listener for button events created in
a panel could be implemented in the panel or a subclass of JPanel. So, for
a radio button named button1 in a panel named myPanel that implements
the ItemEvent event handler for buttons, we would register the listener with
the following statement:

button1.addItemListener(this);

Each event handler method receives an event parameter, which provides
information about the event. Event classes have methods to access that infor-
mation. For example, when called through a radio button, the isSelected
method returns true or false, depending on whether the button was on or off
(pressed or not pressed), respectively.
All the event-related classes are in the java.awt.event package, so it is
imported to any class that uses events.
The following is an example application, RadioB, that illustrates the use
of events and event handling. This application constructs radio buttons that
control the font style of the contents of a text field. It creates a Font object for
each of four font styles. Each of these has a radio button to enable the user to
select the font style.
The purpose of this example is to show how events raised by GUI compo-
nents can be handled to change the output display of the program dynamically.
Because of our narrow focus on event handling, some parts of this program are
not explained here.

/* RadioB.java
An example to illustrate event handling with interactive
radio buttons that control the font style of a textfield
*/
package radiob;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioB extends JPanel implements
ItemListener {
private JTextField text;
Free download pdf