JavaFX CSS“找不到资源”

cob*_*798 2 css java javafx classpath

当我尝试更改 css 文件所在的文件夹时,出现此错误:

WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "file:/C:/[path-to-project]/Test/resources/css/main.css" not found.
Run Code Online (Sandbox Code Playgroud)

我复制了 URL 并将其粘贴到文件管理器中,然后它打开了文件,所以我知道它存在。

public static void main(String[] args)
{
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception
{
    primaryStage.setTitle("New Window");

    Scene scene = new Scene(new AnchorPane(), 800, 600);
    primaryStage.setScene(scene);

    URL css = new URL("file:///" + 
            new File("resources/css").getAbsolutePath().replace("\\", "/") + 
            "/main.css");
    scene.getStylesheets().clear();
    scene.getStylesheets().add(css.toExternalForm());

    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

这是我的 Eclipse 项目布局[也作为图像]

public static void main(String[] args)
{
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception
{
    primaryStage.setTitle("New Window");

    Scene scene = new Scene(new AnchorPane(), 800, 600);
    primaryStage.setScene(scene);

    URL css = new URL("file:///" + 
            new File("resources/css").getAbsolutePath().replace("\\", "/") + 
            "/main.css");
    scene.getStylesheets().clear();
    scene.getStylesheets().add(css.toExternalForm());

    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

scene.getStylesheets().add(getClass().getResource("/resources/css/main.css")); 
scene.getStylesheets().add(getClass().getResource("resources/css/main.css"));
scene.getStylesheets().add(getClass().getResource("../resources/css/main.css"));
Run Code Online (Sandbox Code Playgroud)

我还尝试使用 fxml 添加 css 文件,尝试:

stylesheets="@../resources/css/main.css"
stylesheets="@/resouces/css/main.css"
stylesheets="@resources/css/main.css
Run Code Online (Sandbox Code Playgroud)

Krz*_*soń 11

将您的main.css文件放在resources/com目录中(所以resources+ 加载它的类的包),然后您可以使用一个简单的(假设您的类已命名Client并且它在com包中):

scene.getStylesheets().add(Client.class.getResource("main.css").toExternalForm());
Run Code Online (Sandbox Code Playgroud)