图像在重绘时闪烁() [英] Image flickers on repaint()

查看:110
本文介绍了图像在重绘时闪烁()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了之前的问题的解决方案,这让我陷入了新的问题。

I figured out the solution for my previous question which landed me into new problem.

在下面的代码中,我使用箭头键在JFrame周围移动图像。但是每次按下箭头键,图像看起来都会闪烁,这在连续按下按键时非常明显。

In the following code im moving an image around a JFrame using arrow keys. but every time i press an arrow key the image seems to flicker which is quite noticeable when a key is pressed continuously.

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;


public class TestProgram extends JFrame implements KeyListener {
    private BufferedImage TestImage;
    private int cordX = 100;
    private int cordY = 100;

    public TestProgram() {
        setTitle("Testing....");
        setSize(500, 500);
        imageLoader();
        setVisible(true);
    }

    public void imageLoader() {
        try {
            String testPath = "test.png";
            TestImage = ImageIO.read(getClass().getResourceAsStream(testPath));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        addKeyListener(this);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawImage(TestImage, cordX, cordY, this);
    }

    public static void main(String[] args) {
        new TestProgram();
    }


    public void keyPressed(KeyEvent ke) {
        switch (ke.getKeyCode()) {
            case KeyEvent.VK_RIGHT: {
                cordX+=5;
            }
            break;
            case KeyEvent.VK_LEFT: {
                cordX-=5;
            }
            break;
            case KeyEvent.VK_DOWN: {
                cordY+=5;
            }
            break;
            case KeyEvent.VK_UP: {
                cordY-=3;
            }
            break;
        }
        repaint();
    }

    public void keyTyped(KeyEvent ke) {}

    public void keyReleased(KeyEvent ke) {}
}

有没有解决办法可以避免这种情况?

Is there any solution to avoid that?

编辑:上面是完整的工作代码。我发现很难在其中加入双缓冲器。任何人都可以帮助我吗?

above is the complete working code. I'm finding it difficult to incorporate doublebuffer in it. can anyone help me in that part?

推荐答案

你必须使用缓冲区摆脱闪烁。
对于图像,有BufferedImage缓冲区:

You have to use a Buffer to get rid of the flickering. For images, there is the BufferedImage Buffer:

BufferedImage bf = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);

然后您将图像绘制到屏幕上,如下所示:

Then you draw your image to the screen like this:

g.drawImage(bf, 0, 0, null);

这篇关于图像在重绘时闪烁()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆