我使用了几个场景,目前每个场景都有一个方法,比如
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);
}但是我想记住场景并且像那样做
void setScene1() {
FXMLLoader loader = scene1.getLoaderSomehow(); // < ---- ????
loader.<Controller1>getController().callMethod();
primaryStage.setScene(scene1);
}发布于 2016-01-22 19:58:40
这可以使用Scene.getUserData and Scene.setUserData来完成
...
Scene scene = new Scene(root);
scene.setUserData(loader);FXMLLoader loader = (FXMLLoader) scene.getUserData();但你应该牢记以下几点:
Scene,那么为什么不“记住”加载器/控制器呢?发布于 2016-01-22 22:49:25
为了让事情更有条理,你可以创建一个包含所有必要对象的新类:
// 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() );
}https://stackoverflow.com/questions/34941411
复制相似问题