将图像加载到ImageView JavaFX [英] Load image to ImageView JavaFX
问题描述
我想在对话框窗口中显示图像(保存在项目文件夹中),但是当我运行我的方法showDialogWithImage时,我得到FileNotFoundExcpetion:imgs\pic1.jpg(系统找不到指定的文件),虽然图像是位于那里。
I would like to display image(saved in project folder) in dialog window, but when I run my method showDialogWithImage I get FileNotFoundExcpetion: imgs\pic1.jpg (The system cannot find the file specified), although the image is located there.
我也试过这样加载图像:
图像image = new Image(getClass()。getResourceAsStream(path)) ;但是也遇到了同样的问题。
I have tried load image on this way too:
Image image = new Image(getClass().getResourceAsStream(path));, but got the same problem.
是否有其他可能性将图像加载到ImageView?
感谢您的帮助!
Are there some others possibilities to load image to ImageView ?
Thank you for help!
-
我的Java代码位于项目文件夹中的src \ myProject \ gui。
My Java code is located in src\myProject\gui in project folder.
path =imgs\pic1.jpg// imgs位于项目文件夹中
path="imgs\pic1.jpg" // imgs is located in project folder
public void showDialogWithImage(String path) {
final Stage dialogStage = new Stage();
logger.info(path);
InputStream is = null;
try {
is = new FileInputStream(path); // here I get FileNotFoundException
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Image image = new Image(is);
ImageView view = new ImageView();
view.setImage(image);
Button btnOK = new Button("OK");
btnOK.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
dialogStage.close();
}
});
dialogStage.initModality(Modality.WINDOW_MODAL);
dialogStage.setScene(new Scene(VBoxBuilder.create()
.children(view, btnOK).alignment(Pos.CENTER)
.padding(new Insets(35)).build()));
dialogStage.show();
}
推荐答案
getClass()。getResourceAsStream(path)
将从调用类的位置开始搜索文件。因此,通过使用此路径imgs\pic1.jpg
,您说这是您的文件结构
getClass().getResourceAsStream(path)
will start its file search from the location of the calling class. So by using this path "imgs\pic1.jpg"
, you're saying this is your file structure
src\myProject\gui\imgs\pic1.jpg
要使搜索遍历,您需要在 imgs
之前添加额外的分隔符。所以
To have the search traverse back, you need the extra separator before imgs
. So
"\imgs\pic1.jpg"
另外,我认为当你使用反斜杠作为分隔符时,你需要逃避它。所以
Also, I think when you use a back slash as separator, you need to escape it. So
"\\imgs\\pic1.jpg
或者只是使用正斜杠
"/imgs/pic1.jpg
另一种选择是使用类加载器,它将从根目录进行搜索不需要开始分隔符
Another option is to use a class loader, that will search from the root, where you don't need the beginning separator
getClass().getClassLoader().getResourceAsStream("imgs/pic1.png");
这篇关于将图像加载到ImageView JavaFX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!