Alert in JAVA FX

后端 未结 2 1713
我寻月下人不归
我寻月下人不归 2021-01-24 04:45

I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Ye

相关标签:
2条回答
  • 2021-01-24 05:02

    Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.

    Alert alert = new Alert(AlertType.WARNING, 
                            "File already exists. Do you want to override?", 
                            ButtonType.YES, ButtonType.NO);
    
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.YES){
        // ... user chose YES
    } else {
        // ... user chose NO or closed the dialog
    }
    

    Also here is a good tutorial.

    0 讨论(0)
  • 2021-01-24 05:06

    I usually make a method, and call it if certain conditions are not met. Ex:

    if(condition)
          alert();
    
    
    
    public void alert(){  //alert box
    
    Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO);  //new alert object
        alert.setTitle("Warning!");  //warning box title
        alert.setHeaderText("WARNING!!!");// Header
        alert.setContentText("File already exists. Overwrite?"); //Discription of warning
        alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box 
    
        Optional<ButtonType> result = alert.showAndWait();
        if (result.get() == ButtonType.YES){
            // ... user chose YES
        } else {
            // ... user chose NO or closed the dialog
        }
    
    }
    

    I grabbed some code from Jhonny007, credit to him.

    0 讨论(0)
提交回复
热议问题