Reputation:
I am creating an Image
object to which I want to set url of an image dynamically.
Image img = new Image();
if(vehicleType.equals("car"))
img.setUrl(images/car.png);
else
img.setUrl("");
Here, I don't know if car.png
exists in my images folder in classpath. How can I check for its existence? I want to set default vehicle image to the object if car.png
is not on classpath.
Thanks
Upvotes: 0
Views: 1178
Reputation: 418585
You can't check if an image is on the class path from the client side.
What you can do is add an ErrorHandler
to the Image
with its addErrorHandler()
method so you can detect if the browser can't load the image (because it doesn't exist on the server side for example).
Image img = new Image();
img.setUrl("SET YOUR URL");
img.addErrorHandler(new ErrorHandler() {
@Override
public void onError(ErrorEvent e){
// Failed to load image
}
});
Note: there is also an Image.addLoadHandler()
method which you can use to detect when an image is loaded.
Another way could be to create a method at server side that is published in a service which checks if the image is availabe, and call this method from your client code.
A Side Note
If you're the one that writes the client code and you tell the image url to be images/car.png
and you're the one that assembles server side resources, this shoudln't happen. At production environment you shouldn't use such checks. If you somewhere write img.setUrl("images/car.png")
you should make car.png
available at the server side and not bother with such runtime client side checks.
Upvotes: 2