javaimagejavafxgridpane

JavaFX: Inserting image into a GridPane


Basically, I just want to insert an image into a cell within a gridpane.

GridPane gridpane = new GridPane();
gridpane.add(new Image("File:image/myfile.jpg"));
getChildren().addAll(gridpane);

Always tells me "Image is abstract, cannot be instantiated". Which I've Googled pretty extensively vaguely found that I have to use this as a BufferedImage or something? Not actually getting it though. What am I doing wrong here?


Solution

  • It seems that you have the wrong import for Image (you probably have java.awt.Image). The import you need for a JavaFX image is

    import javafx.scene.image.Image ;
    

    You then need to wrap the image in an ImageView, and add the ImageView to the grid pane:

    GridPane gridpane = new GridPane();
    Image image = new Image("File:image/myfile.jpg")
    gridpane.getChildren().add(new ImageView(image));