简体   繁体   中英

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:

        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".

UPDATE: I've tried to compile on ubuntu's command line and this was what i get. Hope it helps.

Going to assume you are using JDK 8 and above. 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. 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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