JavaFX中无法加载图像(Cannot load image in JavaFX)

2019-08-31 13:37发布

我为了与图像创建对话框测试此代码。

final int xSize = 400;
final int ySize = 280;
final Color backgroundColor = Color.WHITE;
final String text = "SQL Browser";
final String version = "Product Version: 1.0";

final Stage aboutDialog = new Stage();
aboutDialog.initModality(Modality.WINDOW_MODAL);

Button closeButton = new Button("Close");

closeButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent arg0) {
        aboutDialog.close();
    }
});

GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));

Image img = new Image("logo.png");
ImageView imgView = new ImageView(img);

grid.add(imgView, 0, 0);

grid.add(new Text(text), 0, 1);
grid.add(new Text(version), 0, 2);
grid.add(closeButton, 14, 18);

Scene aboutDialogScene = new Scene(grid, xSize, ySize, backgroundColor);
aboutDialog.setScene(aboutDialogScene);
aboutDialog.show();

我把图像文件到目录/src 。 但由于某些原因不显示图像。 你能帮我改正我的错误?

Answer 1:

只需更换验证码

Image img = new Image("logo.png");

有了这个

Image img = new Image("file:logo.png");


Answer 2:

试试这个:

img = new Image("/logo.png");

如果指示URL没有协议部分(如http:文件:)中给出,该文件被假定驻留在默认包。 如果你想让它放在不同的包说你com.my.images以同样方式的路径添加此信息:

img = new Image("/com/my/images/logo.png");


Answer 3:

Image img = new Image("file:/logo.png");

或路径方式:

Image img = new Image("file:c:/logo.png");

要么

File f = new File("c:\\logo.png");
Image img = new Image(f.toURI().toString());

也可以使用:

new Image(file:src/logo.png) //root of project


Answer 4:

这个功能:

Image image  = new Image(getClass()
        .getResourceAsStream("ChimpHumanHand.jpg"));


Answer 5:

复制和将图像粘贴到文件夹中,其中源包(在NetBeans IDE源包)的存在。 然后

Image image = new Image("a1.jpg");
Image image = new Image("File:a1.jpg");

既会工作。



文章来源: Cannot load image in JavaFX