I am trying to write a game in javaFX and need ImageView to display a png image with a transparent background as one of the sprites. I use Main class's getClass.getResource() method to find the image's URL. the image is saved under resources/images/transparentegg.png. I have this line in the constructor of my Bullet class, which extends ImageView:
setImage(new Image(Main.getMain().getResource("images/transparentegg.png").toString()));
Main class has a static field main which is set to this in the start method. Main.getMain() method returns that static field. Main.getResource() method has this body:
public URL getResource(String name) {
return getClass().getResource(name);
}
when I run the game with "images/transparentegg.png" as the input to getResource, I get an error and the image is not loaded. this is the error:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot invoke "java.net.URL.toString()" because the return value of "cuphead.cuphead.Main.getResource(String)" is null at cuphead.cuphead/cuphead.cuphead.sprite.Bullet.(Bullet.java:26) at cuphead.cuphead/cuphead.cuphead.sprite.Chicken.shoot(Chicken.java:80) at cuphead.cuphead/cuphead.cuphead.controller.GameController$2.handle(GameController.java:191) at cuphead.cuphead/cuphead.cuphead.controller.GameController$2.handle(GameController.java:188) at javafx.graphics@18.0.1/com.sun.scenario.animation.shared.TimelineClipCore.visitKeyFrame(TimelineClipCore.java:239) at javafx.graphics@18.0.1/com.sun.scenario.animation.shared.TimelineClipCore.playTo(TimelineClipCore.java:180) at javafx.graphics@18.0.1/javafx.animation.Timeline.doPlayTo(Timeline.java:172) at javafx.graphics@18.0.1/javafx.animation.AnimationAccessorImpl.playTo(AnimationAccessorImpl.java:39) at javafx.graphics@18.0.1/com.sun.scenario.animation.shared.InfiniteClipEnvelope.timePulse(InfiniteClipEnvelope.java:104) at javafx.graphics@18.0.1/javafx.animation.Animation.doTimePulse(Animation.java:1189) at javafx.graphics@18.0.1/javafx.animation.Animation$1.lambda$timePulse$0(Animation.java:207) at java.base/java.security.AccessController.doPrivileged(AccessController.java:399) at javafx.graphics@18.0.1/javafx.animation.Animation$1.timePulse(Animation.java:206)
However, if I enter "images/egg.png" as the argument of getResource, the program runs without a problem. images/egg.png is another image of the egg but without a transparent background: the background is black.
I am using java 17, and JavaFX 18. The program is being run on Windows 10. I will also include the aforementioned images.
EDIT I updated to java 18 and the issue was resolved.