a question on making a pic move in a applet?
i have tried to create a movement of a player in applet.
i modify my code that can run succeessfully in my previous work.
but the modified code din't work as what i expect.
it directly jump to the end, without the movement step.
here are the code i'm using, can someone help me for the problem?
public void run() {
repaint();
try {
if (isForward) {
for(int j=0; j<4; j++) {
repaint();
t.sleep(300);
playerInfo[0] += 10;
}
}
else if (isBackward){
playerInfo[1] -= 10;
}
} catch (InterruptedException err) {
JOptionPane.showMessageDialog(null, "Drawing error!");
}
}
[702 byte] By [
jiuhua] at [2007-11-27 11:17:57]

// <applet code="PicMoving" width="400" height="400"></applet>
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class PicMoving extends JApplet implements Runnable {
PicMovingPanel picPanel;
Thread thread;
boolean animating = false;
long delay = 40;
public void init() {
BufferedImage image = makeImage();
picPanel = new PicMovingPanel(image);
getContentPane().add(picPanel);
}
public void start() {
if(!animating) {
animating = true;
thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
}
public void stop() {
animating = false;
if(thread != null)
thread.interrupt();
thread = null;
}
public void run() {
while(animating) {
try {
Thread.sleep(delay);
} catch(InterruptedException e) {
stop();
}
picPanel.goAhead();
}
}
private BufferedImage makeImage() {
int w = 40;
int h = 40;
int type = BufferedImage.TYPE_INT_RGB;
BufferedImage image = new BufferedImage(w, h, type);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setBackground(UIManager.getColor("Panel.background"));
g2.clearRect(0,0,w,h);
g2.setPaint(Color.red);
g2.fillOval(0,0,w-1,h-1);
g2.dispose();
return image;
}
}
class PicMovingPanel extends JPanel {
BufferedImage image;
Rectangle r;
int dx = 2;
int dy = 3;
public PicMovingPanel(BufferedImage image) {
this.image = image;
r = new Rectangle(image.getWidth(), image.getHeight());
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, r.x, r.y, this);
}
public Dimension getPreferredSize() {
return r.getSize();
}
public void goAhead() {
checkBoundries();
r.translate(dx, dy);
repaint();
}
private void checkBoundries() {
if(r.x + dx < 0 || r.x + r.width + dx > getWidth())
dx *= -1;
if(r.y + dy < 0 || r.y + r.height + dy > getHeight())
dy *= -1;
}
}