Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (480)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (546)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  help with mediatracker & loading images  (Read 808 times)
0 Members and 1 Guest are viewing this topic.
Offline uraknai

Senior Newbie





« Posted 2006-04-23 13:23:05 »

hi,

I have class to load images and storing them in a hash table. I then need to display the images using another class which extends Canvas.

Heres my images class:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
package InvadersGame;

import java.awt.*;
import java.util.*;



public class Images {

/** mediatracker to make sure an image has been loaded */
  private MediaTracker mediaTracker;
  /** hashtable of all loaded images keyed by image file name */
  private Hashtable images;
  /** used for image id in the media tracker */
  private int imageCount=0;

  /**
   * constructing the image object
   * @param frame the parent frame used to load images
   */

  public Images(SpaceInvaders invaders) {
    mediaTracker = new MediaTracker(invaders);
    images = new Hashtable();
  }

  /**
   * load all needed images from files
   */

  public void loadImages()
  {
    //enemy images
   loadImage("images/alien.gif", Color.white);    
  }

  /**
   * load an image from a specific location
   * @param path location of the image file
   * @return an image object, or null if an error happens
   */

  public Image loadImage(String path, Color c)
  {
     
    Image image = Toolkit.getDefaultToolkit().getImage(path);
    addToMediaTracker(image, path);
    if(c!=null)
    {
      //image = GeneralUtil.setTransparentColorOld(image, c);
   }
    waitForImage(image);

    int pos = path.lastIndexOf("/");
    if(pos>=0) images.put(path.substring(pos+1), image);
    return image;
  }

  /**
   * wait for the image to be fully loaded
   * @param image image to be waited for
   */

  private void waitForImage(Image image)
  {
    if(image==null)
    {
      System.out.println("Error Loding Image");
      return;
    }
    while(image.getWidth(null)<0 || image.getHeight(null)<0){}
  }

  private void addToMediaTracker(Image image, String path) {

    if (image == null) {
      System.out.println("Could not load image " + path);
    }
    else {
      mediaTracker.addImage(image, imageCount);
    }
    try {
      mediaTracker.waitForID(imageCount);
      System.out.println("Image loaded " + path +" " +imageCount+" with (w,h)=("+image.getWidth(null)+","+image.getHeight(null)+")");
      imageCount++;
    }
    catch (InterruptedException e) {
      System.out.println("Interrupted while wiating for image " + e);
    }
  }

  /**
   * get an image object from the hashtable given its key
   * @param str image key
   * @return image object if found, otherwise it returns false
   */

  public Image getImage(String str)
  {
    return (Image)images.get(str);
  }
 
   public Image getImageByIndex(int i)
  {
    return (Image)images.get(i);
  }
 
}



and here's the class that should display the images.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
package InvadersGame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.Random;
import java.awt.image.BufferStrategy;


public class SpaceInvaders extends Canvas{
   
    Images image;
   
    JPanel panel;
    //AlienEntity al, al2;
   Graphics2D g2;
    boolean gameRunning = true;
    ArrayList<GameEntities> entitiesList;
    AnimationThread thread;
    private BufferStrategy buffer;
    protected Images imgs;
   
   
    class AnimationThread extends Thread
    {
        public void run()
        {
            while(true)
            {
                paintEntities();
                animateEntities();                
                updateGame();
                try
                {
                    sleep(50);
                }
                catch(InterruptedException e){}
            }
        }
    }
   
    public SpaceInvaders()
    {
        super();
                 
        imgs = new Images(this);
        imgs.loadImage("images/alien.png", null);
        imgs.loadImage("images/a.png", null);
       
        JFrame window = new JFrame("Space Invaders");
        JPanel panel = (JPanel)window.getContentPane();
        setBounds(0, 0, 800, 600);
       
        panel.add(this);
        window.setBounds(0, 0, 800, 600);
        window.setVisible(true);          
       
        window.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
               
        setFocusable(true);
       
        this.createBufferStrategy(2);
        buffer = getBufferStrategy();
       
        thread = new AnimationThread();  
           
        initialise();
    }
   
   
    public void initialise()
    {
        entitiesList = new ArrayList();
        for(int i=0; i<3; i++)
        {
            AlienEntity alien = new AlienEntity(this);
            alien.setX((int)(Math.random()*getWidth()));
           
            entitiesList.add(alien);
        }
    }
   
    public void addGameEntity(GameEntities entity)
    {
        entitiesList.add(entity);
    }
   
   
   public void updateGame()
   {
       //entity out of bounds
      for(int i=0; i<entitiesList.size(); i++)
       {
            if((entitiesList.get(i).getY()>(getHeight()+50))||(entitiesList.get(i).getX()>(getWidth()+50)))
            {
                entitiesList.get(i).setDeletionMarkedTrue(true);
            }
       }    
       
       
       //remove entities with deletion mark true
      for(int i=0; i<entitiesList.size(); i++)
       {
           if(entitiesList.get(i).deletionMark)
           {
               entitiesList.remove(i);
           }
       }
   }
       
    public void paintEntities()
    {
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
               
        g.drawImage(imgs.getImageByIndex(0), 0,0,this);
        g.drawImage(imgs.getImageByIndex(1), 20, 20,this);
               
        buffer.show();
    }
   
    public void animateEntities()
    {
         for(int i=0; i<entitiesList.size(); i++)
        {
            entitiesList.get(i).move();
            System.out.println(entitiesList.get(i).getY());
        }
    }
   
    public Image getImage(String name)
    {
        Image image = imgs.getImage(name);
        return image;
    }
   
   
    public void setBufferstrategy(BufferStrategy buffer)
    {
        buffer = buffer;
    }
   

    public static void main(String[] args)
    {        
        SpaceInvaders canvas = new SpaceInvaders();  
        canvas.thread.start();
    }
   
}



Excuse the mess of my code. I've been chopping and changing to try and gt the images loaded.


In the SpaceInvaders constructor I load the images:

1  
2  
3  
imgs = new Images(this);
        imgs.loadImage("images/alien.png", null);
        imgs.loadImage("images/a.png", null);



and then in the paint() method I select the image from the hash table by it's key:

1  
2  
3  
4  
g.drawImage(imgs.getImageByIndex(0), 0,0,this);
        g.drawImage(imgs.getImageByIndex(1), 20, 20,this);
               
        buffer.show();



Both of these steps are successful but the images aren't displayed in the Frame.

Could someone please help.

cheers
Offline oNyx

JGO Coder


Medals: 2


pixels! :x


« Reply #1 - Posted 2006-04-23 18:35:18 »

How about... using ImageIO like everyone else?

弾幕 ☆ @mahonnaiseblog
Offline Jeff

JGO Coder




Got any cats?


« Reply #2 - Posted 2006-04-23 18:48:13 »

You appear to be trying to wait be spinning until width or height is greater then -1.

This is wrong a whole bunch of ways.  use your media tracker and the MediaTracker.waitforId(...)  call.

Thats what a MediaTracker is for.


Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline uraknai

Senior Newbie





« Reply #3 - Posted 2006-04-26 22:20:13 »

Thanks for the replies guys. It's all sorted and working fine now.

I am having another little problem though. I'm writing a simple space invaders game and need to move and shoot at the same time. My current ship movement is controlled by the keyPressed method:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
public void keyPressed(KeyEvent e)
    {
        int code = e.getKeyCode();
       
        switch(code)
        {
            case 39:ship.moveRight(); break;
            case 37:ship.moveLeft(); break;
            case 32shipFire = new ShipFire(ship.x+0.25*ship.width, ship.y-15, imageHandler.getImages(5));
                      entitiesList.add(shipFire);
                      System.out.println("FIRE");
                      break;
        }       
       
       
    }


This will only allow me to do one key press at a time, so I can't press left and space at the same time to move left and fire. Is there a way to re-write it so I can move and fire at the same time?

Cheers Wink
Offline Kova

Senior Member





« Reply #4 - Posted 2006-04-27 07:54:42 »

yes, use if statements instead of switches.

and i't much nicer to see KeyEvent constants instead of integers for key code. For example, KeyEvent.VK_SPACE.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

atombrot (21 views)
2014-08-19 09:29:53

Tekkerue (21 views)
2014-08-16 06:45:27

Tekkerue (21 views)
2014-08-16 06:22:17

Tekkerue (12 views)
2014-08-16 06:20:21

Tekkerue (19 views)
2014-08-16 06:12:11

Rayexar (56 views)
2014-08-11 02:49:23

BurntPizza (37 views)
2014-08-09 21:09:32

BurntPizza (29 views)
2014-08-08 02:01:56

Norakomi (35 views)
2014-08-06 19:49:38

BurntPizza (65 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!