Java图像绘制问题
我有个问题。。我在java小程序上绘制了一个图像,并使用for循环使x每次向上移动5。。但它会留下旧图像一段时间,然后会将其删除Java图像绘制问题,java,Java,我有个问题。。我在java小程序上绘制了一个图像,并使用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;
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;
}
}
}
for(int-tohouse=0;tohouse尝试以下方法:
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
}
}
for(int-tohouse=0;tohouse您需要告诉java重新绘制框架。”
只需对图像位于for循环末尾的JComponent
组件使用repaint()
。如下所示:
for(int tohouse = 0; tohouse <= 520; tohouse+=2) {
try {
//Process the changes
}
component.repaint(); // where component is what the image is added to.
}
for(int-tohouse=0;tohouse您不能通过循环使用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();
这是我的计算机sci AP课程的一个项目。我要把它改成switch语句。你需要停下来,掌握图形游戏的基本结构。你需要学习的第一课绝对是渲染图形改变游戏状态应该是独立的操作,无论是在时间上还是在代码放置的位置上。在绘制方法中加入for循环无法制作动画。请注意,这不是游戏。我们必须用动画制作图形项目。@Henry:原则仍然适用。请参阅我提供的链接“基本动画”的第4节。(事实上,这可能不是一个很好的资源,因为它似乎并不专注于Java。作为Swing的起点,您可能会从中受益)这不会起作用,因为逻辑在他的paint方法中。他从未说过它在paint()
方法中。在这一点上,这确实没有办法起作用。甚至在paint()中
,重新绘制父组件仍然可以正常工作(通常)。不,不会。在paint()
内部,您位于事件调度线程上的事件内,因此所有repaint()
调用都将排队,并且只有在方法完成运行后才会处理。