【发布时间】:2017-08-12 18:40:17
【问题描述】:
我的方法是在循环中使用“reprint()”成功移动图像,这意味着在不重叠的情况下更新其位置,但现在我想看到图像移动,我使用了“thread.sleep()”来给出repaint()s 之间的时间间隔,但它似乎不起作用
import java.awt.*;
import javax.swing.*;
public class jp extends JPanel implements ActionListener{
Timer t;
JPanel jl=new JPanel();
int x,y;
jp(){
x=10;
//y=10;
t=new Timer(5,this);
t.start();
}
public void actionPerformed(ActionEvent e){
x++;
y++;
if(x>500){
x=0;
y=0;
}
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.black);
g.setColor(Color.blue);
g.fillRect(x,20,50,50);
}
}
public class Jpanel extends JFrame{
public static void main(String[] args) {
jp p=new jp();
JFrame j=new JFrame("TEST_CASE-1");
j.add(p);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(700,500);
j.setVisible(true);
}
}
【问题讨论】:
-
1)
for(int i=0;i<200;i++){ g.fillRect(25+i,25,50,50); }这不是制作动画的方式。 2) “我尝试使用 repaint(),但它似乎不起作用” 在上面看到的代码中没有调用 repaint。 3) 将这两个 cmets 绑定在一起,使用基于 Swing 的Timer来调整i的值,然后调用 repaint。 -
成功了。但是我怎么能看到图像在移动呢?我尝试使用'Thread.sleep',但它似乎不起作用。我在循环中使用了“repaint()”而不是使用计时器
-
1) 将当前尝试的minimal reproducible example 或Short, Self Contained, Correct Example 显示为问题的edit。 2) “尝试使用 'Thread.sleep',但它似乎不起作用” 这种方法不需要它(而且很可能会搞砸)。
-
完成。请立即检查。
-
你赢了,我用“Thread.sleep()”错了。使用“Swing Timer”后效果很好。感谢您的推动。