JavaFX Image scroll with ScrollPane

JavaFx Layout Management: Exercise-12 with Solution

Write a JavaFX application that includes a ScrollPane to display a large image with scrollbars for navigation.

Sample Solution:

JavaFx Code:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {

    public void start(Stage primaryStage) {
        primaryStage.setTitle("Image ScrollPane Example");

        // Load a large image
        Image image = new Image("large_image.png"); // Replace with your image file path

        // Create an ImageView to display the image
        ImageView imageView = new ImageView(image);

        // Create a ScrollPane to display the image with scrollbars
        ScrollPane scrollPane = new ScrollPane(imageView);

        // Set scroll policy to ensure both horizontal and vertical scrollbars appear as needed

        // Create a StackPane to hold the ScrollPane
        StackPane root = new StackPane();

        // Create a scene and add it to the stage
        Scene scene = new Scene(root, 800, 600);


In the exercise above, we load a large image, create an 'ImageView' to display it, and place it within a 'ScrollPane' to provide scrollbars. The scroll policy is set to "AS_NEEDED" for both horizontal and vertical scrollbars. Finally, the 'ScrollPane' is added to a 'StackPane', which is added to the 'Scene' and displayed in the 'Stage'.

Note: Replace "large_image.png" with the path to your own image file.

Sample Output:

JavaFx: JavaFX Image scroll with ScrollPane
JavaFx: JavaFX Image scroll with ScrollPane


Flowchart: JavaFX Image scroll with ScrollPane.

Java Code Editor:

Previous: JJavaFX Honeycomb layout design.
Next: JavaFX Text scroll with ScrollPane.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.