Adam Ren Adam Ren - 2 months ago 11
Java Question

How to display an image larger than the screen using a scrollPane JavaFX

How would one use a scrollPane to display an image larger than the screen in an application that is full screen? I have an image that is about 8000x3800 pixels and I would like to be able to move and interact with the entire image without having to resize it. If you wish specifics about my code or in general just ask.

public class SourceCodeVersion8 extends Application{

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

@Override
public void start(Stage primaryStage) throws Exception {
AnchorPane mapAnchorO = addMapAnchor();
Scene mapScene = new Scene(mapAnchorO);
primaryStage.setScene(mapScene);
primaryStage.setFullScreen(true);
primaryStage.setResizable(false);
primaryStage.show();
}

//Creates an AnchorPane for the map
private AnchorPane addMapAnchor()
{
AnchorPane mapAnchor = new AnchorPane();
ScrollPane mapScrollO = addMapScroll();
mapAnchor.getChildren().add(mapScrollO);
AnchorPane.setLeftAnchor(mapScrollO, 0.0);
AnchorPane.setTopAnchor(mapScrollO, 0.0);
return mapAnchor;
}

//Creates an ImageView for the map
private ImageView addMapView()
{
Image mapImage = new Image("WorldProvincialMap-v1.01.png");
ImageView mapView = new ImageView(mapImage);
return mapView;
}

//Creates a scrollPane for the map
private ScrollPane addMapScroll()
{
ScrollPane mapScroll = new ScrollPane();
ImageView mapViewO = addMapView();
mapScroll.setContent(mapViewO);
mapScroll.setPannable(true);
return mapScroll;
}

}

Answer

You only set 2 of 4 anchors for the ScrollPane, which is why the ScrollPane is never resized and just resizes to a size that allows displaying the whole image.

Therefore no scrollbars are neccessary and panning cannot be done.

You could fix this by also setting the right and bottom anchors. Alternatively use the ScrollPane as root directly.

private AnchorPane addMapAnchor() {
    AnchorPane mapAnchor = new AnchorPane();
    ScrollPane mapScrollO = addMapScroll();
    mapAnchor.getChildren().add(mapScrollO);
    AnchorPane.setLeftAnchor(mapScrollO, 0.0);
    AnchorPane.setTopAnchor(mapScrollO, 0.0);
    AnchorPane.setBottomAnchor(mapScrollO, 0.0);
    AnchorPane.setRightAnchor(mapScrollO, 0.0);
    return mapAnchor;
}