JavaFX:将图像插入 GridPane

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36652453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:31:43  来源:igfitidea点击:

JavaFX: Inserting image into a GridPane

javaimagejavafxgridpane

提问by BEASTthisIndustry

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?

总是告诉我“图像是抽象的,无法实例化”。我在谷歌上搜索的非常广泛,模糊地发现我必须将它用作 BufferedImage 或其他什么?虽然实际上并没有得到它。我在这里做错了什么?

采纳答案by James_D

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

似乎您对Image(您可能有java.awt.Image)有错误的导入。JavaFX 图像所需的导入是

import javafx.scene.image.Image ;

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

然后,您需要将图像包裹在 中ImageView,并将 加入ImageView到网格窗格中:

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

回答by Maverick283

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

原始问题

回答by user1176726

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

Image 是一个抽象类,因此不能被实例化。您应该使用扩展 Image 的类之一,例如 BufferedImage

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

回答by Ramzan

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