RadioButton
RadioButton in JavaFX is used when you want the user to select one option from a group. Multiple RadioButtons can be grouped using a ToggleGroup so that selecting one automatically deselects the others.
Example: RadioButtons with ToggleGroup
FXML (hello-view.fxml)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.RadioButton?>
<?import javafx.scene.control.ToggleGroup?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.VBox?>
<VBox spacing="10" alignment="CENTER"
xmlns="http://javafx.com/javafx/17"
xmlns:fx="http://javafx.com/fxml/1"
fx:controller="org.example.demo.HelloController">
<RadioButton fx:id="option1" text="Option 1"/>
<RadioButton fx:id="option2" text="Option 2"/>
<RadioButton fx:id="option3" text="Option 3"/>
<Button text="Check Selected" onAction="#checkSelected"/>
</VBox>
Controller (HelloController.java)
package org.example.demo;
import javafx.fxml.FXML;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Alert;
public class HelloController {
@FXML
private RadioButton option1;
@FXML
private RadioButton option2;
@FXML
private RadioButton option3;
@FXML
public void initialize() {
// Create a ToggleGroup and assign RadioButtons
ToggleGroup group = new ToggleGroup();
option1.setToggleGroup(group);
option2.setToggleGroup(group);
option3.setToggleGroup(group);
// Optional: set default selected
option1.setSelected(true);
}
@FXML
private void checkSelected() {
RadioButton selected = (RadioButton) option1.getToggleGroup().getSelectedToggle();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Selected Option");
alert.setHeaderText(null);
alert.setContentText("You selected: " + selected.getText());
alert.show();
}
}
Key Points:
- ToggleGroup ensures only one RadioButton can be selected at a time.
- Use
getSelectedToggle()to find out which option the user selected. setSelected(true)allows you to set a default choice.