我测试了此代码,以创建带有图像的对话框。
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");
Docu参考。 https://docs.oracle.com/javase/8/javafx/api/javafx/scene/image/Image.html
当你将a传递String
给Image
该类时,可以用四种不同的方式来处理(从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:
协议分类器。这在文件浏览器或Web浏览器中也适用...;)
作为进一步参考,你可以查看文件URI方案的Wiki页面:https : //en.wikipedia.org/wiki/File_URI_scheme
编码愉快,
卡拉施
该
"file:"
零件有什么作用?我已经编辑了答案,现在我希望它弄清楚它的作用。:)
奇怪的是,Schildt没有在Java中对此进行解释:完整参考
我用Image(url); 加载1MB大小的图像,需要5秒钟,时间太长!有什么方法可以解决这个问题?
@LeeRQ:这是什么类型的URL?HTTP还是本地文件?到目前为止,我还没有这个问题。