如何创建弹出消息来提醒用户字段不完整?

时间:2019-03-14 23:06:38

标签: java javafx fxml scenebuilder

因此,我需要创建一个弹出消息,如果用户未输入内容,则会提醒用户。

例如,我有3个组合框-如果我让其中一个没有用户输入,并尝试更改场景,则会弹出警报,要求我“请确保所有字段都完整”。

下面的代码只是一个简单的弹出窗口,我需要将其链接到myController类。

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();
}

1 个答案:

答案 0 :(得分:1)

JavaFX随附了Dialogs API,该API提供了一些用于弹出警报的选项。毫无疑问,这样的类就是javafx.scene.control.Alert类。确实不需要您为此编写自己的弹出类。

创建和显示简单的Alert确实非常简单:

Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Error");
alert.setHeaderText("This is header text.");
alert.setContentText("This is content text.");
alert.showAndWait();

该代码会产生以下警报:

screenshot


例如,要验证用户输入,您的ComboBox值之一,只需使用简单的if语句来检查有效选择。如果条目丢失(null)或无效,请显示alert

if (comboBox1.getValue() == null) {
  alert.showAndWait();
}

还有更多用于更高级对话框的选项。您可以在这里看到一些很棒的示例:JavaFX Dialogs (official

相关问题