【发布时间】:2019-04-08 09:48:28
【问题描述】:
我正在做一个项目,我想使用带有 JavaFX 的外部 CSS 文件来设置 VBox 和窗格等的样式。
我已经使用下面的行来尝试将样式表添加到相应的场景中:
scene.getStylesheets().add(getClass().getResource("/style.css").toExternalForm());
这给了我空指针,我阅读了有关此问题的其他一些帖子,发现这通常是由于样式表不在尝试访问它的类路径中。这是一个屏幕截图,可以让您看到情况并非如此:
你会注意到有 Styles.css 和 style.css,我尝试了这两种方法用于不同的故障排除目的
我还发现人们的建议是,如果它在类路径中,则应该这样访问它:
scene.getStylesheets().add("style.css");
但是这样做给了我
Nov 04, 2018 9:24:10 PM com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
WARNING: Resource "Styles.css" not found.
我愿意接受任何建议,我正在使用 maven 在 IntelliJ 中工作。
编辑:这是用于进一步调查的 pom 文件 -
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.almasb</groupId>
<artifactId>CashMachine</artifactId>
<version>0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<source.version>1.8</source.version>
<!-- plugins -->
<maven.compiler.version>3.3</maven.compiler.version>
<maven.shade.version>2.4.2</maven.shade.version>
<!-- dependencies -->
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven.compiler.version}</version>
<configuration>
<source>${source.version}</source>
<target>${source.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>${maven.shade.version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.almasb.atm.CashMachineApp</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
【问题讨论】:
-
您能否告诉我们您的班级在继承权中的位置。是 CashMachineApp 吗?
-
你是如何构建你的应用程序的?您是否使用了诸如 Maven 或 Gradle 之类的构建工具?如果是这样,资源应该进入
src/main/resources而不是src/main/java。大多数构建工具默认会忽略src/main/java目录中的非.java文件。 -
另外,如果您将没有协议的
String传递给getStylesheets().add(...),它将在类路径中查找它——但它需要绝对路径。 -
@Slaw 是的,我正在使用 Maven,并且包裹的排列方式与我从学校收到的方式相同。尝试使用样式表的类是 CashMachineApp。
-
检查
target/classes目录,看看您的 CSS 文件是否在您构建项目时复制到那里。
标签: java css javafx stylesheet