使用缓冲策略在Java中轻弹图像
我正在尝试使用缓冲策略和图形2D渲染图像。代码运行良好,但图像在闪烁。在我用Graphics2D测试它之前,我只试过用图形,画面闪烁得很疯狂。代码如下:使用缓冲策略在Java中轻弹图像,java,swing,timer,graphics2d,bufferstrategy,Java,Swing,Timer,Graphics2d,Bufferstrategy,我正在尝试使用缓冲策略和图形2D渲染图像。代码运行良好,但图像在闪烁。在我用Graphics2D测试它之前,我只试过用图形,画面闪烁得很疯狂。代码如下: public Main() { x = 0; Dimension size = new Dimension(sx, sy); setPreferredSize(size); frame = new JFrame(); ImageIcon player2 = new ImageIcon("res/g
public Main() {
x = 0;
Dimension size = new Dimension(sx, sy);
setPreferredSize(size);
frame = new JFrame();
ImageIcon player2 = new ImageIcon("res/gfx/char.png");
player = player2.getImage();
addKeyListener(new AL());
time = new Timer(5, this);
time.start();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
render();
update();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 800, 600);
g2d.drawImage(player, x, 350, null);
g.dispose();
bs.show();
}
(对不起,我的英语不好)我想你是直接在jframe上画的。尝试使用像JPanel这样的中间层容器组件,在其上绘制图像,并将面板添加到框架中。直接绘图会产生闪烁效果。如果我按照您的说法制作,我可以保持三重缓冲吗?目前还不清楚您是如何以及在何处渲染图像的。如果你正在做一些动画,也要尽量避免线程,试着使用javax.swing.Timer。正如你在代码中看到的,我正在使用javax.swing.Timer,但是thx用于回答!你需要三重缓冲吗?默认情况下,JPanel有一个双缓冲区。如果绝对需要的话,您可以使用JPanel制定一个非常混乱的缓冲策略。