Background Image
A plain black background is perhaps not the most exciting so why don't we change it to something more exciting. To do this we are going to edit the SpaceInvaders.java file. First we need our Java program to load the image into its memory to do this we use the following line:
backGroundImage = new javax.swing.ImageIcon("back3.jpg").getImage();
Note: In the quote marks you can see the name of an image file, in this case a jpg called back3. Therefore if we want to load another image file we can change this filename, but before we do that we need to edit the paint code to tell our Java program to actually paint the image instead of the black background. To do this, we change:
public void paint(Graphics g) {
offscreen_high.setColor(Color.black);
offscreen_high.fillRect(0,0, WIDTH, HEIGHT);
army.drawArmy(offscreen_high);
ship.drawShip(offscreen_high);
g.drawImage(offscreen,0,0,this);
}
To this:
public void paint(Graphics g) {
offscreen_high.setColor(Color.black);
offscreen_high.fillRect(0,0, WIDTH, HEIGHT);
offscreen_high.drawImage(backGroundImage, 0, 0, this);
army.drawArmy(offscreen_high);
ship.drawShip(offscreen_high);
g.drawImage(offscreen,0,0,this);
}
Why don;t you have a look on Google images to find some more exciting backgrounds. Aim for an image around 600x400 pixels in size (a little bigger won't hurt).
To compile your code type:
javac *.java
If you don't encounter any errors then you can run your game with this command:
java -cp . SpaceInvaders
If you get any errors just ask your lab tutor.
Return to the start to make more changes <here>.