Javafx slider: text as tick label


I just started to learn Javafx, and I really like it so far. However in my current project I would need to use text as the tick labels for the javafx slider. I googled it a lot, but couldn't find any help. So for example I would like a slider with 4-5 positions, and them being "bad", "good", etc. instead of 1,2,3,...

I know I could build a custom UI manually with labels placed at the correct places, but I need to generate the sliders with custom text, and diofferent length every time, so it wouldn't work. In swing it is possible to change the labels with a hashtable for example, so my question is, is it possible to do it in Javafx?

8/26/2013 3:45:13 PM

Accepted Answer

Here is a sample using slider.setLabelFormatter.

slider snapshot

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;

public class SlidingScale extends Application {

    public void start(Stage primaryStage) throws Exception{
        Slider slider = new Slider(0, 3, 0);

        slider.setLabelFormatter(new StringConverter<Double>() {
            public String toString(Double n) {
                if (n < 0.5) return "Novice";
                if (n < 1.5) return "Intermediate";
                if (n < 2.5) return "Advanced";

                return "Expert";

            public Double fromString(String s) {
                switch (s) {
                    case "Novice":
                        return 0d;
                    case "Intermediate":
                        return 1d;
                    case "Advanced":
                        return 2d;
                    case "Expert":
                        return 3d;

                        return 3d;


        HBox layout = new HBox(slider);
        layout.setPadding(new Insets(30));

        primaryStage.setScene(new Scene(layout));;

    public static void main(String[] args) {

The sample above only works in Java 8 due to a bug in JavaFX 2.2.

Some of the labels disappear as you make the the slider smaller, so I set a min width on the slider so that the labels remain (an alternate solution, might be to set a new label formatter with abbreviated labels used if the slider is sized small).

You might also be interested in voting for or commenting on the following feature request: RT-27863 A LabelFormatter isn't enough to customize Slider ticks.

8/27/2013 7:50:01 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow