javajavafxjavafx-css

Cannot add CSS classes to my JavaFX Label


I am making a simple todolist app. Here is a watered-down version of it:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        ListView<Label> todoListView = new ListView();

        Label doneTodo = new Label ("This todo is meant to be finished and struck through");
        doneTodo.getStyleClass().add("done"); // Add the "done" class to this to-do
        Label undoneTodo = new Label("This todo is meant to be undone and therefore isn't struck through");

        // Add both to-dos to the listview
        addTodo(doneTodo, todoListView);
        addTodo(undoneTodo, todoListView);

        // Set the listview as the scene, and add the stylesheet
        Scene scene = new Scene(todoListView, 600, 550);
        scene.getStylesheets().add(getClass().getResource("styles.css").toExternalForm());

        primaryStage.setTitle("Label not taking on Strikethrough");
        primaryStage.setScene(scene);
        primaryStage.show();


    }

    // Adds the to-do (in this case just a simple Label) to the listview
    private static void addTodo(Label todo, ListView<Label> todoList) {
        todoList.getItems().add(todo);
    }


    public static void main(String[] args) {
        launch(args);
    }
}

Here is my CSS class:

.done {
    -fx-strikethrough: true;
}

When I run the code, the -fx-strikethrough property does not show up on my Label. Note that although this is a simplified version of my app, the issue remains the same: The text inside the JavaFX Label is not being struck through.

Again, sorry for any inadequacies in my question. I am fairly new to Stack Overflow!

Thanks in advance.


Solution

  • The CSS rule should apply to the text node under the label node:

    .done .text {
        -fx-strikethrough: true;
    }