[英]JavaFX Dialog getResult() method not returning the right generic type
[英]Create a generic Dialog method with 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"
我如何解決它? 謝謝。
我不是很有經驗。 那說明
假設您有一些定義了setDialogStage(Stage)
方法的控制器類MyController
,則可以執行
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已經具有用於對話框的標准方法 。
網站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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.