![](/img/trans.png)
[英]How can I be sure that my javaFX application is loading images from a relative path?
[英]how to show images with a relative path on a JavaFX application?
我正在創建一個需要顯示圖像的 JavaFX 應用程序,我目前的做法是這樣的:
ImageView icon=new ImageView(new Image("file:///C:/Users/MMJon/eclipse-workspace/Pumaguia/src/vista/resources/rutas.png"));
我試圖做到像這樣
ImageView icon=new ImageView(new Image(this.getClass().getResource("resources/rutas.png").toExternalForm()));
但它拋出一個空指針異常。 我怎樣才能做我需要的?
這是控制台的圖像,這是我的項目結構的圖像我的主類是“pumaguia”,顯示圖像的類在“pestanas”包中,包含圖像的文件夾是“resources”。
更新:我嘗試在 ubuntu 的命令行上編譯,這就是我得到的。 希望能幫助到你。
假設您使用的是 JDK 8 及更高版本。 路徑必須是相對的,並以適當的平台路徑分隔符開頭。
定義 ImageProvider 以確保您正確處理缺少圖像的情況。 請注意,我使用類引用來建立資源路徑。
public class ImageProvider {
private static ImageProvider imageSingleton;
private Image image = null;
private static final java.util.logging.Logger LOGGER = LogManager.getLogManager().getLogger("MyApp");
private ImageProvider(String imageStr) {
try {
image = new Image(ImageProvider.class.getResource(imageStr).toURI().toString());
} catch (URISyntaxException ex) {
LOGGER.log(Level.SEVERE, "Cannot fine image.", ex);
}
}
/**
* Returns an Image if possible.
* @param imageStr the relative path preceded by the appropriate platform path separator.
* @return
*/
public static Image getImage(String imageStr) {
return Optional.ofNullable(imageSingleton).orElseGet(() -> imageSingleton = new ImageProvider(imageStr)).image;
}
然后你可以使用;
ImageProvider.getImage("/img/myImage.png")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.