How to create a scroll pane using JavaFX?



A scroll pane holds a UI element and provides a scrollable view of it. In JavaFX, you can create a scroll pane by instantiating the javafx.scene.control.ScrollPane class. You can set content to the scroll pane using the setContent() method.

  • To add a scroll pane to a node −

  • Instantiate the ScrollPane class.

  • Create the desired node.

  • Set the node to the scroll pane using the setContent() method.

  • Set the dimensions of the scroll pane using the setter methods.

  • Add the scroll pane to the layout pane or group.

Example

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ScrollPaneActionExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //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);
      //Creating the scroll pane
      ScrollPane scroll = new ScrollPane();
      scroll.setPrefSize(595, 200);
      //Setting content to the scroll pane
      scroll.setContent(imageView);
      //Setting the stage
      Group root = new Group();
      root.getChildren().addAll(scroll);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Scroll Pane Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 18-May-2020 11:21:43
Advertisements