Concepts of Programming Languages

(Sean Pound) #1

656 Chapter 14 Exception Handling and Event Handling


on the browser to check the validity of form data saves the time of sending
that data to the server, where their correctness then must be checked by a
server-resident program or script before they can be processed. This kind of
event-driven programming is often done using a client-side scripting language,
such as JavaScript.

14.6 Event Handling with Java


In addition to Web applications, non-Web Java applications can present GUIs
to users. GUIs in Java applications are discussed in this section.
The initial version of Java provided a somewhat primitive form of sup-
port for GUI components. In version 1.2 of the language, released in late
1998, a new collection of components was added. These were collectively
called Swing.

14.6.1 Java Swing GUI Components


The Swing collection of classes and interfaces, defined in javax.swing,
includes GUI components, or widgets. Because our interest here is event han-
dling, not GUI components, we discuss only two kinds of widgets: text boxes
and radio buttons.
A text box is an object of class JTextField. The simplest JTextField
constructor takes a single parameter, the length of the box in characters. For
example,

JTextField name = new JTextField(32);

The JTextField constructor can also take a literal string as an optional
first parameter. This string parameter, when present, is displayed as the initial
contents of the text box.
Radio buttons are special buttons that are placed in a button group con-
tainer. A button group is an object of class ButtonGroup, whose constructor
takes no parameters. In a radio button group, only one button can be pressed
at a time. If any button in the group becomes pressed, the previously pressed
button is implicitly unpressed. The JRadioButton constructor, used for cre-
ating radio buttons, takes two parameters: a label and the initial state of the
radio button (true or false, for pressed and not pressed, respectively). If
one radio button in a group is initially set to pressed, the others in the group
default to unpressed. After the radio buttons are created, they are placed in
their button group with the add method of the group object. Consider the
following example:

ButtonGroup payment = new ButtonGroup();
JRadioButton box1 = new JRadioButton("Visa", true);
Free download pdf