JavaFX中Slider thumb的坐标

时间:2016-06-30 19:12:51

标签: javafx

有一些方法可以在JavaFX中了解Slider拇指的位置吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

使用getBoundsInParent()lookup()

Bounds bounds = slider.lookup(".thumb").getBoundsInParent();

在查找之前,您可能需要applyCss()到滑块才能使其正常工作。

slipslide

import javafx.application.Application;
import javafx.geometry.Bounds;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class SlipSlide extends Application {
    @Override
    public void start(Stage stage) {
        Slider slider = new Slider(1, 10, 3);

        slider.setMajorTickUnit(9);
        slider.setMinorTickCount(8);
        slider.setSnapToTicks(true);
        slider.setShowTickMarks(true);
        slider.setShowTickLabels(true);
        slider.setPrefWidth(250);

        Label boundsLabel = new Label();

        VBox layout = new VBox(10, slider, boundsLabel);
        stage.setScene(new Scene(layout));

        stage.show();

        reportThumbBounds(slider, boundsLabel);
        slider.valueProperty().addListener((observable, oldValue, newValue) -> {
            reportThumbBounds(slider, boundsLabel);
        });
        slider.boundsInParentProperty().addListener((observable, oldValue, newValue) -> {
            reportThumbBounds(slider, boundsLabel);
        });
    }

    private void reportThumbBounds(Slider slider, Label boundsLabel) {
        Bounds bounds = slider.lookup(".thumb").getBoundsInParent();
        boundsLabel.setText(
                String.format(
                        "(%.2f,%.2f) (%.2f,%.2f)",
                        bounds.getMinX(), bounds.getMinY(),
                        bounds.getMaxX(), bounds.getMaxY()
                )
        );
    }

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