无法在javafx中加载图像

toiithl6  于 2021-07-03  发布在  Java
关注(0)|答案(5)|浏览(397)

我测试了这段代码,以便创建带有图像的对话框。

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 . 但由于某些原因,图像没有显示出来。你能帮我改正错误吗?

wswtfjt7

wswtfjt71#

试试这个:

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

如果没有给出指示url的协议部分(如http:或file:),则该文件应该驻留在默认包中。如果你想把它放在一个不同的包中,比如com.my.images,你可以用类似路径的方式添加这些信息:

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

cvxl0en22#

只需替换此代码:

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

用这个

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

文件参考。https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/image.html
当你经过一个 StringImage 类它可以用四种不同的方式处理(从docu复制):

// The image is located in default package of the classpath
Image image1 = new Image("/flower.png");

// The image is located in my.res package of the classpath
Image image2 = new Image("my/res/flower.png");

// The image is downloaded from the supplied URL through http protocol
Image image3 = new Image("http://sample.com/res/flower.png");

// The image is located in the current working directory
Image image4 = new Image("file:flower.png");

这个 file: prefix只是一个uri方案,或者换句话说是 http: 协议分类器。这也适用于文件浏览器或web浏览器…;)
如需进一步参考,您可以查看文件uri方案的wiki页面:https://en.wikipedia.org/wiki/file_uri_scheme
快乐的编码,
卡拉什

1cklez4t

1cklez4t3#

将映像复制并粘贴到存在源程序包(netbeanside中的源程序包)的文件夹中。那么

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

两者都会起作用。

4ktjp1zp

4ktjp1zp4#

此功能:

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

wfauudbj5#

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

相关问题