NoFlickerApplet

This is a very simple extension/replacement for the Applet class which does all of it's drawing offscreen and the copies it to the screen. Basically, it writes a flickerless update method for you. There are definitely many scenarios where writi ng your own update method and just using a plain Applet make sense, but for a lot of purposes, NoFlickerApplet solves a lot of problems.

As a warning, it repaints the background, so it expects your paint method to fill in the entire area of the applet, or at least setColor to the desired background color.

Also, for complex applets (that do lots of seperate drawing) it's a bit slow.

To use it, take your applet that is flickering and change the part that says 'extends Applet' and change that to 'extends NoFlickerApplet' and recompile.

Back to MK's Java Page


Source

import java.awt.*;
import java.awt.image.ColorModel;
import java.net.URL;
import java.net.MalformedURLException;
import java.applet.Applet;
 
/**
 *
 *  Extension to base applet class to avoid display flicker
 *
 * @version             1.0, 27 Oct 1995
 * @author Matthew Gray
 *
 * Copyright (C) 1996 by Matthew Gray
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of Matthew Gray or net.Genesis not be used in advertising or 
 * publicity pertaining to distribution of the software without specific, 
 * written prior permission.  I make no representations about the 
 * suitability of this software for any purpose.  It is provided "as is" 
 * without express or implied warranty.
 */
 
public class NoFlickerApplet extends Applet {
  private Image offScreenImage;
  private Graphics offScreenGraphics;
  private Dimension offScreenSize;
  
  public final synchronized void update (Graphics theG)
    {
      Dimension d = size();
      if((offScreenImage == null) || (d.width != offScreenSize.width) ||
         (d.height != offScreenSize.height)) 
        {
          offScreenImage = createImage(d.width, d.height);
          offScreenSize = d;
          offScreenGraphics = offScreenImage.getGraphics();
          offScreenGraphics.setFont(getFont());
        }
      offScreenGraphics.fillRect(0,0,d.width, d.height);
      paint(offScreenGraphics);
      theG.drawImage(offScreenImage, 0, 0, null);
    }
}