我正在学习 Java,我尝试构建一个应用程序,当我单击面板时,该应用程序会掉落一个球。问题是,当绘制椭圆形时,它的移动速度非常快,即使将 Thread.sleep 设置为最大值也只会使其几乎无法被注意到。我怎样才能减慢速度?
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.red);
g2.drawOval(x,y,20,20);
Thread thread = new Thread() {
public void run() {
while (true) {
y = y + 1;
repaint();
try {
Thread.sleep(2147483647);
}
catch (InterruptedException ex) {
}
}
}
};
thread.start();
}
最佳答案
我没有在自己的环境中尝试过你的程序,但据我所知,移动你的球的似乎是:
y = y + 1;
行,因此您可能可以考虑将其更改为较小的数字,很可能是 double 。另外,正如已经提到的,也许您可以尝试不使用:
while (true)
声明,因为这将永远评估为真,这不是最大的问题,但也许您可以考虑使用其他东西,例如使用与 y
有关的东西变量如:while (y < 768 )
甚至是类似 for 循环的东西,具体取决于你正在做什么。
希望这对您有所帮助,我还建议您看看这里的答案: Java Graphics Updating Too Fast
祝你一切顺利!
关于java - 为什么这个椭圆移动得这么快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450707/