在JavaFX中动态添加CSS样式表

F.A*_*F.A 7 css java javafx

我想添加一个位于文件系统某处的CSS文件.目的是编写一个应用程序,用户可以动态地添加JavaFX CSS文件(由任何人创建并位于任何地方).
我试过类似的东西,仅用于测试,看看动态添加的CSS文件是否有效:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Label label = new Label("Hello");
        Scene scene = new Scene(label);

        //file would be set by an file chosser
        File file = new File("C:/test.css");
        scene.getStylesheets().add(file.getAbsolutePath());

        primaryStage.setTitle("Title");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我总是得到同样的错误:

WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "C:\test.css" not found. 
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

jij*_* Aj 13

如果css在同一个包装中,只需使用

scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
Run Code Online (Sandbox Code Playgroud)


Ant*_* J. 11

您的问题是您没有使用URL.在这里,您可以找到有关如何加载CSS以及CSS参考的更多文档.

如果您有URL,String您可以使用外部文件动态设置CSS,如下所示:

private boolean isANext = true;

public void start(Stage primaryStage) throws Exception {
    Button button = new Button("Change CSS");
    VBox vbox = new VBox(10);
    vbox.setAlignment(Pos.CENTER);
    vbox.getChildren().add(button);
    scene = new Scene(vbox, 200, 200);

    button.setOnAction(ev -> {
        // Alternate two stylesheets just for this demo.
        String css = isANext ? "file:///C:/temp/a.css" : "file:///C:/temp/b.css";
        isANext = !isANext;
        System.out.println("Loading CSS at URL " + css);

        scene.getStylesheets().clear();
        scene.getStylesheets().add(css);
    });

    primaryStage.setTitle("Title");
    primaryStage.setScene(scene);
    primaryStage.show();
}
Run Code Online (Sandbox Code Playgroud)

在里面 a.css

.button {    
    -fx-text-fill: white;
    -fx-background-color: red;
}
Run Code Online (Sandbox Code Playgroud)

并在 b.css

.button {    
    -fx-text-fill: white;
    -fx-background-color: black;
}
Run Code Online (Sandbox Code Playgroud)