Monday, 11 June 2018

JavaFX: Add horizontal and vertical scrollbars to scroll pane

By using 'setHbarPolicy' and 'setVbarPolicy' methods, we can set horizontal and vertical scroll bars.

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

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);
 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment