AlertDemo.java

Download Java code from AlertDemo.zip

Contents

Reference

JavaFX Dialogs


AlertDemo.java

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

import javafx.stage.StageStyle;
import javafx.scene.*;
import javafx.scene.text.Text;

import javafx.scene.input.KeyCombination;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.input.*;
import javafx.scene.control.ContextMenu;
import javafx.scene.layout.Pane;
import javafx.geometry.*;

import java.util.*;
import javafx.util.*;
import javafx.scene.control.ButtonType;

import javafx.scene.control.Alert;
import java.io.*;

import javafx.scene.image.ImageView;

//import javafx.scene.control.Alert.AlertType;



public class AlertDemo extends Application {
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Alert Demo");
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root, 300, 250, Color.WHITE);

	Pane area = new Pane();
	root.setCenter(area);

        MenuBar menuBar = new MenuBar();
        menuBar.prefWidthProperty().bind(primaryStage.widthProperty());
        root.setTop(menuBar); 

        // File menu - exit
        Menu fileMenu = new Menu("_File");
        MenuItem exit = new MenuItem("_Exit");
        exit.setAccelerator(
            KeyCombination.keyCombination("SHORTCUT+E")
        );
        exit.setOnAction(actionEvent -> {
		Platform.exit();
		System.exit(0);
	}
	);

        fileMenu.getItems().addAll(exit);

	Menu view = new Menu("_View");
        MenuItem alert1 = new MenuItem("Alert1");
        alert1.setOnAction(actionEvent -> showAlert1() );

        MenuItem alert2 = new MenuItem("Alert2");
        alert2.setOnAction(actionEvent -> showAlert2() );

       	MenuItem alert3 = new MenuItem("Alert3");
        alert3.setOnAction(actionEvent -> showAlert3() );
 
        MenuItem alert4 = new MenuItem("Alert4");
        alert4.setOnAction(actionEvent -> showAlert4() );

        MenuItem alert5 = new MenuItem("Alert5");
        alert5.setOnAction(actionEvent -> showAlert5() );

        MenuItem alert6 = new MenuItem("Alert6");
        alert6.setOnAction(actionEvent -> showAlert6() );

        MenuItem alert7 = new MenuItem("Alert7");
        alert7.setOnAction(actionEvent -> showAlert7() );

        MenuItem alert8 = new MenuItem("Alert8");
        alert8.setOnAction(actionEvent -> showAlert8() );

         MenuItem alert9 = new MenuItem("Alert9");
        alert9.setOnAction(actionEvent -> showAlert9() );

         MenuItem alert10 = new MenuItem("Alert10");
        alert10.setOnAction(actionEvent -> showAlert10() );

	view.getItems().addAll(alert1,alert2,alert3,alert4,alert5,alert6,alert7,alert8,alert9,alert10);
 
        menuBar.getMenus().addAll(fileMenu,view);

        primaryStage.setScene(scene);
        primaryStage.show();

    }


public void showAlert1() { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Information Dialog"); alert.setHeaderText("Look, an Information Dialog"); alert.setContentText("I have a great message for you!"); alert.showAndWait(); }

public void showAlert2() { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Information Dialog"); alert.setHeaderText(null); alert.setContentText("I have a great message for you!"); alert.showAndWait(); }

public void showAlert3() { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning Dialog"); alert.setHeaderText("Look, a Warning Dialog"); alert.setContentText("Careful with the next step!"); alert.showAndWait(); }

public void showAlert4() { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Error Dialog"); alert.setHeaderText("Look, an Error Dialog"); alert.setContentText("Ooops, there was an error!"); alert.showAndWait(); }

public void showAlert5() { Alert alert = new Alert(Alert.AlertType.ERROR); alert.setTitle("Exception Dialog"); alert.setHeaderText("Look, an Exception Dialog"); alert.setContentText("Could not find file blabla.txt!"); Exception ex = new FileNotFoundException("Could not find file blabla.txt"); // Create expandable Exception. StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); String exceptionText = sw.toString(); Label label = new Label("The exception stacktrace was:"); TextArea textArea = new TextArea(exceptionText); textArea.setEditable(false); textArea.setWrapText(true); textArea.setMaxWidth(Double.MAX_VALUE); textArea.setMaxHeight(Double.MAX_VALUE); GridPane.setVgrow(textArea, Priority.ALWAYS); GridPane.setHgrow(textArea, Priority.ALWAYS); GridPane expContent = new GridPane(); expContent.setMaxWidth(Double.MAX_VALUE); expContent.add(label, 0, 0); expContent.add(textArea, 0, 1); // Set expandable Exception into the dialog pane. alert.getDialogPane().setExpandableContent(expContent); alert.showAndWait(); }

public void showAlert6() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation Dialog"); alert.setHeaderText("Look, a Confirmation Dialog"); alert.setContentText("Are you ok with this?"); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == ButtonType.OK){ // ... user chose OK } else { // ... user chose CANCEL or closed the dialog } }

public void showAlert7() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Confirmation Dialog with Custom Actions"); alert.setHeaderText("Look, a Confirmation Dialog with Custom Actions"); alert.setContentText("Choose your option."); ButtonType buttonTypeOne = new ButtonType("One"); ButtonType buttonTypeTwo = new ButtonType("Two"); ButtonType buttonTypeThree = new ButtonType("Three"); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeThree, buttonTypeCancel); Optional<ButtonType> result = alert.showAndWait(); if (result.get() == buttonTypeOne){ // ... user chose "One" } else if (result.get() == buttonTypeTwo) { // ... user chose "Two" } else if (result.get() == buttonTypeThree) { // ... user chose "Three" } else { // ... user chose CANCEL or closed the dialog } }

public void showAlert8() { TextInputDialog dialog = new TextInputDialog("walter"); dialog.setTitle("Text Input Dialog"); dialog.setHeaderText("Look, a Text Input Dialog"); dialog.setContentText("Please enter your name:"); // Traditional way to get the response value. Optional<String> result = dialog.showAndWait(); if (result.isPresent()){ System.out.println("Your name: " + result.get()); } // The Java 8 way to get the response value (with lambda expression). result.ifPresent(name -> System.out.println("Your name: " + name)); }

public void showAlert9() { List<String> choices = new ArrayList<>(); choices.add("a"); choices.add("b"); choices.add("c"); ChoiceDialog<String> dialog = new ChoiceDialog<>("b", choices); dialog.setTitle("Choice Dialog"); dialog.setHeaderText("Look, a Choice Dialog"); dialog.setContentText("Choose your letter:"); // Traditional way to get the response value. Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { System.out.println("Your choice: " + result.get()); } // The Java 8 way to get the response value (with lambda expression). result.ifPresent(letter -> System.out.println("Your choice: " + letter)); }

// modified from original code to use ArrayList rather than Pair public void showAlert10() { // Create the custom dialog Dialog<ArrayList<String>> dialog = new Dialog<>(); dialog.setTitle("Login Dialog"); dialog.setHeaderText("Look, a Custom Login Dialog"); // Set the icon (must be included in the project). //dialog.setGraphic(new ImageView(this.getClass().getResource("login.png").toString())); // Set the button types. ButtonType loginButtonType = new ButtonType("Login", ButtonBar.ButtonData.OK_DONE); dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL); // Create the username and password labels and fields. GridPane grid = new GridPane(); grid.setHgap(10); grid.setVgap(10); grid.setPadding(new Insets(20, 150, 10, 10)); TextField username = new TextField(); username.setPromptText("Username"); PasswordField password = new PasswordField(); password.setPromptText("Password"); grid.add(new Label("Username:"), 0, 0); grid.add(username, 1, 0); grid.add(new Label("Password:"), 0, 1); grid.add(password, 1, 1); // Enable/Disable login button depending on whether a username was entered. Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType); loginButton.setDisable(true); // Do some validation (using the Java 8 lambda syntax). username.textProperty().addListener((observable, oldValue, newValue) -> { loginButton.setDisable(newValue.trim().isEmpty()); }); dialog.getDialogPane().setContent(grid); // Request focus on the username field by default. Platform.runLater(() -> username.requestFocus()); // Convert the result to a username-password-pair when the login button is clicked. dialog.setResultConverter(dialogButton -> { if (dialogButton == loginButtonType) { ArrayList<String> list = new ArrayList<String>(); list.add(username.getText()); list.add(password.getText()); return list; } return null; }); Optional<ArrayList<String>> result = dialog.showAndWait(); result.ifPresent(usernamePassword -> { System.out.println("Username= " + usernamePassword.get(0) + ", Password= " + usernamePassword.get(1)); }); } public void showAlert(String str) { Alert a = new Alert(Alert.AlertType.INFORMATION); a.setHeaderText(str); /* optional a.setTitle("My Title"); a.setHeaderText("My Header Text"); a.setResizable(true); String version = System.getProperty("java.version"); String content = String.format("Java: %s.\nThis is a long text. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.", version); a.setContentText(content); */ a.showAndWait(); } public static void main(String[] args) { launch(args); } }


Maintained by John Loomis, updated Thu Mar 08 15:27:45 2018