【发布时间】:2015-02-25 05:16:58
【问题描述】:
我有一个简单的 Java/Swing 应用程序,它试图通过从左到右移动一个盒子来制作动画:
public class TestFrame extends JFrame {
protected long startTime = new Date().getTime();
public class MainPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
// calculate elapsed time
long currentTime = new Date().getTime();
long timeDiff = currentTime - TestFrame.this.startTime;
// animation time dependent
g.fillRect((int) (timeDiff / 100), 10, 10, 10);
}
}
public class MainLoop implements Runnable {
@Override
public void run() {
while (true) {
// trigger repaint
TestFrame.this.repaint();
}
}
}
public static void main(String[] args) {
new TestFrame();
}
public TestFrame() {
// init window
this.setTitle("Test");
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new MainPanel());
this.setVisible(true);
// start render loop
Thread loop = new Thread(new MainLoop());
loop.start();
}
}
问题是动画不干净,框跳(有时)几个像素。我已经做了一些研究,根据他们的说法,如果使用paintComponent(而不是paint)并进行基于时间的动画(不是基于帧),它应该可以正常工作。我都做了,但动画仍然不干净。
谁能给我提示一下出了什么问题?
【问题讨论】:
-
所以,不知道你想走多远,但是当我学习为动画制作游戏循环时,本教程非常简洁:java-gaming.org/index.php?topic=24220.0
-
@Araymer:看起来很有趣。我去看看:)