2012-01-29 187 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组件是双缓冲的。