A JavaFX ImageViewPane2 min read

When working with images in a JavaFX application you may want to create a view which will allow an image to be displayed and then remain centered as the application is re-sized. In JavaFX there is no out of the box solution for this.

You may first consider placing an ImageView object in an HBox or VBox, but maintaining aspect ratio and centering in these components is quite challenging. A solution to this is to create a custom ImageViewPane object. The ImageViewPane keeps an image centered and re-sized as the application is re-sized. The code for the class is as follows:

public class ImageViewPane extends AnchorPane {
    
    private Image image;
    
    public ImageViewPane(Image image)
    {
        this.image = image;
    }
    
    public void init()
    {
        ImageView displayImage = new ImageView();
        displayImage.setImage(image);
        displayImage.setPreserveRatio(true);
        displayImage.fitWidthProperty().bind(this.widthProperty());
        displayImage.fitHeightProperty().bind(this.heightProperty());
        
        VBox vbox = new VBox();
        AnchorPane.setTopAnchor(vbox, 0.0);
        AnchorPane.setBottomAnchor(vbox, 0.0);
        AnchorPane.setLeftAnchor(vbox, 0.0);
        AnchorPane.setRightAnchor(vbox, 0.0);
        vbox.setFillWidth(true);
        vbox.centerShapeProperty().set(true);
        vbox.setAlignment(Pos.CENTER);
        
        HBox hbox = new HBox();
        hbox.setCenterShape(true);
        hbox.setAlignment(Pos.CENTER);
        hbox.getChildren().add(displayImage);
        
        vbox.getChildren().add(hbox);
        VBox.setVgrow(hbox, Priority.ALWAYS);
        
        
        this.getChildren().add(vbox);
    }

}

As you can see, the ImageViewPane extends the AnchorPane and takes in the Image object to display in the constructor. Lines 12-16 create the ImageView, set the preservation of the image size ratio and then binds its size to the containing AnchorPane. Lines 18-25 create a VBox to keep the image vertically centered and lines 27-30 create a HBox to keep the image horizontally centered.

Now you can place the ImageViewPane wherever you would like to have an image displayed in your application. You could improve this class by implementing the Initializable interface and placing the contents of the init() in the initialize(URL location, ResourceBundle resources) method. That is all there is to it. Please feel free to make your suggestions for using or improving the ImageViewPane.

Leave a Reply

Your email address will not be published.