I was asked by uni to create a 2d racing game in java. we were told to use one jcomponent in a jframe. we told to update the game by the swing timer and call repaint() somewhere appropriate in their.
I have now finished but all the way through my use of Graphics g was annoying me. for example below is my gameobject class that players and stuff derive from.
import java.awt.Component;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/*
* Provides The basic functionality of Displaying a game object on the screen
* and methods able to change the image
*/
public class GameObject {
public Vector position = new Vector();
//image set up variables
protected BufferedImage[] buffImage;
protected ImageIcon icon = new ImageIcon();
protected int numberOfImages;
protected String filePrefix;
protected String fileExt;
//////////////interactive variables
//image
protected int imageNumber = 0;
public GameObject(int numOfImages, String filePre, String fileE)
{
//if this gives grief about constructors implement a custom initObject() method that can be overridden with super.
this.numberOfImages = numOfImages;
buffImage = new BufferedImage[numOfImages];
filePrefix = filePre;
fileExt = fileE;
}
//Adds images to array
protected void initImageArray()
{
for(int i = 0; i <numberOfImages; i++)
{
try{
buffImage[i] = (BufferedImage) ImageIO.read(new File(filePrefix + "/" + Integer.toString(i) + fileExt));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//Draws object to screen
public void draw(Graphics g, Component c){
icon.setImage(getNextImage());
icon.paintIcon(c, g, position.x, position.y);
}
//returns current image
protected BufferedImage getNextImage(){
return buffImage[imageNumber];
}
//
protected void increaseImageNumber(){
if(imageNumber < numberOfImages-1){
imageNumber++;
}
else{
imageNumber = 0;
}
}
protected void decreaseimageNumber(){
if(imageNumber > 0){
imageNumber--;
}else{
imageNumber = numberOfImages - 1;
}
}
}
The bit specifically i don't think im doing right is passing the same "Graphics g" parameter to every objects draw method. it works but when i tried to place 15 stars in the back ground and change their imageIcon image from one buffered image array to the next everything became very jarred. I put this down to sharing this one graphic class. It could also just be that we were told not to use a threaded solution but i think any new comp should be able to handle 17 images updating and changing. the update timer is at every 33 milliseconds.
Thank you to anyone who can help explain to me the best way to achieve what i was after or the proper use/sharing of the graphics object.