使用“嵌套背景”生成如下边框:
pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
+ "-fx-background-insets: 0 0 0 0, 0 50 2 100, 2 2 2 2;");
The JavaFX CSS 文档具有所有细节,但基本上它的工作方式是创建三个背景,将其一层一层地放置。第一个是蓝色的,每边插入 0。 IE。:
pane.setStyle("-fx-background-color: blue; -fx-background-insets 0 0 0 0;");
这将创建一个填充整个窗格的蓝色矩形:
![enter image description here](https://i.stack.imgur.com/4WyOO.png)
第二个背景具有来自摩德纳的默认根背景(-fx-background
)。它有以下插图0
在顶部,50
向左转,2
在底部,以及100
在右边。所以前两个嵌套背景:
pane.setStyle("-fx-background-color: blue, -fx-background;"
+ "-fx-background-insets: 0 0 0 0, 0 50 2 100;");
产生这个:
![enter image description here](https://i.stack.imgur.com/vU7KQ.png)
请注意底部 2 像素宽的蓝线。
最后,第三个背景也有默认的背景颜色(-fx-background
),以及每侧两个像素的插图。因此,当将其放置在前两个背景上时,可以看到所需的效果:
![enter image description here](https://i.stack.imgur.com/bMzYs.png)
当所有四个边的值都相同时,您可以将四个值替换为单个值。所以CSS可以缩写
pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
+ "-fx-background-insets: 0 , 0 50 2 100, 2;");
只是一个技术说明:除非创建了至少一个控件,否则不会加载默认样式表,这就是我添加一个Label
在下面的完整示例中。
这是一个 SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class BorderWithGap extends Application {
@Override
public void start(Stage primaryStage) {
AnchorPane pane = new AnchorPane();
Label label = new Label("Border with gap");
AnchorPane.setTopAnchor(label, 50.0);
AnchorPane.setLeftAnchor(label, 50.0);
pane.getChildren().add(label);
pane.setStyle("-fx-background-color: blue, -fx-background, -fx-background;"
+ "-fx-background-insets: 0, 0 50 2 100, 2;");
Scene scene = new Scene(pane, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}