Java中无响应的FPS计数器

时间:2015-10-04 14:19:07

标签: java frame-rate

这段代码应该在控制台上显示一个带绿屏和FPS计数器的应用程序,但它无效。

帮助?



package com.tutorial.main;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

public class Game extends Canvas implements Runnable {

  private static final long serialVersionUID = 7580815534084638412L;

  public static final int WIDTH = 640, HEIGHT = WIDTH / 12 * 9;

  private Thread thread;
  private boolean running = false;

  public Game() {
    new Window(WIDTH, HEIGHT, "Lets Build a Game!", this);
  }

  public synchronized void start() {
    thread = new Thread(this);
    thread.start();
  }

  public synchronized void stop() {
    try {
      thread.join();
      running = false;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void run() {
    long lastTime = System.nanoTime();
    double amountOfTicks = 60.0;
    double ns = 1000000000 / amountOfTicks;
    double delta = 0;
    long timer = System.currentTimeMillis();
    int frames = 0;
    while (running) {
      long now = System.nanoTime();
      delta += (now - lastTime) / ns;
      lastTime = now;
      while (delta >= 1) {
        tick();
        delta--;
      }
      if (running) {
        render();
        frames++;

        if (System.currentTimeMillis() - timer > 1000) {
          timer += 1000;
          System.out.println("FPS: " + frames);
          frames = 0;
        }
      }
      stop();
    }
  }

  private void tick() {

  }

  private void render() {
    BufferStrategy bs = this.getBufferStrategy();
    if (bs == null) {
      this.createBufferStrategy(3);
      return;
    }

    Graphics g = bs.getDrawGraphics();

    g.setColor(Color.green);
    g.fillRect(0, 0, WIDTH, HEIGHT);

    g.dispose();
    bs.show();
  }
  public static void main(String args[]) {
    new Game();
  }
}






package com.tutorial.main;

import java.awt.Canvas;
import javax.swing.*;
import java.awt.Dimension;

public class Window extends Canvas {

  private static final long serialVersionUID = -240840600533728354L;

  public Window(int width, int height, String title, Game game) {
    JFrame frame = new JFrame(title);

    frame.setPreferredSize(new Dimension(width, height));
    frame.setMinimumSize(new Dimension(width, height));
    frame.setMaximumSize(new Dimension(width, height));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.add(game);
    frame.setVisible(true);

  }

}




我似乎对window.java没有任何问题,但我把它放在那里以防万一。

最后它还会出现2个错误 "复制方法run()在Game,Line 34" "复制方法run()在Game,Line 61"。

请告诉我这里出了什么问题。我没有打印过它吗?

0 个答案:

没有答案
相关问题