So, I need to create a popup message that will alert the user if they have not made an input.
For example, I have 3 comboboxes - if I were to leave one of them with no user input and attempted to change scenes an alert would pop up asking me to "please make sure all fields are complete".
The code below is just a simple popup that I will need to link to myController class.
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.stage.*;
import java.awt.*;
import java.awt.Label;
import java.awt.Window;
public class MissingData extends Application {
private static final String[] SAMPLE_TEXT = "hjgjguk".split(" ");
@Override
public void start(Stage primaryStage) throws Exception {
VBox textContainer = new VBox(10);
textContainer.setStyle("-fx-background-color: pink; -fx-padding: 10;");
primaryStage.setScene(new Scene(textContainer, 300, 200));
primaryStage.show();
}
JavaFX comes with the Dialogs
API that provides several options for popup alerts. One such class is, not surprisingly, the javafx.scene.control.Alert class. There really is no need for you to write your own popup class for this.
To create and display a simple Alert
is indeed very simple:
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Error");
alert.setHeaderText("This is header text.");
alert.setContentText("This is content text.");
alert.showAndWait();
That code produces the following alert:
In to validate user input, one of your ComboBox
values, for example, just use a simple if
statement to check for a valid selection. If the entry is missing (null
) or invalid, show the alert
:
if (comboBox1.getValue() == null) {
alert.showAndWait();
}
There are a lot more options for more advanced Dialogs. You can see some great examples here: JavaFX Dialogs (official.