JavaFX ScrollPane class

Introduction

The following code shows how to use a scroll pane.

It creates a multi-line label and add the label to scroll pane.

We can add any Node can be scrolled to a scroll pane.


import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;

public class Main extends Application {
   // Create a label that will be scrolled.
   Label scrlLabel = new Label("CSS\n" + "HTML\n" + "Java\n" + "SQL\n" + "Data\n" + "Web\n" + "IDE");

   // Create a scroll pane, setting scrlLabel as the content.
   ScrollPane scrlPane = new ScrollPane(scrlLabel);
   public static void main(String[] args) {
      launch(args);//w  ww.j  a v a 2 s. c  o m
   }
   public void start(Stage myStage) {
      myStage.setTitle("Demonstrate a ScrollPane");
      FlowPane rootNode = new FlowPane(10, 10);
      rootNode.setAlignment(Pos.CENTER);
      Scene myScene = new Scene(rootNode, 200, 200);
      myStage.setScene(myScene);

      // Set the viewport width and height.
      scrlPane.setPrefViewportWidth(130);
      scrlPane.setPrefViewportHeight(80);

      // Enable panning.
      scrlPane.setPannable(true);

      // Create a reset label.
      Button btnReset = new Button("Reset Scroll Bar Positions");

      // Handle action events for the reset button.
      btnReset.setOnAction(e->{
            // Set the scroll bars to their zero position.
            scrlPane.setVvalue(0);
            scrlPane.setHvalue(0);
      });
      rootNode.getChildren().addAll(scrlPane, btnReset);

      myStage.show();
   }
}



PreviousNext

Related