首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在JavaFx8中获取场景控件?

如何在JavaFx8中获取场景控件?
EN

Stack Overflow用户
提问于 2016-01-22 15:39:26
回答 2查看 11.6K关注 0票数 3

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

代码语言:javascript
复制
  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);

  }

但是我想记住场景并且像那样做

代码语言:javascript
复制
  void setScene1() {
    FXMLLoader loader = scene1.getLoaderSomehow(); // < ---- ????
    loader.<Controller1>getController().callMethod();
    primaryStage.setScene(scene1);

  }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-22 19:58:40

这可以使用Scene.getUserData and Scene.setUserData来完成

代码语言:javascript
复制
...
Scene scene = new Scene(root);
scene.setUserData(loader);
代码语言:javascript
复制
FXMLLoader loader = (FXMLLoader) scene.getUserData();

但你应该牢记以下几点:

  • 你使用加载器只是为了获取控制器。加载器可以包含对对象的引用,否则可以对这些对象进行垃圾回收。考虑保留对控制器的引用。
  • 任何其他地方都会更方便(根据方法的不同,类型更安全)。您正在“记住”Scene,那么为什么不“记住”加载器/控制器呢?
票数 6
EN

Stack Overflow用户

发布于 2016-01-22 22:49:25

为了让事情更有条理,你可以创建一个包含所有必要对象的新类:

代码语言:javascript
复制
// 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() );
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34941411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档