我是否必须防止循环动作处理程序调用

时间:2018-08-27 12:17:08

标签: java javafx action

找不到合适的方法来找到现有的答案,所以这是描述我的情况的草图示例:

public class MyRButton {
    RadioButton rb;
    MyRButton (RadioButton _rb) {
         rb = new RadioButton(_rb);
         rb.setOnAction(this::handleSelectedAction);
    }

    handleSelectedAction(ActionEvent _selected) {
        // DO if RadioButton rb is selected directly (by mouse etc.)
        // Some external actions are able to reset isSelected() state of the 
        // RadioButton during action handling, so to make sure it's still
        // selected after method processing:
        rb.setSelected(true);   // HERE IS THE DOUBT IF THIS OPERATOR CALLS
        // handleSelectedAction(ActionEvent _selected) RECURSIVELY     
    }
}

我必须在rb.setSelected(true)周围加上禁用/启用动作处理程序指令吗?

    handleSelectedAction(ActionEvent _selected) {
        // DO if RadioButton rb is selected directly (by mouse etc.)
        rb.setOnAction(null);
        rb.setSelected(true);
        rb.setOnAction(this::handleSelectedAction);
    }

原始代码运行良好,但是我怀疑handleSelectedAction方法是否在后台永久运行。

1 个答案:

答案 0 :(得分:2)

好的,伙计们,根据kleopatra的要求,我编写了一个可以运行的简短示例:

    package rbexample;

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

    public class RBExample extends Application {
        RadioButton rBtn;
        Button btn;

    @Override
    public void start(Stage primaryStage) {
        rBtn = new RadioButton();
        rBtn.setText("Select Me");
        rBtn.setOnAction(this::handleRBSelectedAction);
        btn = new Button();
        btn.setText("Push Me");
        btn.setOnAction(this::handleBPushedAction);

        VBox root = new VBox(2);
        root.getChildren().add(rBtn);
        root.getChildren().add(btn);
        Scene scene = new Scene(root, 150, 50);
        primaryStage.setTitle("RBExample");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void handleRBSelectedAction(ActionEvent event) {
        if (rBtn.isSelected()) {
            System.out.println("RB Selected directly");
        }
    }
    private void handleBPushedAction(ActionEvent event) {
        rBtn.setSelected(true);
        System.out.println("RB Selected by button");
    }

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

从该示例可以看出,如果操作

,则不会调用RadioButton事件处理程序
  

rBtn.setSelected(true);

是在外部执行的(在这种情况下是从Button操作处理程序执行的)。 因此,我们不需要禁用和重新启用RadioButton事件处理程序。

考虑到需要在RadioButton事件处理程序中使用setSelected(true)来确保确实选择了RadioButton,如果这里有一些可拦截直接RadioButton状态更改的背景处理,则取决于其余代码。