Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (522)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (590)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1]
1  Java Game APIs & Engines / Java 2D / Need help painting on Canvas on: 2006-08-31 12:15:08
Hi,

I've wrote an application that extends Canvas that needs to draw images on screen. I have 2 paint methods, one draws images and the other clears the screen. The 2 paint methods are as follows:

 
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
public void clearScreen()
    {    
       
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
                       
        Rectangle2D clear = new Rectangle2D.Double(0,0,(int)3*this.getWidth()/4, this.getHeight());
        g.setColor(Color.lightGray);
        g.fill(clear);
               
        Rectangle2D divisionArea = new Rectangle2D.Double((int)3*this.getWidth()/4, 0,this.getWidth(),this.getHeight());
        g.setColor(Color.gray);
        g.fill(divisionArea);

    }

   
and
   
   
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
 public void paintQuestions()
    {
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();  
       
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
       
        for(int i = 0; i<selectedQuestionList.size(); i++)
        {
            selectedQuestionList.get(i).draw(g);
            selectedAnswerList.get(i).draw(g);
        }      
       
    }


The paint questions and clear the screen methods are continually called within the following thread:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
class UpdateThread extends Thread
    {
       
        public void run()
        {
            clearScreen();
            paintQuestions();
           
            while(true)
            {  
                                                       
                    try
                    {
                        sleep(130);
                    }
                    catch(InterruptedException e){}                                        
                         
            }            
        }
    }


Is there a way to implement the paint methods and update the screen WITHOUT using a thread since the thread is causing a few problems to the application.

Help would be much appreciated.

Thanks,

Nick
2  Game Development / Newbie & Debugging Questions / Re: Help loading images in an Executable JAR. on: 2006-08-19 10:34:38
Thanks for your help. I just have a few questions.

My project folder is called Maths.
Within this folder are the folders build, dist and src, with src containing my package folders as well as image folder.

I created a manifest using notepad as follows:

Manifest-Version: 1.0
Main-Class: Menu.Login
Created-By: 1.5 (Sun Microsystems Inc.)

Where Menu is the package name (located in the src folder) and Login is the name of the class with the main method to be run.

I save the manifest in the Maths folder (I'm not sure whether it should be saved here or in one of the other folders)

From the DOS prompt I change the directory to the Maths folder (where th manifest is located) and type:

jar cvfm myapp.jar manifest.MF *

It then compresses all the files and creates a JAR.

The problem is that  when I click on the JAR it says "Could not find the main class. Program will exit".

Could you tell me why this happens. Is there a problem with my manifest or how I create the JAR or something else?

Cheers



3  Game Development / Newbie & Debugging Questions / Re: Help loading images in an Executable JAR. on: 2006-08-18 13:02:08
You're right, I don't really know how to make a JAR using netbeans. Could you possibly tell me why the method I used to create a JAR doesn't load the images whereas it runs fine within netbeans.

Thanks
4  Game Development / Newbie & Debugging Questions / Help loading images in an Executable JAR. on: 2006-08-18 10:35:11
Hi,

I've developed an application using netbeans that needs to load and display images.

I use netbeans Clean and Build function to create an executable Jar file. When I run the executable Jar file it runs fine but when I come to a section of the application that needs images it freezes and can't load the images.

When I then return to netbeans the part of the program that did successfully run before Clean and Build doesn't work anymore and I get an error message saying Uncaught error fetching image:

I use,


1  
2  
URL url = getClass().getResource("images/image1.png");
Image image1 = Toolkit.getDefaultToolkit().getImage(url);


to load an image.

I've opened the JAR using winzip and, for some reason, the JAR hasn't preserved my file structure. So, when I try to look for an image as follows:

1  
2  
URL url = getClass().getResource("images/file1.png");
Image img= Toolkit.getDefaultToolkit().getImage(url);


The folder doesn't exist and so it can't find the image.

Can someone tell me how to keep my file structure when I create the JAR or an alternative way to find the images within the JAR file.


Thanks Wink


5  Game Development / Newbie & Debugging Questions / Re: How to close a window without shutting down the application? on: 2006-08-11 12:45:40
That's excellent. Thanks guys Wink
6  Game Development / Newbie & Debugging Questions / How to close a window without shutting down the application? on: 2006-08-11 09:08:15
Hi,

I'm writing a program that needs multiple windows presenting information but want the user to be able to click the X and have just that window close and not the entire running program. Also, if the user clicks on a JButton like submit, then that window will close leaving the other windows open. Can someone tell me how do do this please Smiley

Thanks,

Nick
7  Java Game APIs & Engines / Java 2D / Need help with Flickering Images on: 2006-07-17 09:40:11
hi,

I'm writing an application that needs to display images and I'm having some problems with my images flickering. The application is a kind of e-learning tool and will have questions and answers (both represented by images). The user will be required to drag the appropriate answer image to the corresponding question.

The questions and answers are stored in 2 seperate array Lists. I have a method which runs through the arrayLists and draws each question/answer. I also have a clear screen method which just paints a background coloured rectangle over the Canvas to clear the screen. This method is called only when and image is being moved and is determined by a boolean called screenRefresh.

The 2 paint methods are called from within a thread and for some reason, when the paintQuestions and clearScreen methods are called there is some flickering in the images and I just can't seem to fix it.

Here's my code. Maybe someone will be able to help


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  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
package pictureMatch;



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

public class PictureMatch extends Canvas implements MouseListener, MouseMotionListener{
   
   
    private BufferStrategy buffer;
    private int frameWidth, frameHeight;
    private int lastx, lasty, currentx, currenty;   
    private ArrayList<Question> questionList = new ArrayList();   
    private ArrayList<Question> answerList = new ArrayList();
    private ArrayList<Question> selectedQuestionList = new ArrayList();   
    private ArrayList<Question> selectedAnswerList = new ArrayList();
    private JPanel panel;
    private ImageHandler imageHandler;
    private String[] images = new String[20];
    private UpdateThread thread;
    private boolean screenRefresh = true;
   
   
    /** Creates a new instance of PictureMatch */
    public PictureMatch()
    {
        super();
       
        this.frameWidth = this.getWidth();
        this.frameHeight = this.getHeight();
       
        initialise();     
               
        addMouseListener(this);
        addMouseMotionListener(this);
        setFocusable(true);       
       
        this.createBufferStrategy(2);
        buffer = getBufferStrategy(); 
       
        thread = new UpdateThread(); 
       
    }
   
    public void initialise()
    {
        imageHandler = new ImageHandler(this);   
        loadImages();       
       
        createQuestions();
        createAnswers(); 
        selectQuestions();
       
       
        JFrame window = new JFrame("Differentiation Test");
        panel = (JPanel)window.getContentPane();
        setBounds(0, 0, 850, 550);
        panel.setLayout(new BorderLayout());
       
       
        panel.add(this);
        window.setBounds(0, 0, 850, 550);
        window.setVisible(true); 
        window.setResizable(false);
       
        window.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });
    }
   
   
    public void loadImages()
    {
       
        images[0]="diffPics/q0.png";
        images[1]="diffPics/q1.png";
        images[2]="diffPics/q2.png";
        images[3]="diffPics/q3.png";
        images[4]="diffPics/q4.png";
        images[5]="diffPics/q5.png";
        images[6]="diffPics/q6.png";
        images[7]="diffPics/q7.png";
        images[8]="diffPics/q8.png";
        images[9]="diffPics/q9.png";
        images[10]="diffPics/a0.png";
        images[11]="diffPics/a1.png";
        images[12]="diffPics/a2.png";
        images[13]="diffPics/a3.png";
        images[14]="diffPics/a4.png";
        images[15]="diffPics/a5.png";
        images[16]="diffPics/a6.png";
        images[17]="diffPics/a7.png";
        images[18]="diffPics/a8.png";
        images[19]="diffPics/a9.png";
                   
        imageHandler.images(images);
       
    }
   
    //--------------------create questions------------------
   
    public void createQuestions()
    {               
        for(int i = 0; i<(int)images.length/2; i++)
        {
            Question question = new Question(imageHandler.getImages(i),0,0,false,0);
            questionList.add(question);
        }
    }
   
    public void createAnswers()
    {       
        for(int i = (int)images.length/2; i<images.length; i++)
        {
            Question answer = new Question(imageHandler.getImages(i),0,0,true,0);
            answerList.add(answer);
        }
    }
   
    public void selectQuestions()
    {
        Random random = new Random();
       
        for(int i=0;i<5;i++)
        {
            int ran = random.nextInt(questionList.size());
           
            //select random question from array list
            Question selectedQuestion = questionList.get(ran);
            selectedQuestion.setY(85*i+100);
            selectedQuestionList.add(selectedQuestion);
            questionList.remove(ran);
           
            Question selectedAnswer = answerList.get(ran);
            selectedAnswer.setX(600);
            selectedAnswer.setY(400 - 75*i);
            selectedAnswerList.add(selectedAnswer);
            answerList.remove(ran);             
        }
       
       
    }
   
   
    //--------------------paint methods-----------------------
   
    public void clearScreen()
    {       
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
        try {   
                Rectangle2D clear = new Rectangle2D.Double(0,0,this.getWidth(), this.getHeight());
                g.setColor(this.getBackground());
                g.fill(clear);
           
            }
        finally
        {
            g.dispose();
        }
        buffer.show();       
    }
   
   
    public void paintQuestions()
    {
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
       
        try{
            for(int i = 0; i<selectedQuestionList.size(); i++)
            {
                selectedQuestionList.get(i).draw(g);
           
            }
       
            for(int i = 0; i<selectedAnswerList.size(); i++)
            {
                selectedAnswerList.get(i).draw(g);     
                System.out.println(selectedAnswerList.get(i).getHeight());
            }
        }
        finally
        {
            g.dispose();
           
        }
       
        buffer.show();
    }
   
       
    //-----------------------Mouse Listener and motion Methods------------
   
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}   
    public void mousePressed(MouseEvent e) {}     
    public void mouseReleased(MouseEvent e){screenRefresh = false;} 
   
    public void mouseMoved(MouseEvent e){}
    public void mouseDragged(MouseEvent e)
    {
        int xPos = e.getX();
        int yPos = e.getY();
       
        for(int i = 0; i<answerList.size(); i++)
        {                       
            if(selectedAnswerList.get(i).bounds().contains(xPos, yPos)
               && selectedAnswerList.get(i).isMoveable())
            {               
                selectedAnswerList.get(i).setX(xPos - 0.5*selectedAnswerList.get(i).getWidth());
                selectedAnswerList.get(i).setY(yPos - 0.5*selectedAnswerList.get(i).getHeight());               
            }
        }     
        screenRefresh = true;
    }

   
   
    //-------------------thread----------------------------------
   
    class UpdateThread extends Thread
    {
       
        public void run()
        {
            while(true)
            {   
                if(screenRefresh)
                {
                    clearScreen();
                    paintQuestions();
                }           
               
                try
                {
                    sleep(50);
                }
                catch(InterruptedException e){}
            }
           
           
        }
    }
   
     public void run()
    {
        PictureMatch pm = new PictureMatch();
        pm.thread.start();
    }
   
    public static void main(String[] args)
    {
        PictureMatch pm = new PictureMatch();
        //pm.run();
        pm.thread.start();
    }
       
}


Thanks
8  Game Development / Newbie & Debugging Questions / Re: Help loading images in an Applet on: 2006-06-19 12:25:31
if the file is in the applets jar (presuming you have jarred up your applet?), you should use this.getClass().getResource[asStream](...)

I dont have too much experience working with Jar files. Am I right in thinking that the .jar file will contain .class files and not .java files? If so, how can I modify the applet after the Jar has been created? Also, do I store the images in the Jar file?

cheers
9  Game Development / Newbie & Debugging Questions / Help loading images in an Applet on: 2006-06-19 10:57:19
hi,

I'm writing a simple applet (JApplet actualy) that needs to display images but I'm finding it very difficult.

My code is as follows:

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  
import java.awt.*;  
import javax.swing.*;
import java.applet.*;
import javax.imageio.*;
import java.io.*;
/**
 *
 * @author Nick
 */

public class TestJApplet extends JApplet {
   
    /** Creates a new instance of TestJApplet */
    public TestJApplet() {
    }
   
    public void init()
    {
       
    }
   
    public void paint(Graphics g)
    {
        Image image = null;
       
        try
        {
                       
            InputStream is = new BufferedInputStream(new FileInputStream("a.gif"));
            image = ImageIO.read(is);
        }
        catch(Exception e)
        {
            System.out.println("Exception : " + e);
        }
         
       
        g.drawImage(image, 100,100,this);
        g.drawRect(30,30,30,30);
    }
       
   
}


and get the exception :

1  
java.security.AccessControlException: access denied (java.io.FilePermission a.gif read)


I've also tried:

1  
2  
File file = new File("a.gif");
image = ImageIO.read(file);


and

1  
image = getImage(getDocumentBase(), "a.gif");


and get the same access denied message.

Is there a simple way to get an image to load in an Applet (or JApplet)

Thanks in advance Wink
10  Game Development / Newbie & Debugging Questions / Re: help with mediatracker & loading images on: 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
11  Game Development / Newbie & Debugging Questions / help with mediatracker & loading images on: 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
12  Game Development / Newbie & Debugging Questions / Re: Help with Buffered Images on: 2006-04-12 14:05:33
I can't get my ImageHandler class working and need some help.

First of all, here are my 4 classes:

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  
package InvadersGame;

import java.awt.image.BufferedImage;
import java.io.PrintStream;
import java.util.HashMap;
import javax.imageio.ImageIO;

public class ImageHandler
{   
    private HashMap images;
   
   
    public ImageHandler()
    {
        images = new HashMap();
    }

    public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);
            System.out.println(url); //to check whether the image was found
            return ImageIO.read(url);           
        }
        catch(Exception e)
        {
            System.exit(0);
            System.out.println("image not found");
            return null;
        }
    }     
   
     public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
        if(image == null)
        {
            System.out.println("image null");         
        }
        else System.out.println("not null");
       
        return image;
    }
     
     
    public HashMap getImages()
    {
        return images;
    }

    public void setImages(HashMap val)
    {
        images = val;
    }

}


and....

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  
package InvadersGame;

import java.awt.Graphics;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;

public class GameEntities {
   
    protected double x, y;
    protected int width, height;
    protected String imageName;
    protected boolean deletionMark = false;
    protected SpaceInvaders invaders;
    protected ImageHandler imageHandler;
           
   
   
    public GameEntities(SpaceInvaders invaders)
    {
        this.invaders = invaders;
        imageHandler = invaders.getImageHandler();
       
    }   

    public void setX(int x)
    {
        this.x = x;
    }
   
    public void setY(int y)
    {
        this.y = y;
    }
   
   public String getImageName()
    {
        return imageName;
    }

    public void setImageName(String name)
    {
        imageName = name;
        BufferedImage image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
         
    }
   
    public SpaceInvaders getGame()
    {
        return invaders;
    }
       
    public boolean collidesWith(GameEntities other)
    {       
        Rectangle thisEntity = new Rectangle();
        Rectangle otherEntity = new Rectangle();       
       
        thisEntity.setBounds((int)this.getX(), (int)this.getY(), this.getWidth(), this.getHeight());
        otherEntity.setBounds((int)other.getX(),(int)other.getY(), other.getWidth(), other.getHeight());
       
        return thisEntity.intersects(otherEntity);
    }
   
    public void move(){}
   
    public void paint(Graphics2D g)
    {
         g.drawImage(imageHandler.getImage(imageName), (int)x, (int)y, invaders);
    }
   
}



and....



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  
package InvadersGame;

import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.Graphics2D;
import java.lang.Math;
import java.util.Random;



public class AlienEntity extends GameEntities {
   
    //double x, y;
    int alienType;
    int speedx = 2;
    int speedy = 2;
    int firingFrequency;
   
   
   
    public AlienEntity(SpaceInvaders invaders)
    {
        super(invaders); 
        //setImageName("alien4.gif");
    }   
       
    public void move()
    {
        y = y + speedy;   
       
    }
   
    public void paint(Graphics2D g)
    {
       
        this.setImageName("alien4.gif");       
    }
              
   
}


and finally...

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  
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{
   
    JPanel panel;
    //AlienEntity al, al2;
    Graphics2D g2;
    boolean gameRunning = true;
    ArrayList<GameEntities> entitiesList;
    AnimationThread thread;
    private BufferStrategy buffer;
    ImageHandler imageHandler;
   
    class AnimationThread extends Thread
    {
        public void run()
        {
            while(true)
            {
                paintAlien();
                moveAlien();
                try
                {
                    sleep(50);
                }
                catch(InterruptedException e){}
            }
        }
    }
   
    public SpaceInvaders()
    {
        super();
       
        imageHandler = new ImageHandler();
               
        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<10; i++)
        {
            AlienEntity alien = new AlienEntity(this);
            alien.setX(60*i);
           
            entitiesList.add(alien);
        }
    }
       
    public void paintAlien()
    {
        Graphics2D g = (Graphics2D)buffer.getDrawGraphics();
        g.setColor(Color.black);
        g.fillRect(0, 0, getWidth(), getHeight());
       
                       
        for(int i=0; i<10; i++)
        {
            entitiesList.get(i).paint(g);
        }
       
        buffer.show();
    }
   
    public void moveAlien()
    {
         for(int i=0; i<10; i++)
        {
            entitiesList.get(i).move();
            System.out.println(entitiesList.get(i).getY());
        }
    }
   
   
    public void setBufferstrategy(BufferStrategy buffer)
    {
        buffer = buffer;
    }
   
    public ImageHandler getImageHandler()
    {
        return imageHandler;
    }

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




What happens is in the AlienEntity paint() method I set the image name as alien4.gif:

1  
2  
3  
4  
public void paint(Graphics2D g)
    {               
        this.setImageName("alien4.gif");       
    }


which calls the setImageName() method in the GameEntities class:

1  
2  
3  
4  
5  
6  
7  
8  
public void setImageName(String name)
    {
        imageName = name;
        BufferedImage image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();         
    }
   


What this does is call the getImage(String name) method in the image handler class which should load the appropriate image:

 
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
        if(image == null)
        {
            System.out.println("image null");          
        }
        else System.out.println("not null");
       
        return image;
    }



I've tried running the spaceInvaders class and get a null pointer exception. I put a print line in the image loader method (in ImageHandler) which says that url = null:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);

            System.out.println(url); //to check whether the image was found......returns null

            return ImageIO.read(url);           
        }
        catch(Exception e)
        {
            System.exit(0);
            System.out.println("image not found");
            return null;
        }   
    }


I assume the whole problem lies in the fact that it's not finding my image and so can't load it. I've put the image in the same folder and from within netbeans set the working directory to this folder in a hope that it would find and load the image.

Can someone PLEASE check my code to see if there's any fundamental problem and let me know how to fix this bug.

Cheers Smiley
13  Game Development / Newbie & Debugging Questions / Re: Help with Buffered Images on: 2006-04-12 10:34:49
how about sharing with us then? Somebody might need it.

The problem was with this method:

1  
2  
3  
4  
5  
6  
7  
public void setImageName(String name)
    {
        imageName = name;
        image = ImageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }


for some reason I put image = ImageHandler.getImage(imageName) when I should have created a new instance of ImageHander (my java lingo isn't too good, but I think that's the correct terminology). So it should have been something like:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
public class GameEntities {
   
    ........
    private ImageHandler imageHandler;

    ........
    .......

    public void setImageName(String name)
    {
        imageName = name;
        image = imageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }


I've now sorted that out and am having some other difficulties with the ImageHandler and Buffered images. I'm trying to sort it now but may need some help if I can't get it working.

 Smiley



14  Game Development / Newbie & Debugging Questions / Re: Help with Buffered Images on: 2006-04-11 14:11:34
Don't worry, I've sorted the problem now Smiley.
15  Game Development / Newbie & Debugging Questions / Help with Buffered Images on: 2006-04-11 12:33:15
Hi,

I have to make a space invaders game and am having some problems with using images for my gaming entities. I have a GameEntites class that will be extended by AlienEntity, shot and ship. I have a class called ImageHandler that will be used to represent the entites with images. I've never used BufferImage's before and can't get it running.

My ImageHandler class is as follows:


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  
import java.awt.image.BufferedImage;
import java.io.PrintStream;
import java.util.HashMap;
import javax.imageio.ImageIO;

public class ImageHandler
{   
    private HashMap images;
   
   
    public ImageHandler()
    {
        images = new HashMap();
    }

    public BufferedImage loadImage(String name)
    {
        try
        {
            java.net.URL url = null;
            url = getClass().getResource(name);
            return ImageIO.read(url);
        }
        catch(Exception e)
        {
            System.exit(0);
            return null;
        }
    }

    public BufferedImage getImage(String name)
    {
        BufferedImage image = (BufferedImage)images.get(name);
       
        return image;
    }

    public HashMap getImages()
    {
        return images;
    }

    public void setImages(HashMap val)
    {
        images = val;
    }

}


and my GameEntites class that will use the ImageHandler is as follows:

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  
package InvadersGame;

import java.awt.Graphics;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;



public abstract class GameEntities {
   
    private double x, y;
    private int width, height;
    private String imageName;
    private boolean deletionMark = false;
    private SpaceInvaders invaders;
    private BufferedImage image;
   
   
    public GameEntities(SpaceInvaders invaders)
    {
        this.invaders = invaders;
       
    }   
       
    public double getX()
    {
        return x;
    }
   
    public double getY()
    {
        return y;
    }
   
    public int getWidth()
    {
        return width;
    }
   
    public int getHeight()
    {
        return height;
    }
   
    public Rectangle getBounds()
    {
        return new Rectangle((int)x, (int)y, width, height);
    }
   
    public void setX(int x)
    {
        this.x = x;
    }
   
    public void setY(int y)
    {
        this.y = y;
    }
   
    public void setWidth(int width)
    {
        this.width = width;
    }
   
    public void setHeight(int height)
    {
        this.height = height;
    }
   
    public boolean deletionMarked()
    {
        return deletionMark;
    }
   
    public void setDeletionMarkedTrue(boolean value)
    {
        deletionMark = value;
    }
   
   public String getImageName()
    {
        return imageName;
    }

    public void setImageName(String name)
    {
        imageName = name;
        image = ImageHandler.getImage(imageName);
        height = image.getHeight();
        width = image.getWidth();
    }
       
    public boolean collidesWith(GameEntities other)
    {       
        Rectangle thisEntity = new Rectangle();
        Rectangle otherEntity = new Rectangle();       
       
        thisEntity.setBounds((int)this.getX(), (int)this.getY(), this.getWidth(), this.getHeight());
        otherEntity.setBounds((int)other.getX(),(int)other.getY(), other.getWidth(), other.getHeight());
       
        return thisEntity.intersects(otherEntity);
    }
   
    public abstract void move();
   
    public abstract void paint(Graphics g);   
   
}



The ImageHandler class compiles fine but when I compile the GameEntites class the setImageName method causes an error and I get the following error:

1  
2  
3  
4  
5  
6  
7  
8  
Compiling 1 source file to C:\Documents and Settings\Nick\SpaceInvaders\build\classes
C:\Documents and Settings\Nick\SpaceInvaders\src\InvadersGame\GameEntities.java:89: cannot access InvadersGame.ImageHandler
bad class file: C:\Documents and Settings\Nick\SpaceInvaders\src\InvadersGame\ImageHandler.java
file does not contain class InvadersGame.ImageHandler
Please remove or make sure it appears in the correct subdirectory of the classpath.
        image = ImageHandler.getImage(imageName);
1 error
BUILD FAILED (total time: 2 seconds)


Can someone PLEASE explain what's going wrong and how I can sort the problem.

Any help would really be appreciated,

Cheers Wink
16  Java Game APIs & Engines / Java 2D / Side scroller help on: 2006-03-17 10:05:19
Hi,

I know you've probably seen this a million times before but a little help would be appreciated.

I have to make  a game for a mini-project and would like to make a 2d side scroller (either platform or shooter).

I'm having problem getting my head around how to make the background and enemies to move from right to left. Can someone point me to a good step-by-step tutorial or post some simple code so I can get an idea of what's needed. Also, I've looked on amazon.co.uk for a good java gaming book but I'm not sure which is best. Can anyone recommend one.

Cheers Wink
Pages: [1]
 

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

The first screenshot will be displayed as a thumbnail.

trollwarrior1 (34 views)
2014-11-22 12:13:56

xFryIx (73 views)
2014-11-13 12:34:49

digdugdiggy (52 views)
2014-11-12 21:11:50

digdugdiggy (46 views)
2014-11-12 21:10:15

digdugdiggy (40 views)
2014-11-12 21:09:33

kovacsa (66 views)
2014-11-07 19:57:14

TehJavaDev (70 views)
2014-11-03 22:04:50

BurntPizza (68 views)
2014-11-03 18:54:52

moogie (83 views)
2014-11-03 06:22:04

CopyableCougar4 (82 views)
2014-11-01 23:36:41
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

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
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!