2014-04-03 66 views
0

我試圖使用BufferedImagerun()方法中對緩衝區進行雙緩衝。它不顯示圖像(雖然它顯示g.drawRect等完成的其他圖形繪畫)。 我想實現主動渲染,所以我的繪畫不在paintComponent,但在我自己的方法。當我把它放在paintComponent它確實工作.... 任何人都知道什麼似乎是問題?使用BufferedImage的雙緩衝Java不使用顯示圖像

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.Toolkit; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import javax.swing.JPanel; 


public class GamePanel extends JPanel implements Runnable 
{ 
private static final int PWIDTH = 500, PHEIGHT = 500, PERIOD = 40; 
private Image bgImage; 
private BufferedImage dbImg = null; 
private boolean running; 

public GamePanel() 
{ 
    bgImage = Toolkit.getDefaultToolkit().getImage((new File(".")).getAbsolutePath() + "//a.jpg"); 

} 

public void run() 
{ 

    long before, diff, sleepTime; 
    before = System.currentTimeMillis(); 
    running = true; 
    int x = 1; 
    while(x <= 5) 
    { 
     gameRender(); 
     paintScreen(); // active rendering 

     try { 
      Thread.sleep(50); 
     } 
     catch(InterruptedException e){} 

     x++; 
    } 

} 

// only start the animation once the JPanel has been added to the JFrame 
public void addNotify() 
{ 
    super.addNotify(); // creates the peer 
    startGame(); // start the thread 
} 
public void startGame() 
{ 
    (new Thread(this)).start(); 
} 
public void gameRender() 
{ 
    Graphics dbg; 

    dbImg = new BufferedImage(PWIDTH, PHEIGHT, BufferedImage.TYPE_INT_ARGB); 
    // dbImg = (BufferedImage)createImage(PWIDTH, PHEIGHT); 
    dbg = dbImg.getGraphics(); 
    dbg.setColor(Color.GREEN); 
    dbg.fillRect(0, 0, PWIDTH, PHEIGHT); 
    dbg.drawImage(bgImage, 0, 0, null); // doesn't show 

    dbg.setColor(Color.ORANGE); // this one shows 
    dbg.fillRect(100, 100, 100, 100); 

} 
public void paintScreen() 
{ 
    Graphics g; 
    try { 
     g = getGraphics(); 
     if(g != null && dbImg != null) 
     { 
      g.drawImage(dbImg, 0, 0, null); 
     } 
    } 
    catch(Exception e) 
    { 
     System.out.println("Graphics error"); 
     e.printStackTrace(); 
    } 
} 

}

回答

3

getGraphics是風俗畫是不是怎麼做,看Performing a Custom Painting更多細節

你應該考慮有主動和被動緩衝。活動緩衝區是應該塗在屏幕上的內容,被動緩衝區應該是已更新的內容。這將確保您不會收到髒更新,即將緩衝區的部分更新顯示在屏幕上。

更新完成後,您將交換緩衝區並請求重新繪製。爲了使它更安全,交換緩衝區和繪畫時,應做是​​塊

內說了這麼多,Swing組件都是雙默認

緩衝