2012-01-29 190 views
1

我正在使用設置爲60 fps的FPS上限。我測試過了,它正在工作。問題是它仍然會導致屏幕閃爍。我的顯示器設置爲60 fps。我不知道它是如何引起閃爍的。這裏是我的代碼:FPS Cap仍然會導致閃爍

package com.bgp.chucknorris; 

import java.applet.Applet; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.MediaTracker; 
import java.net.URL; 

public class ChuckNorrisApplet extends Applet implements Runnable { 
    private static final long serialVersionUID = 1L; 
    Thread thread = null; 
    Image title; 
    URL base; 
    MediaTracker mt; 
    String fps = ""; 

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

     mt = new MediaTracker(this); 
     base = getDocumentBase(); 
     title = getImage(base, "title.png"); 
     mt.addImage(title, 1); 
     try { 
      mt.waitForAll(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

    } 

    public void paint(Graphics g) { 
     g.drawImage(title, 0, 0, null); 
    } 

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

    public void stop() { 
     thread = null; 
    } 

    public void run() { 
     int frames = 0; 

     double unprocessedSeconds = 0; 
     long lastTime = System.nanoTime(); 
     double secondsPerTick = 1/60.0; 
     int tickCount = 0; 

     requestFocus(); 

     while (true) { 
      long now = System.nanoTime(); 
      long passedTime = now - lastTime; 
      lastTime = now; 
      if (passedTime < 0) 
       passedTime = 0; 
      if (passedTime > 100000000) 
       passedTime = 100000000; 

      unprocessedSeconds += passedTime/1000000000.0; 

      boolean ticked = false; 
      while (unprocessedSeconds > secondsPerTick) { 
       unprocessedSeconds -= secondsPerTick; 
       ticked = true; 

       tickCount++; 
       if (tickCount % 60 == 0) { 
        System.out.println(frames + " fps"); 
        fps = Integer.toString(frames); 
        lastTime += 1000; 
        frames = 0; 
       } 
      } 

      if (ticked) { 
       repaint(); 
       frames++; 
      } else { 
       try { 
        Thread.sleep(1); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 

     } 
    } 

} 
+0

1)爲什麼'Applet'(而不是'JApplet')? 2)爲什麼applet與框架相反? 3)當大多數組件實現一個時,不要在繪圖中使用'null'作爲'ImageObserver'。 – 2012-01-29 02:25:08

+0

哇。更改爲「JApplet」工作。 – Cg2916 2012-01-29 03:13:38

+0

現在應該進行其他更改,它是Swing。而不是'Thread' /'Runnable' /'sleep()',實現一個Swing'Timer'。將'paint()'移動到'JPanel'的'paintComponent()'中。使用'ImageIO'加載圖像並放下'MediaTracker' ..我添加了第一個建議作爲答案(與解釋)。 – 2012-01-29 03:31:18

回答

0

爲什麼一個Applet(而不是一個JApplet)?請注意,Swing組件是雙緩衝的。