Reputation: 129
I have the following code which opens up a new JavaFX stage (let's call it window).
openAlertBox.setOnAction(e -> {
AlertBox alert = AlertBox.getInstance();
alert.display("AlertBox","Cool");
});
Now I want to prevent user from opening a new window on every click (So if user already opened a window then on another click, nothing should happen because window is already opened)
This is my display method:
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();
}
How can I do that?
Upvotes: 0
Views: 3325
Reputation: 209694
Create a single window and reuse it, instead of creating a new one each time. Then you can either just check if it is showing:
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);
}
}
or you can disable whichever control shows it when it is showing:
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);
}
}
Upvotes: 2