JavaFX:警报自动关闭对话框

3
我是一名初学者,在JavaFX中创建一个简单的练习应用程序。我使用一个对话框来创建“项目”,其中包含3个文本字段和一个日期选择器,以添加为SQLite数据库条目。
我尝试使用警告进行数据验证。如果一个或多个字段为空,并且在对话框上按下OK按钮,则弹出警告。问题在于关闭警告也会关闭对话框。
如何使警告显示并关闭,而不会导致对话框也关闭?
这是我在主窗口控制器中使用的“新项目”按钮的方法,这将带来对话框。
 @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();



    }
}

这是Dialog控制器内包含警告的方法:

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


    }

}

感谢您的时间和回复。
1个回答

1
你可以拦截DialogButtonType.OK操作。试试这个。
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();

在对话框的控制器中。
// 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文档中描述。 对话框验证/拦截按钮操作

谢谢您的回答,现在一切都完美地运作了。感谢您指向正确的文档。 - Alin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接