Saturday 9 June 2018

JavaFX: Create scroll bar

How to create scrollbar?
ScrollBar class provides default constructor to define scroll bar instance.

Ex
ScrollBar scrollBar = new ScrollBar();

How to create horizontal (or) vertical scrollbar?
By setting the orientation to horizontal (or) vertical, you can create horizontal and vertical scroll bars.

Ex
ScrollBar verticalScrollBar = new ScrollBar();
verticalScrollBar.setOrientation(Orientation.VERTICAL);

ScrollBar horizontalScrollBar = new ScrollBar();
horizontalScrollBar.setOrientation(Orientation.HORIZONTAL);

Find the below working application.

ScrollBarApp.java
package com.sample.demos;

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

import javafx.application.Application;
import javafx.geometry.Orientation;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ScrollBarApp extends Application {

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

  ScrollBar verticalScrollBar = new ScrollBar();
  verticalScrollBar.setMin(0);
  verticalScrollBar.setOrientation(Orientation.VERTICAL);
  verticalScrollBar.setPrefHeight(180);
  verticalScrollBar.setMax(360);
  verticalScrollBar.setUnitIncrement(30);
  verticalScrollBar.setBlockIncrement(35);
  
  ScrollBar horizontalScrollBar = new ScrollBar();
  horizontalScrollBar.setMin(0);
  horizontalScrollBar.setOrientation(Orientation.HORIZONTAL);
  horizontalScrollBar.setPrefHeight(30);
  horizontalScrollBar.setPrefWidth(300);
  horizontalScrollBar.setMax(500);
  horizontalScrollBar.setUnitIncrement(30);
  horizontalScrollBar.setBlockIncrement(35);
  
  HBox hBox = new HBox(30, verticalScrollBar, horizontalScrollBar);

  Group root = new Group();
  root.getChildren().addAll(hBox);

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

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX scroll bar 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(ScrollBarApp.class, args);
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment