CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Layout

Controls and layout managers
Components
Radio buttons

A frame with three radio buttons

How to work with radio buttons

  • You must add each radio button in a set of options to a ButtonGroup object.
  • Selecting a radio button automatically deselects all other radio buttons in the same button group.

Common constructors and methods of the JRadioButton class

Constructor Description
JRadioButton(String) Creates an unselected radio button with the specified text.
JRadioButton(String, boolean) Creates a radio button with the specified text. If the boolean value is true, the radio button is selected.
Method Description
isSelected() Returns a true value if the radio button is selected.
addActionListener(ActionListener) Adds an action listener to the radio button.

Common constructor and method of the ButtonGroup class

Constructor Description
ButtonGroup() Creates a button group used to hold a group of buttons.
Method Description
add(AbstractButton) Adds the specified button to the group.

Code that creates three radio buttons and adds them to a panel

private JRadioButton uspsRadioButton, upsRadioButton, fedexRadioButton;
uspsRadioButton = new JRadioButton("USPS", true);
upsRadioButton = new JRadioButton("UPS");
fedexRadioButton = new JRadioButton("Fedex");
add(uspsRadioButton);
add(upsRadioButton);
add(fedexRadioButton);
ButtonGroup shipViaGroup = new ButtonGroup();
shipViaGroup.add(uspsRadioButton);
shipViaGroup.add(upsRadioButton);
shipViaGroup.add(fedexRadioButton);

Code that determines which radio button is selected

if (uspsRadioButton.isSelected())
    shipVia = "USPS";
else if (upsRadioButton.isSelected())
    shipVia = "UPS";
else if (fedexRadioButton.isSelected())
    shipVia = "Federal Express";
Previous | Summary | Text areas | Scroll panes | Check boxes | Radio buttons | Borders | Combo boxes | Event listeners | Lists | Multiple selections in a list | List models | Next