【问题标题】:Java function that gets called every frame每帧调用的Java函数
【发布时间】:2012-07-16 04:01:37
【问题描述】:

我想知道是否有像void draw() 这样的函数,Processing 编程语言使用它在每一帧都被调用。或者甚至只是一个函数,它在被调用时无限循环,但每次有新帧时才会运行它。我听说在java中称为runnable的东西我该如何使用它?还有一种更好的方法,然后有一个具有延迟的可运行对象,例如硬编码以运行每一帧的函数。哦,还有什么函数调用可以让我看到自从应用程序开始运行以来有多少时间(最好是毫秒)在每台计算机上,无论帧速率如何。

【问题讨论】:

  • frame 到底是什么意思,你说的是图形窗口吗?
  • 我的意思是像 FPS 中的帧。就像每次屏幕刷新一样。大多数体面的显示器每秒 60 次。
  • 我猜你正在编写你的第一个游戏。我建议购买一本书或在线阅读一些关于 Java 游戏开发的教程。这应该会教给你你想知道的一切。
  • 我只是想知道为什么人们对我的问题投了反对票,有人能告诉我我做错了什么吗?
  • 这是因为无知的Java程序员不会费心研究Processing,即使你提供了它的链接。我投了赞成票。

标签: java time frame processing runnable


【解决方案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);
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多