答案 0 :(得分:2)
使用getBoundsInParent()
和lookup()
:
Bounds bounds = slider.lookup(".thumb").getBoundsInParent();
在查找之前,您可能需要applyCss()
到滑块才能使其正常工作。
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);
}
}