每帧调用的Java函数

时间:2012-07-16 04:01:38

标签: java time frame processing runnable

我想知道是否有void draw()这样的函数,Processing编程语言使用每个帧调用的函数。或者甚至只是一个函数在被调用时无限循环,但只有在每次有新帧时才会遍历它。我在java中听说过一个叫做runnable的东西我该如何使用它呢?还有一个更好的方法,然后像一个硬编码运行每一帧的功能延迟运行。哦,还有什么是函数调用,这将允许我看到自应用程序开始运行以来有多少时间(以毫秒为单位)我可以使我的runnables / frame调用更加精确,以便游戏以相同的速度运行无论帧速率如何,都在每台计算机上。

1 个答案:

答案 0 :(得分: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);
            }
        });
    }
}