如何在javafx中去另一个场景?

时间:2018-03-09 13:17:47

标签: javafx

我的信息中心fxml位置为Dashboard/DashBoardScene.fxml。我尝试从Login/LoginController切换到信息中心屏幕

public void onLoginButtonClick(ActionEvent actionEvent) throws IOException {

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Dashboard/DashBoardScene.fxml"));
    Parent root1 = (Parent) fxmlLoader.load();
    Stage stage = new Stage();
    stage.initModality(Modality.APPLICATION_MODAL);
    stage.initStyle(StageStyle.UNDECORATED);
    stage.setTitle("ABC");
    stage.setScene(new Scene(root1));
    stage.show();
}

但我得到位置是必需的错误?

1 个答案:

答案 0 :(得分:0)

代码位于RestarantApp.Dashboard包中的一个类中(顺便说一下,请使用proper naming conventions)。您的FXML文件位于同一个包中。

代码getClass().getResource(...)将返回相对于当前类搜索的资源的URL。由于当前类和FXML文件在同一个包中,您只需要

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("DashBoardScene.fxml"));

(这假设FXML文件正确部署,资源名称拼写正确等)。

您还可以为资源指定“绝对”路径(相对于类路径的路径):

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/RestarantApp/Dashboard/DashBoardScene.fxml"));

请注意,此路径以前导/开头。