I want to display an image that is loaded into the program itself and displayed on the screen at X/Y coordinates I chose. It also needs to load relative or within the program (in a jar, for instance). Any help?
BufferedImage image = ImageIO.read(<ClassName>.class.getClassLoader().getResource("res/myImage.png"));
The path is relative to the current working directory, aka the “bin” folder of Eclipse or the folder and the root of the JAR file.
What he said, also:
g.drawImage(image,x,y,null)
(Not sure what that null does tho… ???)
The null is for an ImageObserver, it’s only if you want to keep track of how much it’s been painted on the screen. Mostly useless.
So… can I then call that image using the code Alex posted, which is the method I used when it was non-relative?
g.drawImage(image,x,y,null)
Update: Due to some weird difference between Graphics and Graphics2D, loading an image only works with Graphics2D and throws an exception on Graphics.
There must be a problem somewhere in your code. Graphics/Graphics2D don’t have anything to do with the loading of images, and all Graphics instances are in fact Graphics2Ds, at least in Sun’s implementation (this is why you can always just cast it without first doing an instanceof), so there shouldn’t be any difference in behavior between them. Post some code that shows the problem you’re having.
@BoBear2681:
Actually that is incorrect. According the Java API Graphics2D extends Graphics, thus not all graphics instances are graphics2ds. Although both classes can access a drawImage method…
Yes, but in Sun’s implementation, it is indeed the case that all Graphics instances passed to Component#paint() are actually Graphics2D’s. That’s why you see tons of examples everywhere where people cast to Graphics2D without checking first.
The Graphics parameter is there only to preserve backwards compatibility.
FWIW, you can get a Graphics that doesn’t subclass Graphics2D still today; for example, you could use javax.swing.DebugGraphics. People don’t use that in real life, of course.
Some places online also whisper of getting a different Graphics subclass when printing vs. painting a component, and indeed, there is a ProxyPrintGraphics class in the JDK, among others, that doesn’t inherit from Graphics2D. Not sure if/when it’s still used, and of course I’m too lazy to try to print a Component to see what happens!
AFAIK other vendors’ JVM implementations such as IBM, HP, etc. are always based off Sun’s and always end up using Graphics2D’s for standard UI painting.
But in short - yes, for an AWT-based game you’ll always be getting Graphics2Ds.