Skip to main content

RadioButtonGroup

Open in ChatGPT
23.01
Java API

The RadioButtonGroup manages a collection of RadioButton components. Only one RadioButton can be selected in a RadioButtonGroup. When a user checks a new radio button, the previously selected one in the group is automatically unchecked.

Creating a RadioButtonGroup

RadioButtonGroup rendering

The RadioButtonGroup component doesn't render an HTML element. It only provides logic to make RadioButton components behave as a group rather than individually.

Create individual RadioButton components and pass them to the RadioButtonGroup constructor. Only one button in the group can be selected at a time.

Show Code

Adding and removing RadioButton components

You can include RadioButton components in the RadioButtonGroup constructor to create a group out of the provided components. To add or remove a RadioButton from an existing RadioButtonGroup, use the add() or remove() methods.

Getting the Group of a RadioButton

The RadioButton component has the getButtonGroup() method, which returns the RadioButtonGroup it belongs to, or null if it doesn’t have a group.

Nesting 25.11

Like other components, you can nest a RadioButtonGroup within a container, so you don't have to directly add each individual RadioButton.

RadioButton agree = new RadioButton("Agree");
RadioButton neutral = new RadioButton("Neutral");
RadioButton disagree = new RadioButton("Disagree");

RadioButtonGroup group = new RadioButtonGroup("choices", agree, neutral, disagree);

Fieldset fieldset = new Fieldset("Options");
fieldset.add(group);

Using RadioButtonGroupChangeEvent

Each RadioButton can have its own event listener to detect when a user toggles it. However, one advantage of using a RadioButtonGroup is that you can use a single event listener that responds to all the radio buttons in the group with the RadioButtonGroupChangeEvent.

Adding event listeners to each RadioButton

agree.onValueChange(e -> changeEvent());
neutral.onValueChange(e -> changeEvent());
disagree.onValueChange(e -> changeEvent());

Adding a single event listener to the RadioButtonGroup

RadioButtonGroup group = new RadioButtonGroup("choices", agree, neutral, disagree);
group.onChange(e -> changeEvent());

The following sample from Drawer Placement uses the RadioButtonGroupChangeEvent to automatically change the placement of the Drawer component:

Show Code

Naming

The name attribute in a RadioButtonGroup groups related RadioButtons together, allowing users to make a single choice from the options provided and enforcing exclusivity among the RadioButtons. The name of a group isn't reflected in the DOM, however, and is a convenience utility for the Java developer.