final ToggleGroup radioToggleGroup = new ToggleGroup();
RadioButton radioButton1 = new RadioButton("RadioButton1");
radioButton1.setToggleGroup(radioToggleGroup);
RadioButton radioButton2 = new RadioButton("RadioButton2");
radioButton2.setToggleGroup(radioToggleGroup);
HBox radioBox = new HBox(10, radioButton1, radioButton2);
...
radioToggleGroup.selectToggle(radioToggleGroup.getToggles().get(0));
radioToggleGroup.selectedToggleProperty().addListener((ov, oldValue, newValue) -> {
RadioButton rb = ((RadioButton) radioToggleGroup.getSelectedToggle());
if (rb != null) {
System.out.println(rb.getText() + " selected");
}
});
Defining a RadioButton
In Step 18 of the previous exercise, you selected each of the RadioButton controls shown in Figure 6-9. As a result, a message was printed to the Java console indicating which RadioButton was selected. The following code snippet, from Listing 6-12, implements this functionality in the StarterApp program:
Because the RadioButton class extends the ToggleButton class, the code in the preceding snippet is very similar to the code in the section “Using Toggle Groups” earlier in this chapter. Please review that section if you’d like an explanation of the code in this snippet.