How to add scroll bar to an image in JavaFX?


A scroll bar contains a thumb, right and left buttons attached to a scrollable pane. Using this you can scroll the pane (attached to it) up and down.

In JavaFX the javafx.scene.control.ScrollBar represents a scrollbar. You can create a scroll bar instantiating this class. Usually, a scroll bar is associated with other controls such as ScrollPane, ListView, etc.

Setting ScrollBar to an image

The property named value specifies the current value represented by the scroll bar you can add a listener to this property using the addListener() method.

To attach a scroll bar to an image −

  • Create an ImageView object representing the required image.

  • Create a pane to hold the image view such as scroll pane, vBox, etc..

  • Add a listener to the value property, of the scroll bar.

  • Based on the orientation of the scroll bar, set the X/Y layouts of the layout pane, with the negative of the new value of the scroll bar.

Example

public class ScrollBarActionExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Label for education
      Label label = new Label("Educational qualification:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //list View for educational qualification
      ScrollBar scroll = new ScrollBar();
      scroll.setMin(0);
      scroll.setOrientation(Orientation.VERTICAL);
      scroll.setPrefHeight(200);
      scroll.setPrefWidth(20);
      //creating the image object
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView = new ImageView();
      //Setting image to the image view
      imageView.setImage(image);
      //Setting the image view parameters
      imageView.setX(5);
      imageView.setY(0);
      imageView.setFitWidth(595);
      imageView.setPreserveRatio(true);
      //Adding the toggle button to the pane
      VBox vBox = new VBox(5);
      vBox.getChildren().addAll(imageView);
      scroll.valueProperty().addListener((ObservableValue<? extends Number> ov, Number old_val, Number new_val) -> {
         vBox.setLayoutY(-new_val.doubleValue());
      });
      //Setting the stage
      Group root = new Group();
      root.getChildren().addAll(vBox, scroll);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Scroll Bar Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 18-May-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements