JavaFX: Apply background effect when dialog is open

2.2k Views Asked by At

I am currently exploring the new features from Java JDK 8u40, and I must say I really like the build-in dialog class. In comparison to ControlsFX, there is no background effect when the dialog is openend (ControlsFX made the background appear darker). I also would like to do this with the new dialog class in JavaFX. I am using the following code:

TextInputDialog dialog = new TextInputDialog();
dialog.initOwner(null);
dialog.initStyle(StageStyle.UNDECORATED);
dialog.setHeaderText(“Please fill in a new number“);
dialog.setContentText(“New number:”);

//Check if the optional is filled in
Optional<String> newAmount = dialog.showAndWait();
if (result.isPresent()){
    System.out.println(“New number: " + result.get());
}

I could not find any helpful parts in the dialog class. I tried this code, but it is a bit hacky, and a little bit slow:

myMainFlowPane.setOpacity(0.5);
// ..... dialog code ..... //
myMainFlowPane.setOpacity(1.0);

You should say there has to be a build-in method for this. Any of you know how to do this?

Any help is greatly appreciated!

1

There are 1 best solutions below

2
On BEST ANSWER

You can easily implement the same effect. To add this opaque layer in between your scene and the dialog, just add an invisible region at the top of the scene, and make it visible with some transparency right before the dialog is shown, hidding it again after it is closed.

@Override
public void start(Stage primaryStage) {

    final Region opaqueLayer = new Region();
    opaqueLayer.setStyle("-fx-background-color: #00000044;");
    opaqueLayer.setVisible(false);

    Button btn = new Button("Show Dialog");
    btn.setOnAction(t -> {
        TextInputDialog dialog = new TextInputDialog();
        dialog.initOwner(null);
        dialog.initStyle(StageStyle.UNDECORATED);
        dialog.setHeaderText("Please fill in a new number");
        dialog.setContentText("New number:");

        opaqueLayer.setVisible(true);
        //Check if the optional is filled in
        Optional<String> result = dialog.showAndWait();
        opaqueLayer.setVisible(false);
        if (result.isPresent()){
            System.out.println("New number: " + result.get());
        }
    });

    StackPane root = new StackPane(btn,opaqueLayer);        
    Scene scene = new Scene(root, 800, 600);

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

    opaqueLayer.resizeRelocate(0, 0, scene.getWidth(), scene.getHeight());
}

This will only affect the scene, but you could make it extensible to all the screen.