Coordinates of Slider thumb in JavaFX

前端 未结 1 1148
不思量自难忘°
不思量自难忘° 2021-01-24 10:53

There is some method to know the position of a Slider thumb in JavaFX?

相关标签:
1条回答
  • 2021-01-24 11:32

    Use getBoundsInParent() and a lookup():

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

    You may need to applyCss() to the slider before the lookup in order for it to work.

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题