每当使用箭头键导航到ToggleGroup中时选择一个RadioButton

问题描述

我有一个程序,其中有一系列RadioButton,它们共享一个ToggleGroup。以下是简化版本:

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) {
        ToggleGroup toggleGroup = new ToggleGroup();

        RadioButton button1 = new RadioButton();
        button1.setText("Button 1");
        button1.setonAction(this::printSelectedRadioButton);
        button1.setToggleGroup(toggleGroup);

        RadioButton button2 = new RadioButton();
        button2.setText("Button 2");
        button2.setonAction(this::printSelectedRadioButton);
        button2.setToggleGroup(toggleGroup);

        VBox root = new VBox(10);
        root.setAlignment(Pos.CENTER);
        root.getChildren().addAll(button1,button2);

        primaryStage.setScene(new Scene(root,100,100));
        primaryStage.show();
    }

    private void printSelectedRadioButton(ActionEvent actionEvent) {
        RadioButton radioButton = (RadioButton) actionEvent.getSource();
        System.out.println(radioButton.getText());
    }

    public static void main(String[] args) {
        launch(args);
    }
}

The stage generated by the above code

当我单击RadioButton时,将触发ActionEvent调用printSelectedRadioButton()方法。但是,一旦我单击了RadioButton,如果我使用箭头键导航到另一个,则不会触发ActionEvent并且不会调用方法。我想导航到特定按钮具有与单击相同的效果。我该怎么办?

解决方法

RadioButton#setOnAction仅在单击时有效。如果要选择单选按钮,则必须将 ChangeListener 添加到ToggleGroup。

    ToggleGroup toggleGroup = new ToggleGroup();
    toggleGroup.selectedToggleProperty().addListener((observableValue,oldToggle,newToggle) -> {
        if (toggleGroup.getSelectedToggle() != null) {
            System.out.println("selected radio button: " + toggleGroup.getSelectedToggle());
        }
    });