Java Graphics How to - Create animated BufferedImage








Question

We would like to know how to create animated BufferedImage.

Answer

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
//from w w w  . j a  v  a2  s.  c  om
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
  public static void main(String[] args) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        JPanel gui = new JPanel();

        final AnimatedImage[] tiles = new AnimatedImage[2];
        for (int ii = 0; ii < tiles.length; ii++) {
          tiles[ii] = new AnimatedImage();
          gui.add(new JLabel(new ImageIcon(tiles[ii])));
        }
        ActionListener listener = new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < tiles.length; i++) {
              tiles[i].paintImage();
              gui.repaint();
            }
          }
        };
        Timer timer = new Timer(50, listener);
        timer.start();

        JOptionPane.showMessageDialog(null, gui);
        timer.stop();
      }
    };
    SwingUtilities.invokeLater(r);
  }
}

class AnimatedImage extends BufferedImage {
  GradientPaint[] frameGradient;
  int frame = 0;
  AnimatedImage() {
    super(60, 60, BufferedImage.TYPE_INT_RGB);
    frameGradient = new GradientPaint[6];
    for (int i = 0; i < frameGradient.length; i++) {
      frameGradient[i] = new GradientPaint(0f, (float) i, Color.BLUE, 0f,
          (float) i + 13, Color.RED, true);
    }
  }

  public void paintImage() {
    Graphics2D g = createGraphics();
    if (frame == frameGradient.length - 1)
      frame = 0;
    else
      frame++;
    g.setPaint(frameGradient[frame]);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.dispose();
  }
}