By adding
a ChangeListener to 'toggleGroup' we can receive the events on change in radio
button selection.
Ex
toggleGroup.selectedToggleProperty()
.addListener((ObservableValue<?
extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) -> {
if (toggleGroup.getSelectedToggle() !=
null) {
RadioButton radioButton =
(RadioButton) toggleGroup.getSelectedToggle();
System.out.println("User
selected : " + radioButton.getText());
}
});
Find the
below working application.
package com.sample.demos; import java.io.FileNotFoundException; import java.net.MalformedURLException; import javafx.application.Application; import javafx.beans.value.ObservableValue; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.RadioButton; import javafx.scene.control.Toggle; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class RadioButtonApp extends Application { @Override public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException { ToggleGroup toggleGroup = new ToggleGroup(); RadioButton radioButton1 = new RadioButton("Java"); radioButton1.setToggleGroup(toggleGroup); radioButton1.setSelected(true); RadioButton radioButton2 = new RadioButton("Python"); radioButton2.setToggleGroup(toggleGroup); RadioButton radioButton3 = new RadioButton("Haskell"); radioButton3.setToggleGroup(toggleGroup); VBox vBox = new VBox(10, radioButton1, radioButton2, radioButton3); vBox.setAlignment(Pos.CENTER); toggleGroup.selectedToggleProperty() .addListener((ObservableValue<? extends Toggle> ov, Toggle old_toggle, Toggle new_toggle) -> { if (toggleGroup.getSelectedToggle() != null) { RadioButton radioButton = (RadioButton) toggleGroup.getSelectedToggle(); System.out.println("User selected : " + radioButton.getText()); } }); Scene scene = new Scene(vBox, 400, 400); /* Set the scene to primaryStage, and call the show method */ primaryStage.setTitle("JavaFX Radio Button Example"); primaryStage.setScene(scene); primaryStage.show(); } }
TestFX.java
package com.sample.demos; import javafx.application.Application; public class TestFX { public static void main(String args[]) { Application.launch(RadioButtonApp.class, args); } }
When you
ran the application, it opens below window.
Change the
radio button selection, you can able to see the selected radio button text in
console.
No comments:
Post a Comment