javafx styleSheets内部osgi捆绑
题
我在捆绑的根目录中放置了“styles.css”,现在尝试弄清楚如何在代码中链接它。问题是@ .getStylesheets()。添加(_)拿一个字符串而不是URL,所以我所知道的所有方法都在这里失败:
取1:
scene.getStylesheets().add("styles.css");
.
→
Nov 15, 2013 2:04:47 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "styles.css" not found.
.
需要2:
scene.getStylesheets().add(this.getClass().getResource("styles.css").toExternalForm());
.
→
NullPointerException
.
需要3:
scene.getStylesheets().add(this.getClass().getClassLoader().getResource("styles.css").toExternalForm());
.
→
Nov 15, 2013 2:27:31 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load stylesheet: bundle://5.0:1/styles.css
.
需要4:
scene.getStylesheets().add(myBundle.getEntry("styles.css").toExternalForm());
.
→
Nov 15, 2013 1:31:35 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
INFO: Could not load stylesheet: bundle://5.0:0/styles.css
.
我正在使用 felix-4.2.1 , java-8(build 1.8.0-ea-b115), javafx-8(8.0。0-ea-b115)。
解决方案
我最近在与这个问题的原始海报相同的错误/麻烦,我设法解决了它而不对CSS / FXML进行任何更改或将其提取到临时文件。我在这里发布了它,因为我没有找到任何好的答案:
在我的情况下,设置是:
bundle0:
- oveview.fxml具有相对路径的参考,对CSS文件
- 具有相对路径的somestyle.css对图像的相对路径
- 某种图像.png
- resourceoder.java(从CSS和FXML文件中返回URL对象)
bundle1:
- 基本javafx文件用fxml加载程序从bundle0加载fxml。
问题:
引用的所有CSS和CSS似乎都被FXML忽略了,即使我在FXML加载程序上设置了ClassLoader。如果我使用CSS的绝对文件路径以及CSS中引用的图像,它只工作。这不是我想要的。
解决方案:
javafx中有2个错误/设计问题,禁止使用OSGi。
- 从fxml 加载CSS
- 从CSS引用图像
- -dbinary.css= false
ClassLoader tccl = Thread.currentThread().getContextClassLoader();
try {
final ClassLoader resourcesClassLoader = Resourceloader.class.getClassLoader();
//needed for css
Thread.currentThread().setContextClassLoader(resourcesClassLoader);
this.primaryStage.show();
} finally {
Thread.currentThread().setContextClassLoader(tccl);
}
.
不幸的是,这是我可以提出的最好的解决方案。 javafx不是用课堂装载机或依赖注入的依赖,即使只有每个公司应用程序都使用某种形式的这些功能。 :(
//编辑 它看起来不需要设置线程上下文类加载器来访问来自CSS的图像!
其他提示
此处解释了这不起作用的原因: javafx jira rt-14177 。 由于您不能使用Ressource的“ExternalForm”,因此我通过直接读取输入流在TEMP文件中复制它。
InputStream inputStream = MainApp.class.getResourceAsStream("/styles/styles.css");
File tempStyleSheetDest = File.createTempFile("javafx_stylesheet", "");
tempStyleSheetDest.deleteOnExit();
Files.copy(inputStream, tempStyleSheetDest.toPath(), StandardCopyOption.REPLACE_EXISTING);
scene.getStylesheets().add(tempStyleSheetDest.toURI().toString());
.
- 确保您使用的类的ClassLoader可以访问包含CSS文件 的捆绑包
- 如果您使用的相对路径,请确保CSS相对于该类的包 位于该类别
这里是我如何在 droombler fx ( droombler fx是基于OSGi和Maven的JavaFx的模块化丰富的客户端平台(POM-First)):
此处:stylesheets类与CSS文件相同的捆绑包。
getClass()。getClassLoader()。getResource()。toexternalform()?