简体   繁体   中英

How can I stop image flickering in Java Applet?

My problem is that whenever I use a Java Applet I just coded, my png images flicker repeatdly. I have already changed my thread sleep time to smaller, and that does not remove the problem.

Here is the code where I'm calling on the image to be shown:

    public void init(){
    setSize(854, 480);
    Thread th = new Thread(this);
    th.start();
    offscreen = createImage(854,480);
    d = offscreen.getGraphics();
    addKeyListener(this);
}
public void paint(Graphics g){

    g.clearRect(0, 0, 854, 480);
    g.drawImage(background, 0, 0, this);
    d.drawImage(offscreen, 0, 0, this);
    g.drawOval(x, y, 20, 20);
}
public void update(Graphics g){
    paint(g);
}

And this line of code is where I'm declaring the image if you like

    background = ImageIO.read(this.getClass().getResource("background.png"));

The flickering is caused by clearRect.

If your images cover entire applet, you can just remove clearRect call.

If they do not cover, you need to create an offscreen image, make all drawing to it, and then draw offscreen image by drawImage call to your applet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM