【发布时间】:2023-04-06 12:42:01
【问题描述】:
我正在尝试使用BufferedImage 在run() 方法中双重缓冲我的屏幕。它不显示图像(尽管它确实显示了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();
}
}
}
【问题讨论】:
标签: java swing graphics bufferedimage