How do I draw a border around the text of a JavaFX label?

删除回忆录丶 提交于 2019-12-19 20:44:03

问题


In order to enhance the readability of our text, it has been suggested that we outline the text of label controls. I know you can stroke Text shapes, but we went with Labels. I forget why, but I think it was because there was something a Label could do for us that a Text Shape could not.

How do I go about drawing an outline or a border around the letters and words of a label?

I tried -fx-stroke but that didn't work, and -fx-border just drew a border around the node. Is there anyway to make this work?


回答1:


Use CSS to specify the outline for your label text.

/** 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;
}

Sample usage:

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);
    }
}

The above sample is using an undocumented selector to select the text for styling from the label. Usually, the JavaFX CSS documentation for complex nodes that are parent nodes containing child nodes includes a section for the child nodes in a section of the documentation titled "Substructure". For Labeled, the substructure is not provided, but if it were, it would read something like below:

Substructure

  • text — the text node within the Labeled

I found out the .text selector using a scene graph introspection tool such as ScenicView. For Java 9 the JavaFX implementation sets the style class in code in the class constructor for the following class: com.sun.javafx.scene.control.LabeledText, where it invokes getStyleClass().addAll("text");. So anyway, that is where the somewhat magically appearing subcomponent class .text originates from.



来源:https://stackoverflow.com/questions/27453799/how-do-i-draw-a-border-around-the-text-of-a-javafx-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!