001 /*
002 * LAPIS lightweight structured text processing system
003 *
004 * Copyright (C) 1998-2002 Carnegie Mellon University,
005 * Copyright (C) 2003 Massachusetts Institute of Technology.
006 * All rights reserved.
007 *
008 * This library is free software; you can redistribute it
009 * and/or modify it under the terms of the GNU General
010 * Public License as published by the Free Software
011 * Foundation, version 2.
012 *
013 * LAPIS homepage: http://graphics.lcs.mit.edu/lapis/
014 */
015
016 package lapisx.swing;
017
018 import java.awt.*;
019 import java.awt.event.*;
020 import javax.swing.*;
021
022 public class Animation extends JComponent {
023 public static lapisx.util.Debug debug = lapisx.util.Debug.QUIET;
024
025 boolean animating;
026 Image animatedImage;
027 Image frozenImage;
028
029 public Animation (Image animatedImage, Image frozenImage) {
030 this (animatedImage, frozenImage, true);
031 }
032
033 public Animation (Image animatedImage, Image frozenImage, boolean animating) {
034 this.animatedImage = animatedImage;
035 this.frozenImage = frozenImage;
036
037 MediaTracker mt = new MediaTracker (this);
038 mt.addImage (animatedImage, 0);
039 mt.addImage (frozenImage, 1);
040 try {
041 mt.waitForAll ();
042 } catch (InterruptedException e) {}
043
044 int w = animatedImage.getWidth (null);
045 int h = animatedImage.getHeight (null);
046 if (w == -1 || h == -1)
047 throw new RuntimeException ("image error: can't get width and height");
048
049 w = Math.max (w, frozenImage.getWidth (null));
050 h = Math.max (h, frozenImage.getHeight (null));
051
052 setPreferredSize (new Dimension (w, h));
053
054 this.animating = animating;
055 }
056
057 public synchronized boolean getAnimating () {
058 return animating;
059 }
060
061 public synchronized void setAnimating (boolean animating) {
062 this.animating = animating;
063 repaint ();
064 }
065
066 public void paintComponent (Graphics g) {
067 super.paintComponent (g);
068 debug.println ("Animation.paintComponent");
069
070 if (animating)
071 g.drawImage (animatedImage, 0, 0, this);
072 else {
073 animatedImage.flush ();
074 g.drawImage (frozenImage, 0, 0, this);
075 }
076 }
077
078 public static void main (String[] argv) throws Exception {
079 final Animation anim =
080 new Animation (Toolkit.getDefaultToolkit ().getImage (argv[0]),
081 Toolkit.getDefaultToolkit ().getImage (argv[1]),
082 true);
083 JFrame f = new JFrame ("Animation");
084 f.getContentPane ().add (anim, BorderLayout.CENTER);
085 f.getContentPane ().setBackground (Color.red);
086 f.addWindowListener (new WindowAdapter () {
087 public void windowClosing (WindowEvent evt) {
088 System.exit(0);
089 }
090 });
091 f.addMouseListener (new MouseAdapter () {
092 public void mouseClicked (MouseEvent event) {
093 anim.setAnimating (!anim.getAnimating ());
094 }
095 });
096 f.pack ();
097 f.show ();
098 }
099 }