我有两个项目:“游戏”和“游戏库” - 游戏有一个到游戏库项目的构建路径。在游戏库中,我有一个方法可以在游戏请求时切换场景。如何在eclipse中使用JavaFX从另一个项目加载FXML文件?
在游戏库项目现场切换方法:
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();
}
}
我称之为游戏项目这个方法:
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");
}
}
}
所以,当我点击为playButton在FirstWindow.fxml,FirstWindowController的游戏项目将调用Game Library项目中的switchSceneFXML方法。
我得到这个错误:
java.lang.NullPointerException: Location is required.
在
root = FXMLLoader.load(getClass().getResource(FXMLLocation));
在
scene.switchSceneFXML("/game/SecondWindow.fxml");
有我丢失的东西?我如何让switchSceneFXML方法知道在Game项目中查找包和文件,而不是Game Library项目?
我想使switchSceneFXML方法可以与其他FXML文件重复使用,这样我就不必复制和粘贴代码很多,并会更喜欢一种方式,将允许我写一次和重用。
我已经环顾了很多答案,但我还没有能够完全掌握在其他人的情况下的概念。谢谢您的帮助!
是''/companytycoon/LauncherGUI.fmxl“'('fmxl'而不是'fxml')问题中还是代码中的错字? 'FXMLLoader.load(getClass()。getResource(FXMLLocation))'中的 –
''你必须调用另一个Project中的类的getClass()':FXMLLoader.load(ClassInOtherProject.class.getResource(FXMLLocation)) ' –
@James_D是的,这是一个错字。我纠正了这一点。 – Chris