我想创建一个通用方法来创建特定的对话框。
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"
我该如何解决这个问题?谢谢。
我经验不足。这就是说
最佳答案
假设您有一些 Controller 类 MyController
定义了 setDialogStage(Stage)
方法,您可以这样做
loader.<MyController>getController().setDialogStage(dialogStage);
这实际上并不比简单的强制转换更安全;如果 Controller 类型不正确,它将在运行时失败并出现 ClassCastException
。
如果您有多个可能具有此方法的 Controller ,最好的选择可能是让它们实现定义相关方法的接口(interface):
public interface DialogController {
public void setDialogStage(Stage dialogStage);
}
你的 Controller 看起来像
public class MyController implements DialogController {
// ...
@Override
public void setDialogStage(Stage dialogStage) {
// ...
}
}
然后你只需将 Controller 视为通用的DialogController
:
loader.<DialogController>getController().setDialogStage(dialogStage);
关于java - 使用 Javafx 创建通用对话框方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46636320/