JavaFX禁用按钮

时间:2015-03-28 11:56:27

标签: button javafx

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

谢谢!

2 个答案:

答案 0 :(得分:0)

您的问题有各种解决方案。其中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();

    }
}

答案 1 :(得分:0)

添加一个ROOT类型的事件过滤器,它会消耗所有类型的事件(鼠标,键盘等)

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

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