0
我試圖使用BufferedImage
在run()
方法中對緩衝區進行雙緩衝。它不顯示圖像(雖然它顯示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();
}
}
}