简体   繁体   中英

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?

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));

Try this code ;)

image = new Image("File:image/myfile.jpg");
pic = new ImageView();
pic.setFitWidth(130);
pic.setFitHeight(130);
pic.setImage(image);
gridpane.add(pic);

Original Question

You can try this.

GridPane pane = new GridPane();
FileInputStream imageStream = new FileInputStream("us.gif");
Image image = new Image(imageStream);
pane.add(new ImageView(image), 0, 0);

Image is an abstract class and thus cannot be instancied. You should use one of the class who extend Image, like BufferedImage

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}

使用这个:

ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("picture.jpg")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM