给出以下代码:
代码1:
FXMLLoader loader = new FXMLLoader();
Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));
Screen1Controller controller = loader.getController();
if(controller == null)
System.out.println(" controller is null");
else System.out.println("controller is not null");
输出:
controller为空
码2:
FXMLLoader loader = new FXMLLoader(getClass().getResource("Screen1.fxml"));
Parent root = (Parent)loader.load();
// FXMLLoader loader = new FXMLLoader();
// Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));
Screen1Controller controller = loader.getController();
if(controller == null)
System.out.println(" controller is null");
else System.out.println("controller is not null");
输出:
controller不为空
我认为他们会给出相同的结果?不是吗?
答案 0 :(得分:2)
排队
Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));
你致电getResource(URL)
。该方法是静态的,因此它不会更改FXMLLoader
的任何实例(特别是不会在loader
内创建控制器。)
也许您想调用getResource(InputStream)
,这不是静态的。如果是这样,您应该将代码更改为:
Parent root = (Parent) loader.load(getClass().getResourceAsStream("Screen1.fxml"));