我测试了这段代码以创建带有图像的对话框。
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
中。
但由于某种原因,图像没有显示。你能帮我改正我的错误吗?
最佳答案
只需替换这段代码:
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
当您将 String
传递给 Image
类时,可以用四种不同的方式处理它(从文档中复制 em>):
// 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:
协议(protocol)分类器的对应物。这也适用于文件浏览器或网络浏览器...;)
如需进一步引用,您可以查看文件 URI 方案的维基页面:https://en.wikipedia.org/wiki/File_URI_scheme
快乐编码,
卡拉什
关于java - 无法在 JavaFX 中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16099427/