JavaFX阻止在buttonclick上打开新阶段(窗口)

时间:2017-10-31 20:09:37

标签: java javafx

我有以下代码打开一个新的JavaFX阶段(让我们称之为窗口)。

openAlertBox.setOnAction(e -> {
        AlertBox alert = AlertBox.getInstance();
        alert.display("AlertBox","Cool");
});

现在我想阻止用户在每次点击时打开一个新窗口(因此,如果用户已经打开了一个窗口,那么在另一次点击时,由于窗口已经打开,所以不会发生任何事情)

这是我的显示方法:

public void display(String title, String message) {
    Stage window = new Stage();

    window.initModality(Modality.NONE);
    window.setTitle(title);
    window.setMinWidth(250);

    Label label = new Label();
    label.setText(message);

    VBox layout = new VBox(10);
    layout.getChildren().addAll(label);
    layout.setAlignment(Pos.CENTER);
    //Display window and wait for it to be closed before returning
    Scene scene = new Scene(layout);
    window.setScene(scene);
    window.showAndWait();
}

我该怎么做?

1 个答案:

答案 0 :(得分:2)

创建一个窗口并重复使用它,而不是每次都创建一个新窗口。然后你可以检查它是否显示:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ShowAndWaitNonModalTest extends Application {

    private Stage alertWindow ;

    @Override
    public void start(Stage primaryStage) {
        Button show = new Button("Show");

        alertWindow = new Stage();

        show.setOnAction(e -> {
            if (! alertWindow.isShowing()) {
                Button ok = new Button("OK");
                Scene scene = new Scene(new StackPane(ok), 250, 250);
                alertWindow.setScene(scene);
                ok.setOnAction(evt -> alertWindow.hide());
                alertWindow.showAndWait();
            }
        });


        Scene scene = new Scene(new StackPane(show), 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

或者您可以禁用显示时显示的控件:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ShowAndWaitNonModalTest extends Application {

    private Stage alertWindow ;

    @Override
    public void start(Stage primaryStage) {
        Button show = new Button("Show");

        alertWindow = new Stage();

        show.setOnAction(e -> {
            Button ok = new Button("OK");
            Scene scene = new Scene(new StackPane(ok), 250, 250);
            alertWindow.setScene(scene);
            ok.setOnAction(evt -> alertWindow.hide());
            alertWindow.showAndWait();
        });

        show.disableProperty().bind(alertWindow.showingProperty());

        Scene scene = new Scene(new StackPane(show), 400, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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