用Javafx创建一个通用的对话框方法

问题描述:

我想创建一个通用的方法来创建一个特定的对话框。用Javafx创建一个通用的对话框方法

private void setDialog(String dialog,String title){ 
    try { 
     // Load the fxml file and create a new stage for the popup 
     FXMLLoader loader = new FXMLLoader(Main.class.getResource("/view/" + dialog + ".fxml")); 
     AnchorPane page = (AnchorPane) loader.load(); 
     Stage dialogStage = new Stage(); 
     dialogStage.setTitle(title); 
     dialogStage.initModality(Modality.WINDOW_MODAL); 
     dialogStage.initOwner(Main.getPs()); 
     Scene scene = new Scene(page); 
     dialogStage.setScene(scene); 


    loader.getController().setDialogStage(dialogStage); 

     // Show the dialog and wait until the user closes it 
     dialogStage.showAndWait(); 


     } catch (IOException e) { 
     // Exception gets thrown if the fxml file could not be loaded 
     e.printStackTrace(); 
     } 

} 

但我在这行

loader.getController().setDialogStage(dialogStage) 

得到一个错误,完全错误是这个

"The method setDialogStage(Stage) is undefined for the type Object" 

我该如何解决?谢谢。

我不是很有经验。 ,指出

假设你有一些控制器类MyController定义了setDialogStage(Stage)方法,你可以做

loader.<MyController>getController().setDialogStage(dialogStage); 

这是不是真的比任何一个简单的投更多的类型安全的;如果控制器不是正确的类型,它将在运行时失败,出现ClassCastException

如果您有可能在本方法多个控制器,最好的选择可能是让他们实现定义中的相关方法的接口:

public interface DialogController { 

    public void setDialogStage(Stage dialogStage); 

} 

你的控制器看起来像

public class MyController implements DialogController { 

    // ... 

    @Override 
    public void setDialogStage(Stage dialogStage) { 
     // ... 
    } 

} 

然后你只是将控制器视为一般DialogController

loader.<DialogController>getController().setDialogStage(dialogStage); 

虽然您可能有很好的理由来创建自己的对话机制,但我想指出的是,JavaFX已经有了用于对话框的standard way

网站code.makery显示了如何创建对话框一些例子:

Alert alert = new Alert(AlertType.CONFIRMATION); 
alert.setTitle("Confirmation Dialog"); 
alert.setHeaderText("Look, a Confirmation Dialog"); 
alert.setContentText("Are you ok with this?"); 

Optional<ButtonType> result = alert.showAndWait(); 
if (result.get() == ButtonType.OK){ 
    // ... user chose OK 
} else { 
    // ... user chose CANCEL or closed the dialog 
} 

Confirmation dialog

您还可以创建一个自定义内容的对话框: Exception Dialog