我有一个问题..我的java applet上画了一个图像和一个for循环使x每次向上移动5 ..但它留下了旧图像一点然后它将擦除它..
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;
}
}
}
见图像:
答案 0 :(得分:3)
您无法通过paintComponent()
或paint()
方法循环播放动画。这些方法要求您在特定的时间点绘制自己(即当前帧)。
相反,你需要将你的精灵“移动”的逻辑与“渲染”你的精灵分开。寻找像这样的东西
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();
答案 1 :(得分:0)
试试这个:
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
}
}
答案 2 :(得分:0)
你需要告诉java重绘框架。'
只需在repaint()
上使用JComponent
图片所在的for循环结尾处。像这样:
for(int tohouse = 0; tohouse <= 520; tohouse+=2) {
try {
//Process the changes
}
component.repaint(); // where component is what the image is added to.
}