Sunday, 10 June 2018

JavaFX: Create scroll pane

By using 'ScrollPane' class, you can create a scroll pane.

Ex
ScrollPane scrollPane1 = new ScrollPane();
scrollPane1.setHbarPolicy(ScrollBarPolicy.ALWAYS);
scrollPane1.setVbarPolicy(ScrollBarPolicy.ALWAYS);

How to add content to scroll pane?
By using 'setContent' method of the ScrollPane class, you can add content to scroll pane.

Ex
InputStream is = new FileInputStream(imageFilePath);
Image image = new Image(is);
scrollPane1.setContent(new ImageView(image));

ScrollPaneApp.java
package com.sample.demos;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.MalformedURLException;

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

public class ScrollPaneApp extends Application {

 private static final String imageFilePath = "C:\\Users\\krishna\\Documents\\Study\\javaFX\\flowers.jpg";

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException, MalformedURLException {

  ScrollPane scrollPane1 = new ScrollPane();
  scrollPane1.setHbarPolicy(ScrollBarPolicy.ALWAYS);
  scrollPane1.setVbarPolicy(ScrollBarPolicy.ALWAYS);

  ScrollPane scrollPane2 = new ScrollPane();
  scrollPane2.setHbarPolicy(ScrollBarPolicy.ALWAYS);
  scrollPane2.setVbarPolicy(ScrollBarPolicy.ALWAYS);

  InputStream is = new FileInputStream(imageFilePath);
  Image image = new Image(is);

  scrollPane1.setContent(new ImageView(image));
  scrollPane2.setContent(new ImageView(image));

  HBox hBox = new HBox(30, scrollPane1, scrollPane2);

  Scene scene = new Scene(hBox, 500, 300);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX scroll pane app Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}


TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(ScrollPaneApp.class, args);
 }
}


Points to Note
a. The setMin and setMax methods define the minimum and maximum values represented by the scroll bar.

b. Horizontal is the default orientation of ScrollBar


Previous                                                 Next                                                 Home

No comments:

Post a Comment