Creating a Popup

As you experienced in Step 33 in the exercise, when the Button is clicked, the Popup shown in Figure 6-13 is created and displayed. This Popup displays the HTML that represents the text in the editing area. The preceding snippet contains the code that calls the show() method of the Popup. The Popup, however, is created by another method in StarterAppMain.java, arbitrarily named createAlertPopup() and shown in Listing 6-14.

Listing 6-14. The createAlertPopup() Method

Popup createAlertPopup(String text) {
    Popup alertPopup = new Popup();

    htmlLabel = new Label(text);
    htmlLabel.setWrapText(true);
    htmlLabel.setMaxWidth(280);
    htmlLabel.setMaxHeight(140);

    Button okButton = new Button("OK");
    okButton.setOnAction(e -> alertPopup.hide());

    BorderPane borderPane = new BorderPane();
    borderPane.setCenter(htmlLabel);
    borderPane.setBottom(okButton);

    Rectangle rectangle = new Rectangle(300, 200, Color.LIGHTBLUE);
    rectangle.setArcHeight(20);
    rectangle.setArcWidth(20);
    rectangle.setStroke(Color.GRAY);
    rectangle.setStrokeWidth(2);
    StackPane contentPane = new StackPane(rectangle, borderPane);

    alertPopup.getContent().add(contentPane);

    BorderPane.setAlignment(okButton, Pos.CENTER);
    BorderPane.setMargin(okButton, new Insets(10, 0, 10, 0));
    return alertPopup;
}

Here are some relevant notes about the createAlertPopup() method code:

A String argument containing the HTML to be displayed is passed into the method. A Popup instance is created. A StackPane, including a BorderPane that has a Label containing the HTML, is added to the Popup.

The onAction handler in the OK button causes the Popup to hide from view, as you experienced in Step 34 of the exercise.

Let’s move on to the final UI control in the StarterApp program.