How can I access a Controller class in JavaFx 2.0?

后端 未结 4 684
滥情空心
滥情空心 2020-12-15 22:30

Recently I was programming a software with JavaFx2.0,but I met with a big problem,that is - How can I access a Controller class? For every controller class with the same cla

相关标签:
4条回答
  • 2020-12-15 22:39

    Use getResourceAsStream instead :

    anchorPane = loader.load(LightView.class.getResourceAsStream(fxmlFile));
    

    Its simple, work well.

    0 讨论(0)
  • 2020-12-15 22:54

    In addition to Alf's answer, I want to note, that the code can be shorter:

    URL location = getClass().getResource("MyController.fxml");
    
    FXMLLoader fxmlLoader = new FXMLLoader();
    
    Parent root = (Parent) fxmlLoader.load(location.openStream());
    

    This works as well.

    0 讨论(0)
  • 2020-12-15 22:59

    I use the following :

    URL location = getClass().getResource("MyController.fxml");
    
    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(location);
    fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
    
    Parent root = (Parent) fxmlLoader.load(location.openStream());
    

    In this way fxmlLoader.getController() is not null

    0 讨论(0)
  • 2020-12-15 23:02

    You can try this...

        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(getClass().getResource("LightView.fxml"));
        loader.load();
        Parent parent = loader.getRoot();
        Scene Scene = new Scene(parent);
        Stage Stage = new Stage();
        LightViewController lv = loader.getController();
        lv.setLight(light);
        Stage.setScene(Scene);
        Stage.show();
    
    0 讨论(0)
提交回复
热议问题