2017-10-08 90 views
1

我想創建一個通用的方法來創建一個特定的對話框。用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" 

我該如何解決?謝謝。

我不是很有經驗。 ,指出

回答

1

假設你有一些控制器類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); 
1

雖然您可能有很好的理由來創建自己的對話機制,但我想指出的是,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