Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Image path JavaFx

I want to get the path name of the current Image loaded in my Image object.

I have the following code:

Image lol = new Image("fxml/images/bilhar9.png");

and I want to do something like:

lol.getPath();

that should return "fxml/images/bilhar9.png", I found the method impl_getUrl() but is deprecated.

What should I do?

like image 920
lipinf Avatar asked Aug 04 '14 16:08

lipinf


Video Answer


1 Answers

You can't get the image path from the image through a non-deprecated API, because no such API exists in Java 8. You could use the deprecated API and risk your application being broken in a future Java release when the deprecated API is removed - this is not advisable. You could create a feature request to make getURL() a public API on image, but that there is no guarantee that would be accepted and even if it was, it would only make it into a later Java release.

Image is not final, so I suggest the following:

class LocatedImage extends Image {
    private final String url;

    public LocatedImage(String url) {
        super(url);
        this.url = url;
    }

    public String getURL() {
        return url;
    }
}

Create your image like this:

Image image = new LocatedImage("fxml/images/bilhar9.png");

Then you can access the url via:

String url = image instanceof LocatedImage 
        ? ((LocatedImage) image).getURL() 
        : null;

Not a great solution, but maybe sufficient for your case.

like image 137
jewelsea Avatar answered Oct 04 '22 19:10

jewelsea