Reputation: 31
I have a problem.. I have a image painted on my java applet and a for loop to make the x move up 5 every time.. but it leaves behind the old image for a bit then it will erase it..
for(int tohouse = 0; tohouse <= 520; tohouse+=2) {
try {
x+=5;
tohouse+=10;
if (pos == 0) {
rectX+=5;
g.drawImage(picture1,x,150,this);
pos = 1;
} else if (pos == 1) {
rectX+=4;
g.drawImage(picture2,x,150,this);
pos = 2;
} else if (pos == 2) {
rectX+=5;
g.drawImage(picture3,x,150,this);
pos = 0;
}
}
}
Heres a image:
Upvotes: 3
Views: 117
Reputation: 81154
You can't do animation by looping in your paintComponent()
or paint()
method. Those methods are asking you to paint yourself at a specific point in time (i.e. the current frame).
Instead, you need to decouple the logic of "moving" your sprite from "rendering" your sprite. Look for something like this
private int x;
protected void paintComponent(Graphics g) {
//draw the images at location x
}
// elsewhere, initialize a javax.swing.Timer to increment x every 15 ms
new Timer(15, new ActionListener() {
public void actionPerformed(ActionEvent e) {
x += 5;
repaint();
}
}.start();
Upvotes: 3
Reputation: 12623
You need to tell java to repaint the frame.'
Just use repaint()
on your JComponent
that the image is in at the end of the for loop. Like this:
for(int tohouse = 0; tohouse <= 520; tohouse+=2) {
try {
//Process the changes
}
component.repaint(); // where component is what the image is added to.
}
Upvotes: 0
Reputation: 595
try this:
for(int tohouse = 0; tohouse <= 520; tohouse+=2)
{
try
{
switch(pos){
case 0:
rectX+=5;
g.drawImage(picture1,x,150,this);
pos = 1;
break;
case 1:
rectX+=4;
g.drawImage(picture2,x,150,this);
pos = 2;
break;
case 2:
rectX+=5;
g.drawImage(picture3,x,150,this);
pos = 0;
break;
default: // add some default behavior here
break;
}
} catch(Exception e){
// do something
}
}
Upvotes: 0