JavaFX 禁用按钮

JavaFX disable button

我正在使用 javaFX 在 netbeans 中编写程序 该视图中有几个带有一些坏按钮的按钮(比如炸弹是扫雷器),我试图在按下一个坏按钮时冻结程序,但我不知道该怎么做

谢谢!

您的问题有多种解决方案。其中 2 个只是简单地忽略操作事件或禁用按钮,如下所示:

public class ButtonAction extends Application {

    final BooleanProperty buttonActionProperty = new SimpleBooleanProperty();

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

    @Override
    public void start(Stage primaryStage) {

        FlowPane root = new FlowPane();

        CheckBox checkBox = new CheckBox( "Enabled");
        checkBox.setSelected(true);

        // solution 1: check if action is allowed and process it or not
        buttonActionProperty.bind( checkBox.selectedProperty());

        Button button = new Button( "Click Me");
        button.setOnAction(e -> {
            if( buttonActionProperty.get()) {
                System.out.println( "Allowed, processing action");
            } else {
                System.out.println( "Not allowed, no action");
            }
        });

        // solution 2: remove comments to activate the code
        // button.disableProperty().bind(buttonActionProperty.not());

        root.getChildren().addAll(checkBox, button);

        primaryStage.setScene(new Scene(root, 600, 200));
        primaryStage.show();

    }
}

添加一个 ROOT 类型的事件过滤器来处理所有类型的事件(鼠标、键盘等)

btnThatHasHiddenMine.setOnAction(( ActionEvent event ) ->
{
    System.out.println("Ohh no! You just stepped over the mine!");
    getGameboardPane().addEventFilter( EventType.ROOT, Event::consume );
});

仅将过滤器添加到您的 GameboardPane,因为我们不想冻结应用程序的其他部分。