lipinf
lipinf

Reputation: 133

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?

Upvotes: 7

Views: 12977

Answers (2)

Miljan Rakita
Miljan Rakita

Reputation: 1533

img().impl_getUrl() returns string path

Upvotes: 0

jewelsea
jewelsea

Reputation: 159406

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.

Upvotes: 12

Related Questions