JavaFX: How can I horizontally center an ImageView inside a ScrollPane?

1k views Asked by At
viewScroll.setContent(new ImageView(bigimg));
double w = viewScroll.getContent().getBoundsInLocal().getWidth();
double vw = viewScroll.getViewportBounds().getWidth();

viewScroll.getContent().setTranslateX((vw/2)-(w/2));

viewScroll.toFront();

I set an ImageView with some Image inside the ScrollPane but the ImageView always goes to the far left corner. Here I'm trying to manually offset the difference, but it doesn't work well. The ImageView goes too far to the right plus it only updates once because it's inside the eventhandler for a button.

1

There are 1 answers

6
Chris Smith On BEST ANSWER

Here is an example using a label without the need for listeners:

public void start(Stage primaryStage) throws Exception {
    ScrollPane scrollPane = new ScrollPane();
    Label label = new Label("Hello!");
    label.translateXProperty().bind(scrollPane.widthProperty().subtract(label.widthProperty()).divide(2));
    scrollPane.setContent(label);
    Scene scene = new Scene(scrollPane);
    primaryStage.setScene(scene);
    primaryStage.setWidth(200);
    primaryStage.setHeight(200);
    primaryStage.show();
}

I am not sure if you are familiar with properties or not, but in the code above, when I bind the translateXProperty to the formula, every time one of the dependencies changes, such as the ScrollPane's widthProperty or the Label's widthProperty, the formula is recalculated and translateXProperty is set to the result of the formula.

I am not sure, but in your previous code, it appears that the calculation code would be in a resize listener. This is not required when dealing with properties as they update whenever dependencies changed (note the bind() and not set()).