Java Reference
In-Depth Information
The
QuoteOptionsPanel
class, shown in Listing 5.17, sets up and displays
the GUI components. A radio button is represented by the
JRadioButton
class.
Because the radio buttons in a set work together, the
ButtonGroup
class is used to
define a set of related radio buttons.
Note that each button is added to the button group, and also that each button
is added individually to the panel. A
ButtonGroup
object is not a container to
organize and display components; it is simply a way to define the group of radio
buttons that work together to form a set of dependent options. The
ButtonGroup
object ensures that the currently selected radio button is turned off when another
in the group is selected.
A radio button produces an action event when it is selected. The
actionPer-
formed
method of the listener first retrieves the source of the event using the
getSource
method and then compares it to each of the three radio buttons in
turn. Depending on which button was selected, the text of the label is set to the
appropriate quote.
LISTING 5.17
//********************************************************************
// QuoteOptionsPanel.java Author: Lewis/Loftus
//
// Demonstrates the use of radio buttons.
//********************************************************************
import
javax.swing.*;
import
java.awt.*;
import
java.awt.event.*;
public class
QuoteOptionsPanel
extends
JPanel
{
private
JLabel quote;
private
JRadioButton comedy, philosophy, carpentry;
private
String comedyQuote, philosophyQuote, carpentryQuote;
//-----------------------------------------------------------------
// Sets up a panel with a label and a set of radio buttons
// that control its text.
//-----------------------------------------------------------------
public
QuoteOptionsPanel()
{
comedyQuote = "Take my wife, please.";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Measure twice. Cut once.";
Search WWH ::
Custom Search