getStylesheets().add(...) 不适用于 Windows (7)

getStylesheets().add(...) not working with Windows (7)

(向下滚动查看解决方案)

我用 Linux 用 Ja​​vaFX 制作了一个程序。我用

scene.getStylesheets().add(
            "file:" + Paths.get(System.getProperty("user.dir") + "/resources/style/stylesheet.css").toString());

将我的样式表加载到应用程序中。这在 Linux 下有效,但在 Windows 下无效。无论我做什么它总是说

Aug 01, 2015 5:53:42 PM com.sun.javafx.css.StyleManager loadStyleSheetUnPrivileged
Warning: Resource "file:C:\Users\win7\Desktop\resources\style\stylesheet.css" not found.

有人知道她有什么问题吗?有关键词吗?

提前致谢!

更新: 我试过了

scene.getStylesheets().add(
            "file:///" + Paths.get(System.getProperty("user.dir") + "/resources/style/stylesheet.css").toString());

    URI stylesheetURI = Paths.get(System.getProperty("user.dir") + "/resources/style/stylessheet.css").toUri();
    scene.getStylesheets().add(stylesheetURI.toString());

    Path stylesheetPath = Paths.get(System.getProperty("user.dir") + "/resources/style/stylessheet.css");
    scene.getStylesheets().add(stylesheetPath.toUri().toString());

解决方案: 我已经使用以下代码为 Linux 和 Windows 工作:

scene.getStylesheets().add(Paths.get("./resources/style/stylesheet.css").toAbsolutePath().toUri().toString());

在@RealSkeptic 和@brian 的帮助下。谢谢!

在 Windows 上,创建 "file" URI 的适当方法是在驱动器号前添加三个斜杠:C:\something\something 变为 file:///C:/something/something.

更好的是,由于您使用的是 Path,只需使用 Path.toUri()。它会在 Linux 和 Windows.

上为您正确执行此操作

user.dir 只是程序启动的当前目录。放一个 .说这是相对于当前目录的路径。然后将其转换为正确的字符串,如图所示。

File f = new File("./resources/style/stylesheet.css");
scene.getStylesheets().add(f.toURI().toURL().toExternalForm());

补充:我查了user.dir的定义,java的人不使用current dir这个术语。相反,他们说

"user.dir" User working directory

不确定您的开发设置,但我通常从我的 IDE 创建的 JAR 文件中获取资源。如果您使用的是 fxml,则可以从作为参数传递给 start() 方法的 URL 开始。然后我使用类似下面的东西:

        private String getCssFileLocation() {
            String locInJar = "/net/clarkonium/jist/resources/css/help.css";
            System.out.println("fxml URL: " + fxmlUrl);
            String externalForm = fxmlUrl.toExternalForm();
            System.out.println("fxmUrl.toExternalForm(): " + externalForm);
            String prefix = externalForm.substring(0, externalForm.indexOf("!") + 1);
            System.out.println("prefix: " + prefix);
            String resLocation = prefix + locInJar;
            System.out.println("resLocation: " + resLocation);
            return resLocation;
        }

因为我的程序知道它想要的资源的位置,所以它将它粘贴到 URL 上以代替 fxml 位置。程序的 运行 产生了这个输出,显示了函数执行的步骤:

fxml URL: jar:file:/C:/projects/Jist/dist/run786853897/Jist.jar!/net/clarkonium/jist/RepositorySetup.fxml
fxmUrl.toExternalForm(): jar:file:/C:/projects/Jist/dist/run786853897/Jist.jar!/net/clarkonium/jist/RepositorySetup.fxml
prefix: jar:file:/C:/projects/Jist/dist/run786853897/Jist.jar!
resLocation: jar:file:/C:/projects/Jist/dist/run786853897/Jist.jar!/net/clarkonium/jist/resources/css/help.css

然后您可以使用返回的位置来添加样式表。

所有感叹号前的东西都依赖于我的IDE和运行 运行的变化。此方法在开发完成并且程序是 运行 来自另一个位置后也有效。