gpt4 book ai didi

java - Scene#getStylesheets() 中相对路径的路径原点是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:04 25 4
gpt4 key购买 nike

未记录 getStylesheets() javadoc 中相对路径的原始位置在哪里.部分记录在 "JavaFX CSS Reference Guide" 中,但描述是有争议的。

例如据说:

A style sheet URL may be an absolute URL or a relative URL. If a relative URL is given, it is resolved against the base URL of the ClassLoader of the concrete Application class. If, for example, there is a main class com.wicked.cool.ui.Main that extends Application, the relative URL "/com/wicked/cool/resources/styles.css" would resolve correctly, as would "com/wicked/cool/resources/styles.css". The relative URL "../resources/styles.css" would not since the path ".." relative to the root is not a valid path. It is often easier to use the ClassLoader of some class to find the resource. For example, if the "styles.css" file resides in the same package as Main, the following code will give the correct URL: com.wicked.cool.ui.Main.class.getResource("styles.css").toExternalForm().

即“相对”URL 的一个示例是“/com/wicked/cool/resources/styles.css”,它不是相对的,而是绝对的。

最佳答案

注意两者

/com/wicked/cool/resources/styles.css

com/wicked/cool/resources/styles.css

是在 RFC1808 中定义的相对 URL .

此处的相对意味着相对于 ClassLoader 用来解析 URL 的位置。 (两个 URL 都缺少权限/协议(protocol)部分。)

以下示例使用 URLClassLoader 添加新位置以查找样式表:

public class Main {

public static void main(String[] args) throws MalformedURLException {
File stylesheetDir = ...

// classloader able to resolve additional resources located at the given dir
ClassLoader classLoader = new URLClassLoader(new URL[] {stylesheetDir.toURI().toURL()}, Main.class.getClassLoader());
Thread thread = new Thread(() -> Application.launch(TestApplication.class, new String[0]));

// specify classloader to use
thread.setContextClassLoader(classLoader);

thread.start();
}
}

假设 TestApplication 有以下启动方法:

public void start(Stage primaryStage) {
Scene scene = new Scene(new Group(new Rectangle(100, 100)));
primaryStage.setScene(scene);
scene.getStylesheets().add("/style.css");
primaryStage.show();
}

style.css 是仅位于指定目录的 css 文件,包含以下内容:

* {
-fx-fill: red;
}

矩形 将显示为红色。

现在注释掉

thread.setContextClassLoader(classLoader);

您将获得默认的黑色 Rectangle 以及警告。

关于java - Scene#getStylesheets() 中相对路径的路径原点是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com