This is the first time I am using threads. In my code below, i’ve tried to use threads with double buffering, and although the code compiles, I see nothing on the screen, can you please help me.
Thanx
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Game extends JPanel implements ActionListener, Runnable
{
int X = 40,Y = 40;
private ImageIcon images[];
private static final int TOTAL_IMAGES=7;
private int currentImage = 0;
boolean running = true;
public static Image offscreen;
public Game()
{
setVisible(true);
setupAnimation();
setIgnoreRepaint(true);
}
public void setupAnimation()
{
this.setSize(this.getPreferredSize());
this.images = new ImageIcon[TOTAL_IMAGES];
for (int i = 0; i < images.length; i++)
{
images[i] = new ImageIcon("pac"+i+".gif");
}
}
public void run()
{
offscreen= createImage(400,400);
Graphics buff = offscreen.getGraphics();
buff.setColor(Color.black);
buff.fillRect(0,0,400,400);
try
{
while (running)
{
buff.drawImage(images[currentImage].getImage(), X, Y, this);
images[currentImage].paintIcon(this, buff, X, Y);
currentImage = (++currentImage) % TOTAL_IMAGES;
paint(buff);
Thread.sleep(30);
}
}
catch (Exception e) {}
}
public void paint(Graphics g)
{
if (offscreen != null)
{
g.drawImage(offscreen, 0, 0, this);
}
}
public void actionPerformed(ActionEvent e){ repaint(); }
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getPreferredSize (){return new Dimension(400,400);}
public static void main(String agrs[])
{
Game ji = new Game();
JFrame main = new JFrame("PacMan");
main.getContentPane().add(ji, BorderLayout.CENTER);
main.pack();
main.show();
Thread t = new Thread(ji);
t.start();
}
}