Java Reference
In-Depth Information
RadioButtonsPanel
class. This class creates three radio buttons in the con-
structor and adds them to a
ButtonGroup
instance and to the panel. The class
implements the
ActionListener
interface, and the buttons send their events to
actionPerformed()
. That method uses
getSource()
to determine which
of the radio buttons generated the event and then sets the color accordingly. The
code listing for
RadioButtonsPanel
is given below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
/**
* The RadioButtonsPanel holds radio buttons that set
* the color of the output panel.
**/
public class
RadioButtonsPanel
extends JPanel
implements ActionListener
{
JRadioButton fRed, fGreen, fBlue;
OutputPanel fOutputPanel;
RadioButtonsPanel (OutputPanel output
-
panel) {
fOutputPanel = output
-
panel;
// RadioButtons need to be organized with a
// ButtonGroup object.
ButtonGroup group = new ButtonGroup ();
fRed = new JRadioButton ("Red", true);
fRed.addActionListener (this);
// Add the JRadioButton instance to both the
// ButtonGroup and the panel.
group.add (fRed);
add (fRed);
fGreen
=
new JRadioButton (
"
Green
"
, false);
fGreen.addActionListener (this);
group.add (fGreen);
add (fGreen);
fBlue = new JRadioButton ("Blue", false);
fBlue.addActionListener (this);
Search WWH ::
Custom Search