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

2D Graphic

Development Platform:

Java

  1. /*
  2.  * @(#)BezierScroller.java 1.27 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.Mix;
  31. import java.awt.*;
  32. import java.awt.event.*;
  33. import java.awt.geom.GeneralPath;
  34. import java.awt.geom.PathIterator;
  35. import java.awt.font.FontRenderContext;
  36. import java.awt.font.TextLayout;
  37. import java.awt.image.BufferedImage;
  38. import java.io.File;
  39. import java.io.FileReader;
  40. import java.io.BufferedReader;
  41. import java.util.Vector;
  42. import javax.swing.*;
  43. import AnimatingContext;
  44. import DemoSurface;
  45. import DemoPanel;
  46. import CustomControls;
  47. /**
  48.  * Animated Bezier Curve shape with images at the control points.
  49.  * README.txt file scrolling up. Composited Image fading in and out.
  50.  */
  51. public class BezierScroller extends DemoSurface implements AnimatingContext, CustomControls {
  52.     private static String appletStrs[] = 
  53.         {  " ", "Java2Demo",  
  54.            "BezierScroller - Animated Bezier Curve shape with images", 
  55.            "For README.txt file scrolling run in application mode", " " };
  56.     private static final int NUMPTS = 6;
  57.     private static Color greenBlend = new Color(0, 255, 0, 100);
  58.     private static Font font = new Font("serif", Font.PLAIN, 12);
  59.     private static Color blueBlend = new Color(0, 0, 255, 100);
  60.     private static BasicStroke bs = new BasicStroke(3.0f);
  61.     private static Image hotj_img;
  62.     private static BufferedImage img;
  63.     private static final int UP = 0;
  64.     private static final int DOWN = 1;
  65.     private float animpts[] = new float[NUMPTS * 2];
  66.     private float deltas[] = new float[NUMPTS * 2];
  67.     private BufferedReader reader;      
  68.     private int nStrs;          
  69.     private int strH;
  70.     private int yy, ix, iy, imgX;
  71.     private Vector vector, appletVector;
  72.     private float alpha = 0.2f;
  73.     private int alphaDirection;
  74.     private DemoControls controls;
  75.     protected boolean doImage, doShape, doText;
  76.     protected boolean buttonToggle;
  77.     public BezierScroller() {
  78.         setBackground(Color.white);
  79.         doShape = doText = true;
  80.         hotj_img = getImage("HotJava-16.gif");
  81.         Image image = getImage("jumptojavastrip.gif");
  82.         int iw = image.getWidth(this);
  83.         int ih = image.getHeight(this);
  84.         img = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
  85.         img.createGraphics().drawImage(image, 0, 0, this);
  86.         controls = new DemoControls(this);
  87.     }
  88.     public String[] getCustomControlsConstraints() {
  89.         return new String[] { BorderLayout.NORTH };
  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 animate(float[] pts, float[] deltas, int index, int limit) {
  102.         float newpt = pts[index] + deltas[index];
  103.         if (newpt <= 0) {
  104.             newpt = -newpt;
  105.             deltas[index] = (float) (Math.random() * 4.0 + 2.0);
  106.         } else if (newpt >= (float) limit) {
  107.             newpt = 2.0f * limit - newpt;
  108.             deltas[index] = - (float) (Math.random() * 4.0 + 2.0);
  109.         }
  110.         pts[index] = newpt;
  111.     }
  112.     public void getFile() {
  113.         try {
  114.             File file = new File("README.txt");
  115.             if ((reader = new BufferedReader(new FileReader(file))) != null) {
  116.                 getLine();
  117.             }
  118.         } catch (Exception e) { reader = null; }
  119.         if (reader == null) {
  120.             appletVector = new Vector(100);
  121.             for (int i = 0; i < 100; i++) {
  122.                 appletVector.addElement(appletStrs[i%appletStrs.length]);
  123.             }
  124.             getLine();
  125.         }
  126.         buttonToggle = true;
  127.     }
  128.     public String getLine() {
  129.         String str = null;
  130.         if (reader != null) {
  131.             try {
  132.                 if ((str = reader.readLine()) != null) {
  133.                     if (str.length() == 0) {
  134.                         str = " ";
  135.                     }
  136.                     vector.addElement(str);
  137.                 }
  138.             } catch (Exception e) { e.printStackTrace(); reader = null; }
  139.         } else {
  140.             if (appletVector.size() != 0) {
  141.                 vector.addElement(str = (String) appletVector.remove(0));
  142.             }
  143.         }
  144.         return str;
  145.     }
  146.     public void reset(int w, int h) {
  147.         for (int i = 0; i < animpts.length; i += 2) {
  148.             animpts[i + 0] = (float) (Math.random() * w);
  149.             animpts[i + 1] = (float) (Math.random() * h);
  150.             deltas[i + 0] = (float) (Math.random() * 6.0 + 4.0);
  151.             deltas[i + 1] = (float) (Math.random() * 6.0 + 4.0);
  152.             if (animpts[i + 0] > w / 2.0f) {
  153.                 deltas[i + 0] = -deltas[i + 0];
  154.             }
  155.             if (animpts[i + 1] > h / 2.0f) {
  156.                 deltas[i + 1] = -deltas[i + 1];
  157.             }
  158.         }
  159.         FontMetrics fm = getFontMetrics(font);
  160.         strH = fm.getAscent()+fm.getDescent();
  161.         nStrs = h/strH+1;
  162.         vector = new Vector(nStrs);
  163.         ix = (int) (Math.random() * (w - 80));
  164.         iy = (int) (Math.random() * (h - 80));
  165.     }
  166.     public void step(int w, int h) {
  167.         if (doText && vector.size() == 0) {
  168.             getFile();
  169.         }
  170.         if (doText) {
  171.             String s = getLine();
  172.             if (s == null || vector.size() == nStrs && vector.size() != 0) {
  173.                 vector.removeElementAt(0);
  174.             }
  175.             yy = (s == null) ? strH : h - ((vector.size()-1) * strH);
  176.         }
  177.        
  178.         for (int i = 0; i < animpts.length && doShape; i += 2) {
  179.             animate(animpts, deltas, i + 0, w);
  180.             animate(animpts, deltas, i + 1, h);
  181.         }
  182.         if (doImage && alphaDirection == UP) {
  183.             if ((alpha += 0.025) > .99) {
  184.                 alphaDirection = DOWN;
  185.                 alpha = 1.0f;
  186.             }
  187.         } else if (doImage && alphaDirection == DOWN) {
  188.             if ((alpha -= .02) < 0.01) {
  189.                 alphaDirection = UP;
  190.                 alpha = 0;
  191.                 ix = (int) (Math.random() * (w - 80));
  192.                 iy = (int) (Math.random() * (h - 80));
  193.             }
  194.         }
  195.         if (doImage) {
  196.             if ((imgX += 80) == 800) {
  197.                 imgX = 0;
  198.             }
  199.         }
  200.     }
  201.     public void drawDemo(int w, int h, Graphics2D g2) {
  202.         if (doText) {
  203.             g2.setColor(Color.lightGray);
  204.             g2.setFont(font);
  205.             float y = yy;
  206.             for (int i = 0; i < vector.size(); i++) {
  207.                 g2.drawString((String)vector.get(i), 1, y);
  208.                 y += strH;
  209.             }
  210.         }
  211.         if (doShape) {
  212.             float[] ctrlpts = animpts;
  213.             int len = ctrlpts.length;
  214.             float prevx = ctrlpts[len - 2];
  215.             float prevy = ctrlpts[len - 1];
  216.             float curx = ctrlpts[0];
  217.             float cury = ctrlpts[1];
  218.             float midx = (curx + prevx) / 2.0f;
  219.             float midy = (cury + prevy) / 2.0f;
  220.             GeneralPath gp = new GeneralPath(GeneralPath.WIND_NON_ZERO);
  221.             gp.moveTo(midx, midy);
  222.             for (int i = 2; i <= ctrlpts.length; i += 2) {
  223.                 float x1 = (midx + curx) / 2.0f;
  224.                 float y1 = (midy + cury) / 2.0f;
  225.                 prevx = curx;
  226.                 prevy = cury;
  227.                 if (i < ctrlpts.length) {
  228.                     curx = ctrlpts[i + 0];
  229.                     cury = ctrlpts[i + 1];
  230.                 } else {
  231.                     curx = ctrlpts[0];
  232.                     cury = ctrlpts[1];
  233.                 }
  234.                 midx = (curx + prevx) / 2.0f;
  235.                 midy = (cury + prevy) / 2.0f;
  236.                 float x2 = (prevx + midx) / 2.0f;
  237.                 float y2 = (prevy + midy) / 2.0f;
  238.                 gp.curveTo(x1, y1, x2, y2, midx, midy);
  239.             }
  240.             gp.closePath();
  241.             g2.setColor(blueBlend);
  242.             g2.setStroke(bs);
  243.             g2.draw(gp);
  244.             g2.setColor(greenBlend);
  245.             g2.fill(gp);
  246.             PathIterator pi = gp.getPathIterator(null);
  247.             float pts[] = new float[6];
  248.             while ( !pi.isDone() ) {
  249.                 if (pi.currentSegment(pts) == pi.SEG_CUBICTO) {
  250.                     g2.drawImage(hotj_img, (int) pts[0], (int) pts[1], this);
  251.                 }
  252.                 pi.next();
  253.             }
  254.         }
  255.         if (doImage) {
  256.             AlphaComposite ac = AlphaComposite.getInstance(
  257.                                    AlphaComposite.SRC_OVER, alpha);
  258.             g2.setComposite(ac);
  259.             g2.drawImage(img.getSubimage(imgX,0,80,80), ix, iy, this);
  260.         }
  261.     }
  262.     public static void main(String argv[]) {
  263.         final DemoPanel dp = new DemoPanel(new BezierScroller());
  264.         Frame f = new Frame("Java2D Demo - BezierScroller");
  265.         f.addWindowListener(new WindowAdapter() {
  266.             public void windowClosing(WindowEvent e) {System.exit(0);}
  267.             public void windowDeiconified(WindowEvent e) { 
  268.                 dp.surface.start(); 
  269.             }
  270.             public void windowIconified(WindowEvent e) { 
  271.                 dp.surface.stop(); 
  272.             }
  273.         });
  274.         f.add("Center", dp);
  275.         f.pack();
  276.         f.setSize(new Dimension(400,300));
  277.         f.show();
  278.         dp.surface.start();
  279.     }
  280.     static class DemoControls extends JPanel implements ActionListener, Runnable {
  281.         BezierScroller demo;
  282.         JToolBar toolbar;
  283.         JComboBox combo;
  284.         Thread thread;
  285.         public DemoControls(BezierScroller demo) {
  286.             this.demo = demo;
  287.             setBackground(Color.gray);
  288.             add(toolbar = new JToolBar());
  289.             toolbar.setFloatable(false);
  290.             addTool("Image", false);
  291.             addTool("Shape", true);
  292.             addTool("Text", true);
  293.             addMouseListener(new MouseAdapter() {
  294.                 public void mouseClicked(MouseEvent e) {
  295.                     if (thread == null) start(); else stop();
  296.                 }
  297.             });
  298.         }
  299.         public void addTool(String str, boolean state) {
  300.             JButton b = (JButton) toolbar.add(new JButton(str));
  301.             b.setBackground(state ? Color.green : Color.lightGray);
  302.             b.setSelected(state);
  303.             b.addActionListener(this);
  304.         }
  305.         public void actionPerformed(ActionEvent e) {
  306.             JButton b = (JButton) e.getSource();
  307.             b.setSelected(!b.isSelected());
  308.             b.setBackground(b.isSelected() ? Color.green : Color.lightGray);
  309.             if (b.getText().equals("Image")) {
  310.                 demo.doImage = b.isSelected();
  311.             } else if (b.getText().equals("Shape")) {
  312.                 demo.doShape = b.isSelected();
  313.             } else {
  314.                 demo.doText = b.isSelected();
  315.             }
  316.             if (demo.thread == null) {
  317.                 demo.repaint();
  318.             }
  319.         }
  320.         public Dimension getPreferredSize() {
  321.             return new Dimension(200,37);
  322.         }
  323.         public void start() {
  324.             if (thread != null) {
  325.                 return;
  326.             }
  327.             thread = new Thread(this);
  328.             thread.setPriority(Thread.MIN_PRIORITY);
  329.             thread.setName("Mix.BezierScroller DemoControls Thread");
  330.             thread.start();
  331.         }
  332.         public synchronized void stop() {
  333.             if (thread != null) {
  334.                 thread.interrupt();
  335.             }
  336.             thread = null;
  337.             notifyAll();
  338.         }
  339.         public void run() {
  340.             Thread me = Thread.currentThread();
  341.             int i = 0;
  342.             while (thread == me) {
  343.                 try {
  344.                     thread.sleep(250);
  345.                 } catch (InterruptedException e) { return; }
  346.                 if (demo.buttonToggle) {
  347.                     ((JButton) toolbar.getComponentAtIndex(i++%2)).doClick();
  348.                     demo.buttonToggle = false;
  349.                 }
  350.             }
  351.             thread = null;
  352.         }
  353.     } // End DemoControls
  354. } // End BezierScroller