ADVERTISEMENT
How to Create JavaFX Alert Dialogs

JavaFX Alert Dialogs similar to JOptionPane




JavaFX Alert Dialogs are the easiest way to communicate with the users in your application. Alert dialogs can be used to show login statuses such as login error and many more options.

JDK 8 or newer version provides an easier way to create dialogs in JavaFX (Modal Dialogs[JDialog Version of JavaFx] and Standard Dialogs [JoptionPane version of JavaFx]).

Under this article, I will illustrate how to create JavaFX alert dialogs AKA standard dialogs. These dialogs are well known from the swing JOptionPane dialogs. If you are looking at how to create similar dialogs as JOptionPane in JavaFX, you are in the right place.

How to Create JavaFX Alert Dialogs

JavaFX Alert Dialogs library contains at least four types of alert dialogs:

  1. Information Dialogs
  2. Error Dialogs
  3. Warning Dialogs
  4. Exceptional Dialogs

1. Information Alert Dialogs

JavaFX Information dialogs are used to show important messages in the software. The following code illustrates how to create an information alert dialog in JavaFX

Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.initStyle(StageStyle.UTILITY);
alert.setTitle("success");
alert.setHeaderText(null);
alert.setContentText("Infromatin Message");
alert.showAndWait();

 

2. JavaFX Error Alert Dialogs

An alert dialog in JavaFX is used to prohibit a user from taking a certain direction in the system, for example, it can be used to show login error in case of invalid login. The following code demonstrates how to create an error alert dialog in JavaFX.

JavaFX Error alert Dialog

Alert alert = new Alert(Alert.AlertType.ERROR);
alert.initStyle(StageStyle.UTILITY);
alert.setTitle("Error Message");
alert.setHeaderText(null);
alert.setContentText("Error Message");
alert.showAndWait();

 

3. JavaFX Warning Alert Dialogs

JavaFX warning dialogs are used to tell users to be careful of certain actions in the system, proceed with the action but you should be warned. For example, when a user enters a certain character on a TextField, you can show a warning like, “Users are discouraged from using numbers in the username field”. A warning does not prevent a user from taking an action, it only makes users careful. The following code illustrates how to create a JavaFX warning dialog.

JavaFX Warning Diaog

Alert alert = new Alert(Alert.AlertType.WARNING);
alert.initStyle(StageStyle.UTILITY);
alert.setTitle("Warning Message");
alert.setHeaderText(null);
alert.setContentText("Warning Message");
alert.showAndWait();

 

That’s how to create alert dialogs in JavaFX