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

2D Graphic

Development Platform:

Java

  1. /*
  2.  * @(#)TransformAnim.java 1.28 99/08/16
  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.Transforms;
  31. import java.awt.*;
  32. import java.awt.event.*;
  33. import java.awt.geom.*;
  34. import java.awt.image.*;
  35. import javax.swing.*;
  36. import javax.swing.event.*;
  37. import javax.swing.border.*;
  38. import java.util.Vector;
  39. import AnimatingContext;
  40. import DemoSurface;
  41. import DemoPanel;
  42. import CustomControls;
  43. /**
  44.  * Animation of shapes, text and images rotating, scaling and translating
  45.  * around a canvas.
  46.  */
  47. public class TransformAnim extends DemoSurface implements AnimatingContext, CustomControls {
  48.     private static TexturePaint texture;
  49.     static {
  50.         BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
  51.         Graphics2D gi = bi.createGraphics();
  52.         gi.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  53.                             RenderingHints.VALUE_ANTIALIAS_ON);
  54.         gi.setColor(Color.red);
  55.         gi.fillOval(0,0,9,9);
  56.         texture = new TexturePaint(bi,new Rectangle(0,0,10,10));
  57.     }
  58.     private static BasicStroke bs = new BasicStroke(6); 
  59.     private static Font fonts[] = {
  60.                 new Font("Times New Roman", Font.PLAIN, 48),
  61.                 new Font("serif", Font.BOLD + Font.ITALIC, 24),
  62.                 new Font("Courier", Font.BOLD, 36),
  63.                 new Font("Arial", Font.BOLD + Font.ITALIC, 64),
  64.                 new Font("Helvetica", Font.PLAIN, 52)};
  65.     private static String strings[] = {
  66.                 "Transformation", "Rotate", "Translate",
  67.                 "Shear", "Scale" };
  68.     private static String imgs[] = { "duke.gif" };
  69.     private static Paint paints[] = { 
  70.                 Color.red, Color.blue, texture, Color.green, Color.magenta, 
  71.                 Color.orange, Color.pink, Color.cyan, 
  72.                 new Color(0, 255, 0, 128), new Color(0, 0, 255, 128), 
  73.                 Color.yellow, Color.lightGray, Color.white};
  74.     private Vector vector = new Vector(13);
  75.     private DemoControls controls;
  76.     private int numShapes, numStrings, numImages;
  77.     protected boolean doRotate = true;
  78.     protected boolean doTranslate = true;
  79.     protected boolean doScale = true;
  80.     protected boolean doShear;
  81.     public TransformAnim() {
  82.         setBackground(Color.black);
  83.         setStrings(1);
  84.         setImages(2);
  85.         setShapes(10);
  86.         controls = new DemoControls(this);
  87.     }
  88.     public String[] getCustomControlsConstraints() {
  89.         return new String[] { BorderLayout.EAST };
  90.     }
  91.     public Component[] getCustomControls() {
  92.         return new Component[] { (Component) controls };
  93.     }
  94.     public void customControlsThread(int state) {
  95.         if (state == CustomControls.START) {
  96.             controls.start();
  97.         } else if (state == CustomControls.STOP) {
  98.             controls.stop();
  99.         }
  100.     }
  101.     public void setImages(int num) {
  102.         if (num < numImages) {
  103.             Vector v = new Vector(vector.size());
  104.             for (int i = 0; i < vector.size(); i++) {
  105.                 if (((ObjectData) vector.get(i)).object instanceof Image) {
  106.                     v.addElement(vector.get(i));
  107.                 }
  108.             }
  109.             vector.removeAll(v);
  110.             v.setSize(num);
  111.             vector.addAll(v);
  112.         } else {
  113.             Dimension d = getSize();
  114.             for (int i = numImages; i < num; i++) {
  115.                 Object obj = getImage(imgs[i % imgs.length]);
  116.                 ObjectData od = new ObjectData(obj, Color.black);
  117.                 od.reset(d.width, d.height);
  118.                 vector.addElement(od);
  119.             }
  120.         }
  121.         numImages = num;
  122.     }
  123.         
  124.     public void setStrings(int num) {
  125.         if (num < numStrings) {
  126.             Vector v = new Vector(vector.size());
  127.             for (int i = 0; i < vector.size(); i++) {
  128.                 if (((ObjectData) vector.get(i)).object instanceof TextData) {
  129.                     v.addElement(vector.get(i));
  130.                 }
  131.             }
  132.             vector.removeAll(v);
  133.             v.setSize(num);
  134.             vector.addAll(v);
  135.         } else {
  136.             Dimension d = getSize();
  137.             for (int i = numStrings; i < num; i++) {
  138.                 int j = i % fonts.length;
  139.                 int k = i % strings.length;
  140.                 Object obj = new TextData(strings[k], fonts[j]); 
  141.                 ObjectData od = new ObjectData(obj, paints[i%paints.length]);
  142.                 od.reset(d.width, d.height);
  143.                 vector.addElement(od);
  144.             }
  145.         }
  146.         numStrings = num;
  147.     }
  148.         
  149.     public void setShapes(int num) {
  150.         if (num < numShapes) {
  151.             Vector v = new Vector(vector.size());
  152.             for (int i = 0; i < vector.size(); i++) {
  153.                 if (((ObjectData) vector.get(i)).object instanceof Shape) {
  154.                     v.addElement(vector.get(i));
  155.                 }
  156.             }
  157.             vector.removeAll(v);
  158.             v.setSize(num);
  159.             vector.addAll(v);
  160.         } else {
  161.             Dimension d = getSize();
  162.             for (int i = numShapes; i < num; i++) {
  163.                 Object obj = null;
  164.                 switch (i % 7) {
  165.                     case 0 : obj = new GeneralPath(); break;
  166.                     case 1 : obj = new Rectangle2D.Double(); break;
  167.                     case 2 : obj = new Ellipse2D.Double(); break;
  168.                     case 3 : obj = new Arc2D.Double(); break;
  169.                     case 4 : obj = new RoundRectangle2D.Double(); break;
  170.                     case 5 : obj = new CubicCurve2D.Double(); break;
  171.                     case 6 : obj = new QuadCurve2D.Double(); break;
  172.                 }
  173.                 ObjectData od = new ObjectData(obj, paints[i%paints.length]);
  174.                 od.reset(d.width, d.height);
  175.                 vector.addElement(od);
  176.             }
  177.         } 
  178.         numShapes = num;
  179.     }
  180.         
  181.     public void reset(int w, int h) {
  182.         for (int i = 0; i < vector.size(); i++) {
  183.             ((ObjectData) vector.get(i)).reset(w, h);
  184.         }
  185.     }
  186.     public void step(int w, int h) {
  187.         for (int i = 0; i < vector.size(); i++) {
  188.             ((ObjectData) vector.get(i)).step(w, h, this);
  189.         }
  190.     }
  191.     public void drawDemo(int w, int h, Graphics2D g2) {
  192.         for (int i = 0; i < vector.size(); i++) {
  193.             ObjectData od = (ObjectData) vector.get(i);
  194.             g2.setTransform(od.at);
  195.             g2.setPaint(od.paint);
  196.             if (od.object instanceof Image) {
  197.                 g2.drawImage((Image) od.object, 0, 0, this);
  198.             } else if (od.object instanceof TextData) {
  199.                 g2.setFont(((TextData) od.object).font);
  200.                 g2.drawString(((TextData) od.object).string, 0, 0);
  201.             } else if (od.object instanceof QuadCurve2D 
  202.                     || od.object instanceof CubicCurve2D) 
  203.             {
  204.                 g2.setStroke(bs);
  205.                 g2.draw((Shape) od.object);
  206.             } else if (od.object instanceof Shape) {
  207.                 g2.fill((Shape) od.object);
  208.             }
  209.         }
  210.     }
  211.     public static void main(String argv[]) {
  212.         final DemoPanel dp = new DemoPanel(new TransformAnim());
  213.         Frame f = new Frame("Java2D Demo - TransformAnim");
  214.         f.addWindowListener(new WindowAdapter() {
  215.             public void windowClosing(WindowEvent e) {System.exit(0);}
  216.             public void windowDeiconified(WindowEvent e) { 
  217.                 dp.surface.start(); 
  218.             }
  219.             public void windowIconified(WindowEvent e) { 
  220.                 dp.surface.stop(); 
  221.             }
  222.         });
  223.         f.add("Center", dp);
  224.         f.pack();
  225.         f.setSize(new Dimension(500,300));
  226.         f.show();
  227.         dp.surface.start();
  228.     }
  229.     static class TextData extends Object {
  230. public String string;
  231.         public Font font;
  232.         public TextData(String str, Font font) {
  233.             string = str;
  234.             this.font = font;
  235.         }
  236.     }
  237.     static class ObjectData extends Object {
  238.         Object object;
  239.         Paint paint;
  240.         static final int UP = 0;
  241.         static final int DOWN = 1;
  242.         double x, y;
  243.         double ix=5, iy=3;
  244.         int rotate;
  245.         double scale, shear;
  246.         int scaleDirection, shearDirection;
  247.         AffineTransform at = new AffineTransform();
  248.         public ObjectData(Object object, Paint paint) {
  249.             this.object = object;
  250.             this.paint = paint;
  251.             rotate = (int)(Math.random() * 360);
  252.             scale = Math.random() * 1.5;
  253.             scaleDirection = Math.random() > 0.5 ? UP : DOWN;
  254.             shear = Math.random() * 0.5;
  255.             shearDirection = Math.random() > 0.5 ? UP : DOWN;
  256.         }
  257.         public void reset(int w, int h) {
  258.             x = Math.random()*w;
  259.             y = Math.random()*h;
  260.             double ww = 20 + Math.random()*((w == 0 ? 400 : w)/4);
  261.             double hh = 20 + Math.random()*((h == 0 ? 300 : h)/4);
  262.             if (object instanceof Ellipse2D) {
  263.                 ((Ellipse2D) object).setFrame(0, 0, ww, hh);
  264.             } else if (object instanceof Rectangle2D) {
  265.                 ((Rectangle2D) object).setRect(0, 0, ww, ww);
  266.             } else if (object instanceof RoundRectangle2D) {
  267.                 ((RoundRectangle2D) object).setRoundRect(0, 0, hh, hh, 20, 20); 
  268.             } else if (object instanceof Arc2D) {
  269.                 ((Arc2D) object).setArc(0, 0, hh, hh, 45, 270, Arc2D.PIE);
  270.             } else if (object instanceof QuadCurve2D) {
  271.                 ((QuadCurve2D) object).setCurve(0, 0, w*.2, h*.4, w*.4, 0);
  272.             } else if (object instanceof CubicCurve2D) {
  273.                     ((CubicCurve2D) object).setCurve(0,0,30,-60,60,60,90,0);
  274.             } else if (object instanceof GeneralPath) {
  275.                 GeneralPath p = new GeneralPath();
  276.                 float size = (float) ww;
  277.                 p.moveTo(- size / 2.0f, - size / 8.0f);
  278.                 p.lineTo(+ size / 2.0f, - size / 8.0f);
  279.                 p.lineTo(- size / 4.0f, + size / 2.0f);
  280.                 p.lineTo(+         0.0f, - size / 2.0f);
  281.                 p.lineTo(+ size / 4.0f, + size / 2.0f);
  282.                 p.closePath();
  283.                 object = p;
  284.             }
  285.         }
  286.         public void step(int w, int h, TransformAnim demo) {
  287.             at.setToIdentity();
  288.             if (demo.doRotate) {
  289.                 if ((rotate+=5) == 360) {
  290.                     rotate = 0;
  291.                 }
  292.                 at.rotate(Math.toRadians(rotate), x, y);
  293.             }
  294.             at.translate(x, y);
  295.             if (demo.doTranslate) {
  296.                 x += ix;
  297.                 y += iy;
  298.                 if (x > w) {
  299.                     x = w - 1;
  300.                     ix = Math.random() * -w/32 - 1;
  301.                 }
  302.                 if (x < 0) {
  303.                     x = 2;
  304.                     ix = Math.random() * w/32 + 1;
  305.                 }
  306.                 if (y > h ) {
  307.                     y = h - 2;
  308.                     iy = Math.random() * -h/32 - 1;
  309.                 }
  310.                 if (y < 0) {
  311.                     y = 2;
  312.                     iy = Math.random() * h/32 + 1;
  313.                 }
  314.             }
  315.             if (demo.doScale && scaleDirection == UP) {
  316.                 if ((scale += 0.05) > 1.5) {
  317.                     scaleDirection = DOWN;
  318.                 }
  319.             } else if (demo.doScale && scaleDirection == DOWN) {
  320.                 if ((scale -= .05) < 0.5) {
  321.                     scaleDirection = UP;
  322.                 }
  323.             }
  324.             if (demo.doScale) {
  325.                 at.scale(scale, scale);
  326.             }
  327.             if (demo.doShear && shearDirection == UP) {
  328.                 if ((shear += 0.05) > 0.5) {
  329.                     shearDirection = DOWN;
  330.                 }
  331.             } else if (demo.doShear && shearDirection == DOWN) {
  332.                 if ((shear -= .05) < -0.5) {
  333.                     shearDirection = UP;
  334.                 }
  335.             }
  336.             if (demo.doShear) {
  337.                 at.shear(shear, shear);
  338.             }
  339.         }
  340.     } // End ObjectData class
  341.     static class DemoControls extends JPanel implements ActionListener, ChangeListener, Runnable {
  342.         TransformAnim demo;
  343.         JSlider shapeSlider, stringSlider, imageSlider;
  344.         Thread thread;
  345.         Font font = new Font("serif", Font.PLAIN, 10);
  346.         JToolBar toolbar;
  347.         public DemoControls(TransformAnim demo) {
  348.             this.demo = demo;
  349.             setBackground(Color.gray);
  350.             setLayout(new BorderLayout());
  351.             JToolBar bar = new JToolBar(JToolBar.VERTICAL);
  352.             bar.setBackground(Color.gray);
  353.             bar.setFloatable(false);
  354.             shapeSlider = new JSlider(JSlider.HORIZONTAL,0,20,demo.numShapes);
  355.             shapeSlider.addChangeListener(this);
  356.             TitledBorder tb = new TitledBorder(new EtchedBorder());
  357.             tb.setTitleFont(font);
  358.             tb.setTitle(String.valueOf(demo.numShapes) + " Shapes");
  359.             shapeSlider.setBorder(tb);
  360.             shapeSlider.setPreferredSize(new Dimension(80,44));
  361.             bar.add(shapeSlider);
  362.             bar.addSeparator();
  363.             stringSlider = new JSlider(JSlider.HORIZONTAL,0,10,demo.numStrings);
  364.             stringSlider.addChangeListener(this);
  365.             tb = new TitledBorder(new EtchedBorder());
  366.             tb.setTitleFont(font);
  367.             tb.setTitle(String.valueOf(demo.numStrings) + " Strings");
  368.             stringSlider.setBorder(tb);
  369.             stringSlider.setPreferredSize(new Dimension(80,44));
  370.             bar.add(stringSlider);
  371.             bar.addSeparator();
  372.             imageSlider = new JSlider(JSlider.HORIZONTAL,0,10,demo.numImages);
  373.             imageSlider.addChangeListener(this);
  374.             tb = new TitledBorder(new EtchedBorder());
  375.             tb.setTitleFont(font);
  376.             tb.setTitle(String.valueOf(demo.numImages) + " Images");
  377.             imageSlider.setBorder(tb);
  378.             imageSlider.setPreferredSize(new Dimension(80,44));
  379.             bar.add(imageSlider);
  380.             bar.addSeparator();
  381.             toolbar = new JToolBar();
  382.             toolbar.setFloatable(false);
  383.             addButton("T", "translate", demo.doTranslate);
  384.             addButton("R", "rotate", demo.doRotate);
  385.             addButton("SC", "scale", demo.doScale);
  386.             addButton("SH", "shear", demo.doShear);
  387.             bar.add(toolbar);
  388.             add(bar);
  389.             bar.addMouseListener(new MouseAdapter() {
  390.                 public void mouseClicked(MouseEvent e) {
  391.                     if (thread == null) start(); else stop();
  392.                 }
  393.             });
  394.         }
  395.         public void addButton(String s, String tt, boolean state) {
  396.             JButton b = (JButton) toolbar.add(new JButton(s));
  397.             b.setFont(font);
  398.             b.setSelected(state);
  399.             b.setToolTipText(tt);
  400.             b.setBackground(state ? Color.green : Color.lightGray);
  401.             b.addActionListener(this);
  402.         }
  403.         public void actionPerformed(ActionEvent e) {
  404.             JButton b = (JButton) e.getSource();
  405.             b.setSelected(!b.isSelected());
  406.             b.setBackground(b.isSelected() ? Color.green : Color.lightGray);
  407.             if (b.getText().equals("T")) {
  408.                 demo.doTranslate = b.isSelected();
  409.             } else if (b.getText().equals("R")) {
  410.                 demo.doRotate = b.isSelected();
  411.             } else if (b.getText().equals("SC")) {
  412.                 demo.doScale = b.isSelected();
  413.             } else if (b.getText().equals("SH")) {
  414.                 demo.doShear = b.isSelected();
  415.             }
  416.             if (demo.thread == null) {
  417.                 demo.repaint();
  418.             }
  419.         }
  420.         public void stateChanged(ChangeEvent e) {
  421.             JSlider slider = (JSlider) e.getSource();
  422.             int value = slider.getValue();
  423.             TitledBorder tb = (TitledBorder) slider.getBorder();
  424.             if (slider.equals(shapeSlider)) {
  425.                 tb.setTitle(String.valueOf(value) + " Shapes");
  426.                 demo.setShapes(value);
  427.             } else if (slider.equals(stringSlider)) {
  428.                 tb.setTitle(String.valueOf(value) + " Strings");
  429.                 demo.setStrings(value);
  430.             } else if (slider.equals(imageSlider)) {
  431.                 tb.setTitle(String.valueOf(value) + " Images");
  432.                 demo.setImages(value);
  433.             } 
  434.             if (demo.thread == null) {
  435.                 demo.repaint();
  436.             }
  437.             slider.repaint();
  438.         }
  439.         public Dimension getPreferredSize() {
  440.             return new Dimension(80,36);
  441.         }
  442.         public void start() {
  443.             if (thread != null) {
  444.                 return;
  445.             }
  446.             thread = new Thread(this);
  447.             thread.setPriority(Thread.MIN_PRIORITY);
  448.             thread.setName("Transforms.TransformAnim DemoControls Thread");
  449.             thread.start();
  450.         }
  451.         public synchronized void stop() {
  452.             if (thread != null) {
  453.                 thread.interrupt();
  454.             }
  455.             thread = null;
  456.             notifyAll();
  457.         }
  458.         public void run() {
  459.             Thread me = Thread.currentThread();
  460.             while (thread == me) {
  461.                 for (int i = 1; i < toolbar.getComponentCount(); i++) {
  462.                     try {
  463.                         thread.sleep(4444);
  464.                     } catch (InterruptedException e) { return; }
  465.                     ((JButton) toolbar.getComponentAtIndex(i)).doClick();
  466.                 }
  467.             }
  468.             thread = null;
  469.         }
  470.     } // End DemoControls
  471. } // End TransformAnim