Image flickers on repaint()

江枫思渺然 提交于 2019-11-28 12:46:15

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

Non flickering, working Code.

Repaint() doesn't just call the paint() method. A repaint() method actually calls the update() method and the default update() method then calls to the paint() method. So just override the update() method. Also painting as BufferedImage as mentioned above correctly.

This should work now. It worked fine here. I only used a different imagepath.

import java.awt.Graphics;
import java.awt.Image;
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 static final long serialVersionUID = 1L;
    private Image TestImage;
    private BufferedImage bf;
    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);
    }

    public void update(Graphics g){
           paint(g);
    }

    public void paint(Graphics g){

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

    try{
    animation(bf.getGraphics());
    g.drawImage(bf,0,0,null);
    }catch(Exception ex){

    }
}

    public void animation(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) {
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!