How to display an image in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

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.

To display an image in JavaFX −

  • Create a FileInputStream representing the image you want to load.

  • Instantiate the Image class bypassing the input stream object created above, as a parameter to its constructor.

  • Instantiate the ImageView class.

  • Set the image to it by passing above the image object as a parameter to the setImage() method.

  • Set the required properties of the image view using the respective setter methods.

  • Add the image view mode to the group object.

Example

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Stage;
public class ImageViewExample 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 imageView = new ImageView();
      //Setting image to the image view
      imageView.setImage(image);
      //Setting the image view parameters
      imageView.setX(10);
      imageView.setY(10);
      imageView.setFitWidth(575);
      imageView.setPreserveRatio(true);
      //Setting the Scene object
      Group root = new Group(imageView);
      Scene scene = new Scene(root, 595, 370);
      stage.setTitle("Displaying Image");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]) {
      launch(args);
   }
}

Output

raja
Published on 16-May-2020 06:59:08
Advertisements