Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 835
Will Avatar asked Dec 05 '22 23:12

Will


1 Answers

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

outline

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.

like image 163
jewelsea Avatar answered Jan 23 '23 11:01

jewelsea