如何在eclipse中使用JavaFX从另一个项目加载FXML文件?

时间:2017-06-15 21:36:40

标签: java eclipse javafx fxml scene

我有两个项目:" Game"和#34;游戏库" - 游戏具有游戏库项目的构建路径。在游戏库中,我有一个方法可以在游戏请求时切换场景。

Game Library项目中的场景切换方法:

package gamelibrary;

public class SceneSwitcher{

    public Stage window;
    public Parent root;

    public void switchSceneFXML(String FXMLLocation) throws Exception{

        try{

            window = (Stage) node.getScene().getWindow();

        }catch(Exception e){

            e.printStackTrace();

        }

        root = FXMLLoader.load(getClass().getResource(FXMLLocation));

        window.setScene(new Scene(root));
        window.show();

    }
}

我在Game项目中调用此方法:

package game;

import gamelibrary.sceneSwitcher;

public class firstWindowController{

    public void buttonHandler(ActionEvent event){

        SceneSwitcher scene = new SceneSwitcher();

        if(event.getSource().equals(playButton){

            scene.switchScene("/game/SecondWindow.fxml");

        }

    }

}

因此,当我单击FirstWindow.fxml中的playButton时,Game项目中的FirstWindowController将调用Game Library项目中的switchSceneFXML方法。

我收到此错误:

  

java.lang.NullPointerException:位置是必需的。

root = FXMLLoader.load(getClass().getResource(FXMLLocation));

scene.switchSceneFXML("/game/SecondWindow.fxml");

我有什么遗失的东西吗?如何让switchSceneFXML方法知道在Game项目而不是Game Library项目中查找包和文件?

我正在尝试使switchSceneFXML方法可以与其他FXML文件重用,这样我就不必复制和粘贴代码了很多,并且更喜欢一种允许我编写一次并重用的方法。

我已经四处寻找答案,但我还没能完全掌握其他人的情况。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

  

我试图使switchSceneFXML方法不仅仅在FXML上可重用。有没有办法可以自动获取课程名称? - 克里斯

然后你应该让各种类本身加载他们的FXML。您可以使用JVM ServiceLoader

执行此操作

在gane lib中:

interface FxmlController{
  boolean isPrividingScene(String nextSceneIdOrName);
  String getFXMLLocation();
}


public class SceneSwitcher{
    public Stage window;
    public Parent root;
   private static ServiceLoader<FxmlController> sceneControllers
     = ServiceLoader.load(FxmlController.class);
    public void switchSceneFXML(String nextSceneIdOrName) throws Exception{
        try{
            window = (Stage) node.getScene().getWindow();
            for(FxmlController controller : sceneControllers){
               if(controller.isPrividingScene(nextSceneIdOrName)){ // however you want to select the next scene...
                 FXMLLoader fxmlLoader = new FXMLLoader();
                 fxmlLoader.setController(controller);
                 root = fxmlLoader.load(controller.getClass().getResource(controller.getFXMLLocation()));
                 window.setScene(new Scene(root));
                 window.show();
               }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

这样每个FxmlController都可以(但不需要)生成自己的jar文件,该文件有自己的FXML文件相对路径。