I am developing a simple platform game using Java using BlueJ as the IDE. Right now I have player/enemy sprites, platforms and other items in the game drawn using polygons and simple shapes. Eventually I hope to replace them with actual images.
For now I would like to know what is the simplest solution to setting an image (either URL or from local source) as the ‘background’ of my game window/canvas?
I would appreciate it if it isn’t something long or complex as my programming skills aren’t very good and I want to keep my program as simple as possible. Kindly provide example codes with comments to elaborate on their function, and also if it’s in its own class, how to call on relevant methods used by it on other classes.
Thank you very much.
The answer will vary slightly depending on whether the application or applet is using AWT or Swing.
(Basically, classes that start with
Jsuch asJAppletandJFrameare Swing, andAppletandFrameare AWT.)In either case, the basic steps would be:
Imageobject.Componentyou want to draw the background in.Step 1. Loading the image can be either by using the
Toolkitclass or by theImageIOclass.The
Toolkit.createImagemethod can be used to load anImagefrom a location specified in aString:Similarly,
ImageIOcan be used:Step 2. The painting method for the
Componentthat should get the background will need to be overridden and paint theImageonto the component.For AWT, the method to override is the
paintmethod, and use thedrawImagemethod of theGraphicsobject that is handed into thepaintmethod:For Swing, the method to override is the
paintComponentmethod of theJComponent, and draw theImageas with what was done in AWT.Simple Component Example
Here’s a
Panelwhich loads an image file when instantiated, and draws that image on itself:For more information on painting: