17

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

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中。但由于某种原因,图像没有显示。你能帮我纠正我的错误吗?

4

5 回答 5

55

只需替换此代码:

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

当您将 a 传递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:前缀只是一个 URI 方案,或者换句话说,http:协议分类器的对应物。这也适用于文件浏览器或网络浏览器......;)

如需进一步参考,您可以查看文件 URI 方案的 wiki 页面:https ://en.wikipedia.org/wiki/File_URI_scheme

快乐编码,

卡拉施

于 2013-04-19T11:56:55.260 回答
16

尝试这个:

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

如果没有给出指示 URL 的协议部分(如http:file:),则该文件应该驻留在默认包中。如果您希望它放入不同的包中,例如 com.my.images,您可以以类似路径的方式添加此信息:

img = new Image("/com/my/images/logo.png");
于 2013-04-20T15:48:35.917 回答
9
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
于 2016-06-15T00:25:33.627 回答
4

这个功能:

Image image  = new Image(getClass()
        .getResourceAsStream("ChimpHumanHand.jpg"));
于 2015-03-07T15:45:06.337 回答
0

将图像复制并粘贴到源包(NetBeans IDE 中的源包)所在的文件夹中。然后

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

两者都可以。

于 2015-05-22T11:58:42.560 回答