JRadioButton Class

Package: javax.swing

The JRadioButton class creates a radio button, which is similar to a check box but with a crucial difference: a user can select only one radio button in each group at a time. When you click a radio button to select it, whatever radio button was previously selected is automatically deselected. Figure 5-9 shows a frame with three radio buttons.

9781118239742-fg0509.tif

Figure 5-9

To work with radio buttons, you use two classes. First, you create the radio buttons themselves with the JRadioButton class, whose constructors and methods are shown here. Then you create a group for the buttons with the ButtonGroup class. You must add the radio buttons themselves to a panel (so that they’re displayed) and to a button group (so that they’re grouped properly with other buttons). For more information, see ButtonGroup Class.

Constructors

Constructor

Description

JRadioButton()

Creates a new radio button with no text

JRadioButton(String text)

Creates a new radio button with the specified text

Methods

Method

Description

void addActionListener(ActionListener listener)

Adds an ActionListener to listen for action events

void addItem Listener(Item Listener listener)

Adds an ItemListener to listen for item events

String getText()

Gets the text displayed by the radio button

Boolean isSelected()

Returns true if the radio button ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.