为了增强文本的可读性,有人建议我们对标签控件的文本进行轮廓化。我知道您可以描边文本形状,但我们选择了标签。我忘记了为什么,但我认为这是因为 Label 可以为我们做一些 Text Shape 做不到的事情。
如何在标签的字母和单词周围绘制轮廓或边框?
我尝试了 -fx-stroke
但没有用,而 -fx-border
只是在节点周围画了一个边框。有没有办法让这项工作成功?
最佳答案
使用 CSS 指定标签文本的轮廓。
/** file: outline.css (place in same directory as OutlinedLabelText) */
.label {
-fx-font-size: 50px;
}
.outline.label .text {
-fx-fill: lightseagreen;
-fx-stroke: firebrick;
-fx-stroke-width: 2px;
}
示例用法:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class OutlinedLabelText extends Application {
@Override
public void start(Stage stage) throws Exception {
Label label = new Label("Outlined");
label.getStyleClass().add("outline");
StackPane layout = new StackPane(label);
layout.setPadding(new Insets(10));
Scene scene = new Scene(layout, Color.PALEGREEN);
scene.getStylesheets().addAll(getClass().getResource(
"outline.css"
).toExternalForm());
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
上面的示例使用未记录的选择器从标签中选择要设置样式的文本。通常,JavaFX CSS documentation对于作为包含子节点的父节点的复杂节点,在标题为“子结构”的文档部分中包含一个子节点部分。对于 Labeled , 没有提供子结构,但如果有的话,它会像下面这样:
Substructure
- text — the text node within the Labeled
我使用场景图内省(introspection)工具(例如 ScenicView)找到了 .text
选择器.对于 Java 9,JavaFX 实现在类构造函数中的代码中为以下类设置样式类:com.sun.javafx.scene.control.LabeledText
,它调用 getStyleClass()。 addAll("文本");
。所以无论如何,这就是有点神奇地出现的子组件类 .text
的来源。
关于css - 如何在 JavaFX 标签的文本周围绘制边框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27453799/