JavaFX: Creating a second stage to show alert

We have always used alert box to show an alert message in web development but for JavaFX, we have to roll out our own alert box.

The usual method for most JavaFX developers is to create a second stage as shown in the example below.

In this example, we will create an AlertBox class and put the class in a separate JavaFX class file.

Main Application
package javafxapplication26;

import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;

public class JavaFXApplication26 extends Application {

    @Override
    public void start(Stage stage) {

        Button btn = new Button();
        btn.setText("Click Me");
        btn.setOnAction(e -> buttonClick());

        BorderPane pane = new BorderPane();
        pane.setCenter(btn);

        Scene scene = new Scene(pane, 500, 400);

        stage.setScene(scene);
        stage.setTitle("Show Alert");
        stage.show();
    }

    public void buttonClick() {

        AlertBox.show("This Is An Alert!", "Alert!");

    }

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

}

You can add a class file and name the file as AlertBox.java shown below.

AlertBox.java
package javafxapplication26;

import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;

public class AlertBox       
{
    public static void show(String message, String title)    
    {
        Stage stage = new Stage();       
        stage.initModality(Modality.APPLICATION_MODAL);       
        stage.setTitle(title);       
        stage.setMinWidth(400);       
        stage.setMinHeight(300);

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

        Button btnOK = new Button();       
        btnOK.setText("OK");
        btnOK.setMinWidth(60);
        btnOK.setOnAction(e -> stage.close());       

        VBox pane = new VBox(20);       
        pane.getChildren().addAll(lbl, btnOK);
        pane.setAlignment(Pos.CENTER);       

        Scene scene = new Scene(pane);       
        stage.setScene(scene);
        stage.showAndWait();       
    }
}

alert

 

Series Navigation<< JavaFX: Putting Objects Into Choice Box
JavaFX: Change listener for a Choice Box >>

2 thoughts on “JavaFX: Creating a second stage to show alert

  1. Hi, it is a good tutorial but I just wanted to point out that in Java 8u40 Dialog classes were introduced. Here’s an example of an alert:

    Alert alert = new Alert(AlertType.INFORMATION, “This is an Alert”);
    alert.getDialogPane().setContentText(“Content text”);
    alert.getDialogPane().setHeaderText(“Header text”);
    alert.showAndWait();

    Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Alert.html

    1. Oh, thanks, something new here. Will take note.

Comments are closed.