我想知道是否有一个像Processingvoid draw()
编程语言使用的函数,它在每一帧都被调用。或者甚至只是一个函数,它在被调用时无限循环,但每次有新帧时才会运行它。我听说在java中称为runnable的东西我该如何使用它?还有一种更好的方法,然后有一个具有延迟的可运行对象,例如硬编码以运行每一帧的函数。哦,还有什么函数调用可以让我看到自从应用程序开始运行以来有多少时间(最好是毫秒)在每台计算机上,无论帧速率如何。
问问题
2801 次
1 回答
1
也许你需要这样的东西
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class Repainter extends JPanel {
private Point topLeft;
private int increamentX = 5;
public Repainter() {
topLeft = new Point(100, 100);
}
public void move() {
topLeft.x += increamentX;
if (topLeft.x >= 200 || topLeft.x <= 100) {
increamentX = -increamentX;
}
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(topLeft.x, topLeft.y, 100, 100);
}
public void startAnimation() {
SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
while (true) {
move();
Thread.sleep(100);
}
}
};
sw.execute();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Repaint Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
Repainter repainter = new Repainter();
frame.add(repainter);
repainter.startAnimation();
frame.setVisible(true);
}
});
}
}
于 2012-07-16T10:57:53.887 回答