【问题标题】:JavaFX: IllegalStateException: Location is requiredJavaFX:IllegalStateException:需要位置
【发布时间】:2020-02-02 15:11:48
【问题描述】:

我正在尝试为我的应用程序加载 FXML,就像我在另一个项目中所做的那样。区别:不起作用。我收到“IllegalStateException:需要位置”

我尝试将文件移动到其他位置,但也没有用。 我用调试器检查了 URL (tmp)。它指向正确的文件。

    URL tmp = getClass().getClassLoader().getResource("FXMLDocument.fxml");
    FXMLLoader baseLoader = new FXMLLoader(tmp);
    Parent root = baseLoader.load();
    Scene scene = new Scene(root);        
    stage.setScene(scene);
    stage.show();

【问题讨论】:

  • 请将堆栈跟踪添加到问题中。 FXMLDocument.fxml 相对于班级的位置是什么?
  • 根据堆栈跟踪,它位于FXMLDocument.fxml 就好了。问题出在FXMLDocumentController#initialize 方法中,在线43。您必须尝试在该行上加载另一个 FXML 文件,这就是导致问题的 FXML 文件。请显示您的代码部分以及项目的结构(即请提供minimal reproducible example)。

标签: java javafx illegalstateexception fxmlloader


【解决方案1】:

实际上导致问题的代码不是问题中的代码。

事实证明

URL tmp = getClass().getResource("FXMLDrawerMain.fxml");

无论出于何种原因返回null。 (也许是操作系统?)

我换成

URL tmp = getClass().getClassLoader().getResource("FXMLDrawerMain.fxml");

现在它可以正常工作了。

【讨论】:

  • 实际导致问题的代码不是问题中的代码,这是您应该提供minimal reproducible example 的原因之一(与单纯的 sn-ps 相比)不,操作系统与它无关 - 请阅读 getResource 的 api 文档以获取 class 和 classLoader (提示:它们以不同的方式解析给定路径)。通常,不建议在默认包中包含任何内容(又名:无包).. 更好地清理您的项目结构:)
  • 如果getClass().getClassLoader("FXMLDrawerMain.fxml") 有效,那么getClass().getResource("/FXMLDrawerMain.fxml") 也应该有效(注意前面的/)。
【解决方案2】:

请替换:

URL tmp = getClass().getClassLoader().getResource("FXMLDocument.fxml");

URL tmp = getClass().getResource("FXMLDocument.fxml");

【讨论】:

  • 在不解释原因/您在做什么的情况下尝试随机路径并没有太大帮助...您评论中的建议与原始查找完全相同...(类加载器 always 假定包路径是绝对路径)
猜你喜欢
  • 1970-01-01
  • 2017-04-16
  • 2014-03-26
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
相关资源
最近更新 更多