Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - First attempts at painting Current Page - 04 - First images   Next Page - Optimizing the loading of images
  Return to the index of free Java tutorials  

First images

(c) Alexander Hristov
English Version proofreading and corrections : Jeff Lunt

Since we want to develop a somewhat interesting game, it is clear that we cannot paint our monsters and spaceships using the standard Java drawing primitives of Graphics2D (i.e. lines, points, and simple shapes). Instead we will use image files which we will load as we need them.

So our next step will be loading an external image and painting it on the window. As a starting point and in order to make use of transparency easy , we'll use .gif images, and we'll load them using the ImageIO class added in JDK 1.4.

The image we'll load is called bicho.gif and must be in a subdirectory called "res" (resources) beneath the main directory of our project (but not beneath the package directory). For example, if our class is located in c:\planetalia\curso\java\version04\Invaders.class, then the resource directory must be located in c:\planetalia\curso\java\res\):

The specific image is:

Java Monster


1     package version04;
2     /**
3      * Curso B?sico de desarrollo de Juegos en Java - Invaders
4      * 
5      * (c) 2004 Planetalia S.L. - Todos los derechos reservados. Prohibida su reproducci?n
6      * 
7      * http://www.planetalia.com
8      * 
9      */
10    
11    
12    import java.awt.Canvas;
13    import java.awt.Dimension;
14    import java.awt.Graphics;
15    import java.awt.event.WindowAdapter;
16    import java.awt.event.WindowEvent;
17    import java.awt.image.BufferedImage;
18    import java.net.URL;
19    
20    import javax.imageio.ImageIO;
21    import javax.swing.JFrame;
22    import javax.swing.JPanel;
23    
24    public class Invaders extends Canvas {
25      public static final int WIDTH = 800;
26      public static final int HEIGHT = 600;
27      
28      
29      public Invaders() {
30        JFrame ventana = new JFrame("Invaders");
31        JPanel panel = (JPanel)ventana.getContentPane();
32        setBounds(0,0,WIDTH,HEIGHT);
33        panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
34        panel.setLayout(null);
35        panel.add(this);
36        ventana.setBounds(0,0,WIDTH,HEIGHT);
37        ventana.setVisible(true);
38        ventana.addWindowListener( new WindowAdapter() {
39          public void windowClosing(WindowEvent e) {
40            System.exit(0);
41          }
42        });
43      }
44      
45      public BufferedImage loadImage(String nombre) {
46 URL url=null; 47 try { 48 url = getClass().getClassLoader().getResource(nombre); 49 return ImageIO.read(url); 50 } catch (Exception e) { 51 System.out.println("No se pudo cargar la imagen " + nombre +" de "+url); 52 System.out.println("El error fue : "+e.getClass().getName()+" "+e.getMessage()); 53 System.exit(0); 54 return null; 55 } 56 } 57 58
59 public void paint(Graphics g) { 60 BufferedImage bicho = loadImage("res/bicho.gif");
61 g.drawImage(bicho, 40, 40,this);
62 } 63 64 public static void main(String[] args) { 65 Invaders inv = new Invaders(); 66 } 67 } 68

You can see that error handling is almost nonexistent : Any problem during the loading of the image causes the program to stop. We'll try to improve this later on.

It's also interesting to point that instead of using a hand-coded path to the image, we use getClass().getClassLoader().getResource(...), which allows us to get a URL pointing to the folder from which our class was loaded. This allows us to move the program, or turn it into an applet, or deploy it using WebStart without having to change anything regarding the location of the images.

The result of this program is the following window:

Tutorial Space Invaders en Java



Do you want to be notified when new tutorials or lessons are published? Press here


Full list of Java source files for this step

Invaders.java      

Full list of resources

bicho.gif bicho0.gif bicho1.gif bicho2.gif
bombD.gif bombDL.gif bombDR.gif bombL.gif
bombR.gif bombU.gif bombUL.gif bombUR.gif
disparo.gif disparo0.gif disparo1.gif disparo2.gif
explosion.wav misil.gif missile.wav musica.wav
nave.gif oceano.gif photon.wav test.gif
Thumbs.db      

  Previous Page - First attempts at painting Current Page - 04 - First images   Next Page - Optimizing the loading of images
  Return to the index of free Java tutorials  

(c) 2004 Planetalia S.L. All rights reserved. Unauthorized reproduction and/or mirroring is not permitted