Java中的双缓冲使用BufferedImage dosn&t显示图像

时间:2014-04-03 20:10:56

标签: java swing graphics bufferedimage

我尝试使用run()BufferedImage方法对我的屏幕进行双倍缓冲。它没有显示图像(虽然它确实显示了由g.drawRect等完成的其他图形绘画)。 我试图实现主动渲染,所以我的绘画不在paintComponent中,而是在我自己的方法中。当我把它放在paintComponent它确实有效.... 谁知道这似乎是什么问题?

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();
    }
}

}

1 个答案:

答案 0 :(得分:3)

getGraphics不是自定义绘画的完成方式,有关详细信息,请参阅Performing a Custom Painting

您应该考虑使用主动和被动缓冲区。活动缓冲区应该绘制到屏幕上,被动缓冲区应该是更新的内容。这样可以确保您不会得到脏更新,这是对屏幕上绘制的缓冲区的部分更新。

更新完成后,您将交换缓冲区并请求重新绘制。为了更安全,交换缓冲区并绘制时应该在synchronized块内

说了这么多,Swing组件默认是双缓冲的