简体   繁体   English

如何在 JavaFX 应用程序上显示具有相对路径的图像?

[英]how to show images with a relative path on a JavaFX application?

I'm creating a JavaFX application that needs to show an image, my currently way to do that is this:我正在创建一个需要显示图像的 JavaFX 应用程序,我目前的做法是这样的:

        ImageView icon=new ImageView(new Image("file:///C:/Users/MMJon/eclipse-workspace/Pumaguia/src/vista/resources/rutas.png"));

i've tried to do it like this我试图做到像这样

        ImageView icon=new ImageView(new Image(this.getClass().getResource("resources/rutas.png").toExternalForm()));

but it throws a Null Pointer exception.但它抛出一个空指针异常。 How can i do what i need?我怎样才能做我需要的?

Here's an image of the console and here's an image of my project's structure My main class is "pumaguia" and the class that shows the image is in "pestanas" package, and the folder that contains the image is "resources".这是控制台的图像,这是我的项目结构的图像我的主类是“pumaguia”,显示图像的类在“pestanas”包中,包含图像的文件夹是“resources”。

UPDATE: I've tried to compile on ubuntu's command line and this was what i get.更新:我尝试在 ubuntu 的命令行上编译,就是我得到的。 Hope it helps.希望能帮助到你。

Going to assume you are using JDK 8 and above.假设您使用的是 JDK 8 及更高版本。 The path must be relative and be preceded with the appropriate platform path separator.路径必须是相对的,并以适当的平台路径分隔符开头。

Define an ImageProvider to ensure you handle the absence of the image correctly.定义 ImageProvider 以确保您正确处理缺少图像的情况。 Note that I use a class reference to establish the resource path.请注意,我使用类引用来建立资源路径。

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;
    }

You can then use;然后你可以使用;

ImageProvider.getImage("/img/myImage.png")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM