Javafx slider: text as tick label

流过昼夜 提交于 2019-12-01 05:48:20

Here is a sample using slider.setLabelFormatter.

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 {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Slider slider = new Slider(0, 3, 0);
        slider.setMin(0);
        slider.setMax(3);
        slider.setValue(1);
        slider.setMinorTickCount(0);
        slider.setMajorTickUnit(1);
        slider.setSnapToTicks(true);
        slider.setShowTickMarks(true);
        slider.setShowTickLabels(true);

        slider.setLabelFormatter(new StringConverter<Double>() {
            @Override
            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";
            }

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

                    default:
                        return 3d;
                }
            }
        });

        slider.setMinWidth(380);

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

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


    public static void main(String[] args) {
        launch(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.

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