我使用了几个场景,目前每个场景都有一个方法,比如
void setScene1() {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/main2.fxml"));
Parent root = FXMLLoader.load();
Scene scene = new Scene(root);
loader.<Controller1>getController().callMethod();
primaryStage.setScene(scene);
}
但我想记住Scene并按照那样做
void setScene1() {
FXMLLoader loader = scene1.getLoaderSomehow(); // < ---- ????
loader.<Controller1>getController().callMethod();
primaryStage.setScene(scene1);
}
答案 0 :(得分:5)
可以使用Scene.getUserData
and Scene.setUserData
:
...
Scene scene = new Scene(root);
scene.setUserData(loader);
FXMLLoader loader = (FXMLLoader) scene.getUserData();
但是你应该记住以下几点:
Scene
,为什么不“记住”装载机/控制器呢?答案 1 :(得分:1)
为了使事情更有条理,您可以创建一个包含所有必要对象的新类:
// application screen i.e. view, "page"
public class AppScreen
{
private String fxmlPath;
private javafx.scene.Scene scene;
private RootController rootController;
// Getters, setters
}
// Collection to store loaded app screens, uses fxml path text as a key
private final Map<String, AppScreen> appScreens = new HashMap<>();
// load the fxml if it is not loaded previously or use already loaded one
void loadAppScreen( String fxmlPath ) throws IOException
{
AppScreen appScreen;
if ( appScreens.containsKey( fxmlPath ) )
{
appScreen = appScreens.get( fxmlPath );
}
else
{
FXMLLoader loader = new FXMLLoader( getClass().getResource( fxmlPath ) );
Parent root = loader.load();
Scene scene = new Scene( root );
RootController rc = loader.<RootController>getController();
appScreen = new AppScreen();
appScreen.setFxmlPath( fxmlPath );
appScreen.setScene( scene );
appScreen.setRootController( rc );
appScreens.put( fxmlPath, appScreen );
}
appScreen.getRootController().refreshData();
primaryStage.setScene( appScreen.getScene() );
}