JavaFX:警告自动关闭对话框

JavaFX: alert closing the dialog box automatically

我是使用 JavaFX 创建简单练习应用程序的初学者。我使用一个带有 3 个文本字段和一个日期选择器的对话框来创建 "Items" 以作为条目添加到 SQLite 数据库中。

我正在尝试使用警报进行数据验证。如果一个或多个字段为空并且按下对话框中的确定按钮,则会弹出警报。问题是关闭警报也会关闭对话框。

我怎样才能显示和关闭警报,而不导致对话框也关闭?


这是我在 window 主控制器中用于 "new item" 按钮的方法,这会弹出对话框:

 @FXML
public void newItem() {

    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("newEventDialog.fxml"));
    try {
        dialog.getDialogPane().setContent(fxmlLoader.load());
    } catch (IOException e) {
        System.out.println("Error loading new Dialog : " + e.getMessage());
    }

    newEventDialogController newController = fxmlLoader.getController();

    dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);


    Optional<ButtonType> result = dialog.showAndWait();


    if (result.isPresent() && result.get() == ButtonType.OK) {

            newController.addItem();
            refreshList();



    }
}

这是对话框控制器中包含警报的方法:

public void addItem() {
    if (validateFields()) {

        String eventdate = datepick.getValue().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

        Item item = new Item(namefield.getText(), emailfield.getText(), typefield.getText(), eventdate);
        Datasource.getInstance().insertEvent(item);
    } else {
        Alert alert = new Alert(Alert.AlertType.ERROR);

        alert.setContentText("Error: One or more fields are empty.");
        alert.showAndWait();


    }

}

感谢您的宝贵时间以及所有回复。

您可以拦截 ButtonType.OKDialog 的操作。试试这个。

dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
final Button btOk = (Button)dialog.getDialogPane().lookupButton(ButtonType.OK);
btOk.addEventFilter(ActionEvent.ACTION, event -> {
   if (newController.addItem()) {
       refreshList();
   } else {
       event.consume();  // Make dialog NOT to be closed.
   }
});

Optional<ButtonType> result = dialog.showAndWait();

在 Dialog 的控制器中

// Return false, if you want NOT to close dialog.
public boolean addItem() {
    if (validateFields()) {
        String eventdate = datepick.getValue().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
        Item item = new Item(namefield.getText(), emailfield.getText(), typefield.getText(), eventdate);
        Datasource.getInstance().insertEvent(item);
        return true;
    } else {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setContentText("Error: One or more fields are empty.");
        alert.showAndWait();
        return false;
    }
}

此方法已在 Dialog API 文档中进行了描述。 Dialog Validation / Intercepting Button Actions