FadeAnim.java
Upload User: cdlibang
Upload Date: 2016-07-17
Package Size: 774k
Code Size: 18k
Category:

2D Graphic

Development Platform:

Java

  1. /*
  2.  * @(#)FadeAnim.java 1.29 99/05/07
  3.  *
  4.  * Copyright (c) 1998, 1999 by Sun Microsystems, Inc. All Rights Reserved.
  5.  * 
  6.  * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
  7.  * modify and redistribute this software in source and binary code form,
  8.  * provided that i) this copyright notice and license appear on all copies of
  9.  * the software; and ii) Licensee does not utilize the software in a manner
  10.  * which is disparaging to Sun.
  11.  * 
  12.  * This software is provided "AS IS," without a warranty of any kind. ALL
  13.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
  14.  * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
  15.  * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
  16.  * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
  17.  * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
  18.  * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
  19.  * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
  20.  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
  21.  * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
  22.  * POSSIBILITY OF SUCH DAMAGES.
  23.  * 
  24.  * This software is not designed or intended for use in on-line control of
  25.  * aircraft, air traffic, aircraft navigation or aircraft communications; or in
  26.  * the design, construction, operation or maintenance of any nuclear
  27.  * facility. Licensee represents and warrants that it will not use or
  28.  * redistribute the Software for such purposes.
  29.  */
  30. package demos.Composite;
  31. import java.awt.*;
  32. import java.awt.geom.*;
  33. import java.awt.image.*;
  34. import java.awt.event.*;
  35. import java.util.Vector;
  36. import javax.swing.*;
  37. import javax.swing.event.*;
  38. import javax.swing.border.*;
  39. import AnimatingContext;
  40. import DemoSurface;
  41. import DemoPanel;
  42. import CustomControls;
  43. /**
  44.  * Animation of compositing shapes, text and images fading in and out.
  45.  */
  46. public class FadeAnim extends DemoSurface implements AnimatingContext, CustomControls {
  47.     private static TexturePaint texture;
  48.     static {
  49.         int w = 10; int h = 10;
  50.         BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  51.         Graphics2D gi = bi.createGraphics();
  52.         Color oc = Color.blue; Color ic = Color.green;
  53.         gi.setPaint(new GradientPaint(0,0,oc,w*.35f,h*.35f,ic));
  54.         gi.fillRect(0, 0, w/2, h/2);
  55.         gi.setPaint(new GradientPaint(w,0,oc,w*.65f,h*.35f,ic));
  56.         gi.fillRect(w/2, 0, w/2, h/2);
  57.         gi.setPaint(new GradientPaint(0,h,oc,w*.35f,h*.65f,ic));
  58.         gi.fillRect(0, h/2, w/2, h/2);
  59.         gi.setPaint(new GradientPaint(w,h,oc,w*.65f,h*.65f,ic));
  60.         gi.fillRect(w/2, h/2, w/2, h/2);
  61.         texture = new TexturePaint(bi,new Rectangle(0,0,w,h));
  62.     }
  63.     private static BasicStroke bs = new BasicStroke(6); 
  64.     private static Font fonts[] = {
  65.                 new Font("Times New Roman", Font.PLAIN, 64),
  66.                 new Font("serif", Font.BOLD + Font.ITALIC, 24),
  67.                 new Font("Courier", Font.BOLD, 36),
  68.                 new Font("Arial", Font.BOLD + Font.ITALIC, 48),
  69.                 new Font("Helvetica", Font.PLAIN, 52)};
  70.     private static String strings[] = {
  71.                 "Alpha", "Composite", "Src", "SrcOver", 
  72.                 "SrcIn", "SrcOut", "Clear", "DstOver", "DstIn" };
  73.     private static String imgs[] = { 
  74.                 "jumptojavastrip.gif", "duke.gif", "star7.gif" };
  75.     private static Paint paints[] = { 
  76.                 Color.red, Color.blue, Color.green, Color.magenta, 
  77.                 Color.orange, Color.pink, Color.cyan, texture,
  78.                 Color.yellow, Color.lightGray, Color.white};
  79.     private Vector vector = new Vector(20);
  80.     private DemoControls controls;
  81.     private int numShapes, numStrings, numImages;
  82.     public FadeAnim() {
  83.         setBackground(Color.black);
  84.         setStrings(2);
  85.         setImages(3);
  86.         setShapes(8);
  87.         controls = new DemoControls(this);
  88.     }
  89.     public String[] getCustomControlsConstraints() {
  90.         return new String[] { BorderLayout.EAST };
  91.     }
  92.     public Component[] getCustomControls() {
  93.         return new Component[] { (Component) controls };
  94.     }
  95.     public void customControlsThread(int state) {
  96.         if (state == CustomControls.START) {
  97.             controls.start();
  98.         } else if (state == CustomControls.STOP) {
  99.             controls.stop();
  100.         }
  101.     }
  102.     public void setImages(int num) {
  103.         if (num < numImages) {
  104.             Vector v = new Vector(vector.size());
  105.             for (int i = 0; i < vector.size(); i++) {
  106.                 if (((ObjectData) vector.get(i)).object instanceof Image) {
  107.                     v.addElement(vector.get(i));
  108.                 }
  109.             }
  110.             vector.removeAll(v);
  111.             v.setSize(num);
  112.             vector.addAll(v);
  113.         } else {
  114.             Dimension d = getSize();
  115.             for (int i = numImages; i < num; i++) {
  116.                 Object obj = getImage(imgs[i % imgs.length]);
  117.                 if (imgs[i % imgs.length].equals("jumptojavastrip.gif")) {
  118.                     int iw = ((Image) obj).getWidth(null);
  119.                     int ih = ((Image) obj).getHeight(null);
  120.                     BufferedImage bimg = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
  121.                     bimg.createGraphics().drawImage((Image) obj, 0, 0, null);
  122.                     obj = bimg;
  123.                 }
  124.                 ObjectData od = new ObjectData(obj, Color.black);
  125.                 od.reset(d.width, d.height);
  126.                 vector.addElement(od);
  127.             }
  128.         }
  129.         numImages = num;
  130.     }
  131.         
  132.     public void setStrings(int num) {
  133.         if (num < numStrings) {
  134.             Vector v = new Vector(vector.size());
  135.             for (int i = 0; i < vector.size(); i++) {
  136.                 if (((ObjectData) vector.get(i)).object instanceof TextData) {
  137.                     v.addElement(vector.get(i));
  138.                 }
  139.             }
  140.             vector.removeAll(v);
  141.             v.setSize(num);
  142.             vector.addAll(v);
  143.         } else {
  144.             Dimension d = getSize();
  145.             for (int i = numStrings; i < num; i++) {
  146.                 int j = i % fonts.length;
  147.                 int k = i % strings.length;
  148.                 Object obj = new TextData(strings[k], fonts[j], this); 
  149.                 ObjectData od = new ObjectData(obj, paints[i%paints.length]);
  150.                 od.reset(d.width, d.height);
  151.                 vector.addElement(od);
  152.             }
  153.         }
  154.         numStrings = num;
  155.     }
  156.         
  157.     public void setShapes(int num) {
  158.         if (num < numShapes) {
  159.             Vector v = new Vector(vector.size());
  160.             for (int i = 0; i < vector.size(); i++) {
  161.                 if (((ObjectData) vector.get(i)).object instanceof Shape) {
  162.                     v.addElement(vector.get(i));
  163.                 }
  164.             }
  165.             vector.removeAll(v);
  166.             v.setSize(num);
  167.             vector.addAll(v);
  168.         } else {
  169.             Dimension d = getSize();
  170.             for (int i = numShapes; i < num; i++) {
  171.                 Object obj = null;
  172.                 switch (i % 7) {
  173.                     case 0 : obj = new GeneralPath(); break;
  174.                     case 1 : obj = new Rectangle2D.Double(); break;
  175.                     case 2 : obj = new Ellipse2D.Double(); break;
  176.                     case 3 : obj = new Arc2D.Double(); break;
  177.                     case 4 : obj = new RoundRectangle2D.Double(); break;
  178.                     case 5 : obj = new CubicCurve2D.Double(); break;
  179.                     case 6 : obj = new QuadCurve2D.Double(); break;
  180.                 }
  181.                 ObjectData od = new ObjectData(obj, paints[i%paints.length]);
  182.                 od.reset(d.width, d.height);
  183.                 vector.addElement(od);
  184.             }
  185.         } 
  186.         numShapes = num;
  187.     }
  188.     public void reset(int w, int h) {
  189.         for (int i = 0; i < vector.size(); i++) {
  190.             ((ObjectData) vector.get(i)).reset(w, h);
  191.         }
  192.     }
  193.     public void step(int w, int h) {
  194.         for (int i = 0; i < vector.size(); i++) {
  195.             ((ObjectData) vector.get(i)).step(w, h);
  196.         }
  197.     }
  198.     public void drawDemo(int w, int h, Graphics2D g2) {
  199.         for (int i = 0; i < vector.size(); i++) {
  200.             ObjectData od = (ObjectData) vector.get(i);
  201.             AlphaComposite ac = AlphaComposite.getInstance(
  202.                                    AlphaComposite.SRC_OVER, od.alpha);
  203.             g2.setComposite(ac);
  204.             g2.setPaint(od.paint);
  205.             g2.translate(od.x, od.y);
  206.             if (od.object instanceof Image) {
  207.                 g2.drawImage((Image) od.object, 0, 0, this);
  208.             } else if (od.object instanceof TextData) {
  209.                 g2.setFont(((TextData) od.object).font);
  210.                 g2.drawString(((TextData) od.object).string, 0, 0);
  211.             } else if (od.object instanceof QuadCurve2D 
  212.                     || od.object instanceof CubicCurve2D) 
  213.             {
  214.                 g2.setStroke(bs);
  215.                 g2.draw((Shape) od.object);
  216.             } else if (od.object instanceof Shape) {
  217.                 g2.fill((Shape) od.object);
  218.             }
  219.             g2.translate(-od.x, -od.y);
  220.         }
  221.     }
  222.     public static void main(String argv[]) {
  223.         final DemoPanel dp = new DemoPanel(new FadeAnim());
  224.         Frame f = new Frame("Java2D Demo - FadeAnim");
  225.         f.addWindowListener(new WindowAdapter() {
  226.             public void windowClosing(WindowEvent e) {System.exit(0);}
  227.             public void windowDeiconified(WindowEvent e) { 
  228.                 dp.surface.start(); 
  229.             }
  230.             public void windowIconified(WindowEvent e) { 
  231.                 dp.surface.stop(); 
  232.             }
  233.         });
  234.         f.add("Center", dp);
  235.         f.pack();
  236.         f.setSize(new Dimension(400,300));
  237.         f.show();
  238.         dp.surface.start();
  239.     }
  240.     static class TextData extends Object {
  241. public String string;
  242.         public Font font;
  243.         public int width, height;
  244.         public TextData(String str, Font font, Component cmp) {
  245.             string = str;
  246.             this.font = font;
  247.             FontMetrics fm = cmp.getFontMetrics(font);
  248.             width = fm.stringWidth(str);
  249.             height = fm.getHeight();
  250.         }
  251.     }
  252.     static class ObjectData extends Object {
  253.         final int UP = 0;
  254.         final int DOWN = 1;
  255.         Object object;
  256.         BufferedImage bimg;
  257.         Paint paint;
  258.         double x, y;
  259.         float alpha;
  260.         int alphaDirection;
  261.         int imgX;
  262.         public ObjectData(Object object, Paint paint) {
  263.             this.object = object;
  264.             this.paint = paint;
  265.             if (object instanceof BufferedImage) {
  266.                 bimg = (BufferedImage) object;
  267.                 this.object = bimg.getSubimage(0, 0, 80, 80);    
  268.             }
  269.             getRandomXY(300, 250);
  270.             alpha = (float) Math.random();
  271.             alphaDirection = Math.random() > 0.5 ? UP : DOWN;
  272.         }
  273.         private void getRandomXY(int w, int h) {
  274.             if (object instanceof TextData) {
  275.                 x = Math.random() * (w - ((TextData) object).width);
  276.                 y = Math.random() * h;
  277.                 y = y < ((TextData) object).height ? ((TextData) object).height : y;
  278.             } else if (object instanceof Image) {
  279.                 x = Math.random() * (w - ((Image) object).getWidth(null));
  280.                 y = Math.random() * (h - ((Image) object).getHeight(null));
  281.             } else if (object instanceof Shape) {
  282.                 Rectangle bounds = ((Shape) object).getBounds();
  283.                 x = Math.random() * (w - bounds.width);
  284.                 y = Math.random() * (h - bounds.height);
  285.             }
  286.         }
  287.         public void reset(int w, int h) {
  288.             getRandomXY(w, h);
  289.             double ww = 20 + Math.random()*((w == 0 ? 400 : w)/4);
  290.             double hh = 20 + Math.random()*((h == 0 ? 300 : h)/4);
  291.             if (object instanceof Ellipse2D) {
  292.                 ((Ellipse2D) object).setFrame(0, 0, ww, hh);
  293.             } else if (object instanceof Rectangle2D) {
  294.                 ((Rectangle2D) object).setRect(0, 0, ww, ww);
  295.             } else if (object instanceof RoundRectangle2D) {
  296.                 ((RoundRectangle2D) object).setRoundRect(0, 0, hh, hh, 20, 20); 
  297.             } else if (object instanceof Arc2D) {
  298.                 ((Arc2D) object).setArc(0, 0, hh, hh, 45, 270, Arc2D.PIE);
  299.             } else if (object instanceof QuadCurve2D) {
  300.                 ((QuadCurve2D) object).setCurve(0, 0, w*.2, h*.4, w*.4, 0);
  301.             } else if (object instanceof CubicCurve2D) {
  302.                     ((CubicCurve2D) object).setCurve(0,0,30,-60,60,60,90,0);
  303.             } else if (object instanceof GeneralPath) {
  304.                 GeneralPath p = new GeneralPath();
  305.                 float size = (float) ww;
  306.                 p.moveTo(- size / 2.0f, - size / 8.0f);
  307.                 p.lineTo(+ size / 2.0f, - size / 8.0f);
  308.                 p.lineTo(- size / 4.0f, + size / 2.0f);
  309.                 p.lineTo(+         0.0f, - size / 2.0f);
  310.                 p.lineTo(+ size / 4.0f, + size / 2.0f);
  311.                 p.closePath();
  312.                 object = p;
  313.             }
  314.         }
  315.         public void step(int w, int h) {
  316.             if (object instanceof BufferedImage) {
  317.                 if ((imgX += 80) == 800) {
  318.                     imgX = 0;
  319.                 }
  320.                 object = bimg.getSubimage(imgX, 0, 80, 80);    
  321.             }
  322.             if (alphaDirection == UP) {
  323.                 if ((alpha += 0.05) > .99) {
  324.                     alphaDirection = DOWN;
  325.                     alpha = 1.0f;
  326.                 }
  327.             } else if (alphaDirection == DOWN) {
  328.                 if ((alpha -= .05) < 0.01) {
  329.                     alphaDirection = UP;
  330.                     alpha = 0;
  331.                     getRandomXY(w, h);
  332.                 }
  333.             }
  334.         }
  335.     }
  336.     static class DemoControls extends JPanel implements ChangeListener, Runnable {
  337.         FadeAnim demo;
  338.         JSlider shapeSlider, stringSlider, imageSlider;
  339.         Thread thread;
  340.         Font font = new Font("serif", Font.PLAIN, 10);
  341.         public DemoControls(FadeAnim demo) {
  342.             this.demo = demo;
  343.             setBackground(Color.gray);
  344.             setLayout(new BorderLayout());
  345.             JToolBar toolbar = new JToolBar(JToolBar.VERTICAL);
  346.             toolbar.setBackground(Color.gray);
  347.             toolbar.setFloatable(false);
  348.             shapeSlider = new JSlider(JSlider.HORIZONTAL,0,20,demo.numShapes);
  349.             shapeSlider.addChangeListener(this);
  350.             TitledBorder tb = new TitledBorder(new EtchedBorder());
  351.             tb.setTitleFont(font);
  352.             tb.setTitle(String.valueOf(demo.numShapes) + " Shapes");
  353.             shapeSlider.setBorder(tb);
  354.             shapeSlider.setPreferredSize(new Dimension(80,45));
  355.             toolbar.addSeparator();
  356.             toolbar.add(shapeSlider);
  357.             toolbar.addSeparator();
  358.             stringSlider = new JSlider(JSlider.HORIZONTAL,0,10,demo.numStrings);
  359.             stringSlider.addChangeListener(this);
  360.             tb = new TitledBorder(new EtchedBorder());
  361.             tb.setTitleFont(font);
  362.             tb.setTitle(String.valueOf(demo.numStrings) + " Strings");
  363.             stringSlider.setBorder(tb);
  364.             stringSlider.setPreferredSize(new Dimension(80,45));
  365.             toolbar.add(stringSlider);
  366.             toolbar.addSeparator();
  367.             imageSlider = new JSlider(JSlider.HORIZONTAL,0,10,demo.numImages);
  368.             imageSlider.addChangeListener(this);
  369.             tb = new TitledBorder(new EtchedBorder());
  370.             tb.setTitleFont(font);
  371.             tb.setTitle(String.valueOf(demo.numImages) + " Images");
  372.             imageSlider.setBorder(tb);
  373.             imageSlider.setPreferredSize(new Dimension(80,45));
  374.             toolbar.add(imageSlider);
  375.             toolbar.addSeparator();
  376.             add(toolbar);
  377.             toolbar.addMouseListener(new MouseAdapter() {
  378.                 public void mouseClicked(MouseEvent e) {
  379.                     if (thread == null) start(); else stop();
  380.                 }
  381.             });
  382.         }
  383.         public void stateChanged(ChangeEvent e) {
  384.             JSlider slider = (JSlider) e.getSource();
  385.             int value = slider.getValue();
  386.             TitledBorder tb = (TitledBorder) slider.getBorder();
  387.             if (slider.equals(shapeSlider)) {
  388.                 tb.setTitle(String.valueOf(value) + " Shapes");
  389.                 demo.setShapes(value);
  390.             } else if (slider.equals(stringSlider)) {
  391.                 tb.setTitle(String.valueOf(value) + " Strings");
  392.                 demo.setStrings(value);
  393.             } else if (slider.equals(imageSlider)) {
  394.                 tb.setTitle(String.valueOf(value) + " Images");
  395.                 demo.setImages(value);
  396.             } 
  397.             slider.repaint();
  398.             if (demo.thread == null) {
  399.                 demo.repaint();
  400.             }
  401.         }
  402.         public Dimension getPreferredSize() {
  403.             return new Dimension(80,0);
  404.         }
  405.         public void start() {
  406.             if (thread != null) {
  407.                 return;
  408.             }
  409.             thread = new Thread(this);
  410.             thread.setPriority(Thread.MIN_PRIORITY);
  411.             thread.setName("Composite.FadeAnim DemoControls Thread");
  412.             thread.start();
  413.         }
  414.         public synchronized void stop() {
  415.             if (thread != null) {
  416.                 thread.interrupt();
  417.             }
  418.             thread = null;
  419.             notifyAll();
  420.         }
  421.         public void run() {
  422.             try { 
  423.                thread.sleep(999);
  424.             } catch (InterruptedException e) { return; }
  425.             shapeSlider.setValue((int) (Math.random() * 5));
  426.             stringSlider.setValue(10);
  427.             thread = null;
  428.         }
  429.     } // End DemoControls
  430. } // End FadeAnim