简体   繁体   English

Javafx Slider 拇指

[英]Javafx Slider Thumb

Is there a way to display an integer on the slider thumb in javafx?有没有办法在 javafx 的 slider 拇指上显示 integer? Just curious because I am trying to make a clean UI and cannot find anything on displaying an integer on the slider thumb.只是好奇,因为我正在尝试制作一个干净的 UI,但在 slider 拇指上显示 integer 时找不到任何东西。

One way to address the requirement is by accessing the thumb node and include a Text/Label node.解决该要求的一种方法是访问拇指节点并包含一个文本/标签节点。 Please check the below demo for what i mean.请检查以下演示以了解我的意思。

You can adjust the thumb padding and the text size for fine tuning.您可以调整拇指填充和文本大小以进行微调。

在此处输入图像描述

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class SliderTextDemo extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Slider slider = new Slider(1, 10, 3);
        slider.setShowTickMarks(true);
        slider.setShowTickLabels(true);
        slider.setMajorTickUnit(1f);
        slider.setBlockIncrement(1f);
        slider.setSnapToTicks(true);

        Text text = new Text();
        slider.skinProperty().addListener((obs,old,skin)->{
            if(skin!=null){
                StackPane thumb = (StackPane)slider.lookup(".thumb");
                thumb.setPadding(new Insets(10));
                thumb.getChildren().add(text);
            }
        });
        slider.valueProperty().addListener((obs,old,val)->text.setText(val.intValue()+""));
        slider.setValue(2);

        VBox root = new VBox(slider);
        root.setAlignment(Pos.CENTER);
        root.setPadding(new Insets(20));
        root.setSpacing(20);
        Scene scene = new Scene(root,600,200);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Slider Text Demo");
        primaryStage.show();
    }
}

UPDATE:更新:

If you don't want to rely on accessing the skin,you can indeed implement/initialize the Slider as below.如果您不想依赖访问皮肤,您确实可以实现/初始化 Slider,如下所示。 That way you can create a custom Slider and can reuse in multiple places.这样您就可以创建自定义 Slider 并且可以在多个地方重复使用。

Slider slider = new Slider(1, 10, 3) {
    Text text;

    @Override
    protected void layoutChildren() {
        super.layoutChildren();
        if (text == null) {
            text = new Text(((int) getValue()) + "");
            valueProperty().addListener((obs, old, val) -> text.setText(val.intValue() + ""));
            StackPane thumb = (StackPane) lookup(".thumb");
            thumb.setPadding(new Insets(10));
            thumb.getChildren().add(text);
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM