How to view multiple images in JavaFX?


The javafx.scene.image.Image class is used to load an image into a JavaFX application. This supports BMP, GIF, JPEG, and, PNG formats.

JavaFX provides a class named javafx.scene.image.ImageView is a node that is used to display, the loaded image.

  • The fitHeight property of the image view node represents the height of the bounding box within which you need to have displayed the image. You can set the value to this property using the setFitHeight() method.

  • The fitWidth property of the image view node represents the width of the bounding box within which you need to have displayed the image. You can set the value to this property using the setFitWidth() method.

  • The properties x and y represent the coordinates of the image view origin. You can set values to these using the setX() and setY() methods respectively.

Using these methods you can set multiple images in a single image view.

Example

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ViewingMultipleImages extends Application {
   public void start(Stage stage) throws IOException {
      //creating the image object
      InputStream stream = new FileInputStream("D:\images\elephant.jpg");
      Image image = new Image(stream);
      //Creating the image view
      ImageView imageView1 = new ImageView(image);
      //Setting the image view parameters
      imageView1.setX(10);
      imageView1.setY(10);
      imageView1.setFitWidth(200);
      imageView1.setPreserveRatio(true);
      ImageView imageView2 = new ImageView(image);
      //Setting the image view parameters
      imageView2.setX(230);
      imageView2.setY(10);
      imageView2.setFitWidth(350);
      imageView2.setPreserveRatio(true);
      //Setting the view port
      Rectangle2D rect2 = new Rectangle2D(45, 30, 250, 250);
      imageView2.setViewport(rect2);
      Image image2 = new Image(new FileInputStream("D:\images\boy.jpg"));
      //Creating the image view
      ImageView imageView3 = new ImageView(image2);
      //Setting the image view parameters
      imageView3.setX(10);
      imageView3.setY(200);
      imageView3.setFitWidth(200);
      imageView3.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView1, imageView2, imageView3);
      Scene scene = new Scene(root, 595, 370, Color.BEIGE);
      stage.setTitle("Multiple Images");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}

Output

Updated on: 16-May-2020

939 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements