【问题标题】:Selecting a RadioButton in a ToggleGroup whenever it is navigated to with the arrow keys使用箭头键导航到 ToggleGroup 时选择 RadioButton
【发布时间】:2023-03-09 03:00:01
【问题描述】:

我有一个包含一系列RadioButtons 的程序,它们共享一个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);
    }
}

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

【问题讨论】:

  • @Slaw 你有在选择时切换触发的本机(最好是Windows)示例吗?凭直觉,我想说,在 fx 中实现的基本行为是非常正确的。客户端代码总是可以增强以做更多事情(记住触发动作是一个强有力的措施)
  • selection != 动作:在选择切换的组之前添加一个普通按钮(使其最初聚焦)-> 不触发。反过来:注意鼠标点击后的行为是两步(按下 -> 手臂,释放 -> 开火)。要查看,请按下切换开关,然后在释放前移开 - 不会开火。
  • @Slaw 但自古以来就是这样(旧的 awt 和 swing,fi :) 考虑仅使用键盘的交互:要到达特定控件,在导航时,我们将触摸(并可能选择,取决于我们从哪里开始以及是否选择了组中的任何切换)几个切换 - 我们真的要触发每个切换的动作(我们刚刚导航过,因为它正在通往我们真正目标的路上)?不要这么想,上面应该有东西。触发按钮操作的常用键盘手势是焦点时的空格(或回车)。
  • @kleopatra 有道理。

标签: java javafx radio-button


【解决方案1】:

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());
        }
    });

【讨论】:

    猜你喜欢
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-14
    • 2016-07-06
    相关资源
    最近更新 更多