JavaFX - change the color of a slider for a specific tick

So, I'm going to add a password generator to my gui application, I want to add a slider to choose how secure the password will be. I can change the color of all ticks, but I want to have red for the first, yellow for the second and green for the last tick. This is the css code to change the color of all major ticks. (Adapted from Color Changing Vise Slider )

.slider .axis .axis-tick-mark {
    -fx-fill: null;
    -fx-stroke: red;
}
+4
source share
1 answer

First of all, create a slider, as you suggest, with three main ticks:

@Override
public void start(Stage primaryStage) {
    Slider slider = new Slider(0, 10, 5);
    slider.setMajorTickUnit(5);
    slider.setMinorTickCount(0);
    slider.setShowTickMarks(true);
    slider.setSnapToTicks(true);
    StackPane root = new StackPane(slider);
    root.getStyleClass().add("pane");
    Scene scene = new Scene(root, 300, 250);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();
}

where style.csscontains:

.pane {
    -fx-background-color: #dcdcdc;
    -fx-padding: 10;
}

.slider .axis .axis-tick-mark {
    -fx-fill: null;
    -fx-stroke: red;
}

no gradient

Now let's see how tick axis labels are created and what type of node they are. To do this, you can select any of these options:

lookup . :

primaryStage.show();

System.out.println("Axis-Tick-Mark: " + slider.lookup(".axis-tick-mark"));

:

Axis-Tick-Mark: Path[elements=[MoveTo[x=0.0, y=0.0], LineTo[x=0.0, y=5.0], MoveTo[x=132.0, y=0.0], LineTo[x=132.0, y=5.0], MoveTo[x=264.0, y=0.0], LineTo[x=264.0, y=5.0]], fill=null, fillRule=NON_ZERO, stroke=0xff0000ff, strokeWidth=1.0]

, - Path, node. , - -.

, stroke .

, , :

.slider .axis .axis-tick-mark {
    -fx-fill: null;
    -fx-stroke-width: 2;
    -fx-stroke: linear-gradient(to right, red, yellow, green);
}

:

with gradient

, ( ), , ...

+5

Source: https://habr.com/ru/post/1694417/


All Articles