利用类方法比较简单快捷,代码如下:
URL url = getClass().getResource("Example1.fxml");
Parent root = FXMLLoader.load(url);
Scene scene = new Scene(root, 300, 200);
stage.setTitle("User Login");
stage.setScene(scene);
stage.show();
static T load(java.net.URL location)
static T load(java.net.URL location,
java.util.ResourceBundle resources)
static T load(java.net.URL location,
java.util.ResourceBundle resources,
BuilderFactory builderFactory)
static T load(java.net.URL location,
java.util.ResourceBundle resources,
BuilderFactory builderFactory,
Callback, java.lang.Object> controllerFactory)
static T load(java.net.URL location,
java.util.ResourceBundle resources,
BuilderFactory builderFactory,
Callback,java.lang.Object> controllerFactory,
java.nio.charset.Charset charset)
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader(); // 创建对象
loader.setBuilderFactory(new JavaFXBuilderFactory()); // 设置BuilderFactory
loader.setLocation(Main.class.getResource(fxml)); // 设置路径基准
try {
InputStream in = Main.class.getResourceAsStream(fxml);
AnchorPane page = (AnchorPane) loader.load(in); // 对象方法的参数是InputStream,返回值是Object
Scene scene = new Scene(page, 800, 600);
stage.setScene(scene);
stage.sizeToScene();
return (Initializable) loader.getController(); // 可以得到Controller
} finally {
in.close();
return null;
}
}
AnchorPane page = (AnchorPane) loader.load(in);
return (Initializable) loader.getController();
loader.setLocation(Main.class.getResource(fxml)); // 设置路径基准
源代码下载:http://download.csdn.net/detail/u012994553/6641887