JavaFX-指定CSS文件相对于fxml文件的位置


基本实施

资料夹结构

1
2
3
4
5
6
7
8
`-src/main/
  |-java/
  | `-sample/javafx/
  |   `-Main.java
  |
  `-resources/
    |-main.fxml
    `-main.css

main.css

1
2
3
4
5
6
7
8
.label {
    -fx-font-size: 25pt;
    -fx-text-fill: yellow;
    -fx-underline: true;
    -fx-padding: 10px;
    -fx-background-color: skyblue;
    -fx-font-family: consolas;
}

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package sample.javafx;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/main.fxml"));

        Parent root = loader.load();
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

正常设置时

main.fxml

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>

<Label stylesheets="main.css" text="Style Sheet" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" />

执行结果

javafx.jpg

样式表正确反映。

在Scene Budiler中查看

javafx.jpg

不反映样式表设置。

说明

main.fxml

1
<Label stylesheets="main.css" ... />
  • 为节点指定CSS文件在stylesheets属性中指定CSS文件的路径。
  • 此路径将相对于classpath的根

getStyleSheets()|场景(JavaFX 8)

URL是格式为[scheme:] [// Authority] [path]的分层URI。
如果URL没有[scheme:]组件,则该URL仅被视为[path]组件。
[path]之前的所有" /"字符都将被忽略,并且[path]被视为到应用程序类路径根目录的相对路径。

  • 也就是说,在运行时它可以从类路径的根目录中找到main.css,并且样式将正确应用。
  • 但是,在Scene Builder中查看时,不会应用样式,因为在Scene Builder类路径中找不到main.css
  • 这样,使用Scene Builder图形化创建屏幕的优点就消失了。

将其设置为在Scene Builder中看起来相同

main.fxml

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>

<Label stylesheets="@main.css" text="Style Sheet" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" />

执行结果

javafx.jpg

在Scene Budiler中查看

javafx.jpg

在Scene Builder中查看时,也会应用该样式。

说明

main.fxml

1
<Label stylesheets="@main.css" ... />
  • 指定stylesheets的路径规范以@开头

  • 然后,此路径将被视为该fxml文件中的相对路径

位置解析| FXML概述| JavaFX 8.0

位置解析运算符(由属性值的@前缀表示)应将属性值视为相对于当前文件的相对位置,而不是简单的字符串。

  • 结果,即使从Scene Builder中查看,也可以找到main.css,并且将应用样式。