Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Saturday, July 11, 2015

Don't Just Tell Me. Show Me with Custom Alerts in JavaFX 8.

With the u40 version of JavaFX 8, the toolkit finally adds standard Alerts.  Alerts are popups that notify the user of a condition or polls for a simple input like a confirmation.  The standard is great because you don't have to build your own Alerts class.  However, you may find that you want to customize the contents of the Alert.

This example adds a Hyperlink in with the Alert text to not only notify the user of a condition, but to provide navigation to its resolution.

This video shows an Alert telling the user that they've missed a configuration.  In this case, a keytool.exe must be defined prior to bringing up the Configure window.  The Alert has a Hyperlink in it "File > Settings" indicating where to fix the problem.  Clicking on the Hyperlink will close the Alert and open the Settings window.

video
The Alert is a standard JavaFX Alert of type ERROR.  Instead of providing simple text for the body, I've combined a Label ("Set key tool in ") and a Hyperlink ("File > Settings").

JavaFX 8 Alert with Custom Content
I wrap the Label and Hyperlink into a FlowPane and add that to the Alert's DialogPane, accessed by a superclass method.


    Alert alert = new Alert(
        Alert.AlertType.ERROR,
                    "Set keytool.exe in File > Settings");
    alert.setHeaderText("Keytool not defined");

    FlowPane fp = new FlowPane();
    Label lbl = new Label("Set keytool in ");
    Hyperlink link = new Hyperlink("File > Settings");
    fp.getChildren().addAll( lbl, link);

    link.setOnAction( (evt) -> {
                alert.close();
                openSettings();
    } );

    alert.getDialogPane().contentProperty().set( fp );

    alert.showAndWait();

contentNodeProperty() has precedence over contentTextProperty() which means that if you provide text in the Alert constructor, it will be ignored when you call contentProperty().set().

Standard Alerts are an overdue addition to JavaFX 8.  While it's no great engineering feat to write your own simple popup classes, that type of activity adds unneeded code or dependencies to your JavaFX project.  The standard Alerts are flexible enough  to be customized as shown by this example to make an app more user friendly.

No comments:

Post a Comment