如何在JavaFx8中获取场景控制器?

时间:2016-01-22 07:39:26

标签: javafx javafx-8

我使用了几个场景,目前每个场景都有一个方法,比如

  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);

  }

2 个答案:

答案 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() );
}