KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java2d > demos > Mix > BezierScroller


1 /*
2  * @(#)BezierScroller.java 1.43 06/08/29
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)BezierScroller.java 1.43 06/08/29
39  */

40
41 package java2d.demos.Mix;
42
43 import static java.awt.Color JavaDoc.*;
44 import java.awt.*;
45 import java.awt.event.*;
46 import java.awt.geom.GeneralPath JavaDoc;
47 import java.awt.geom.PathIterator JavaDoc;
48 import java.awt.font.FontRenderContext JavaDoc;
49 import java.awt.font.TextLayout JavaDoc;
50 import java.awt.image.BufferedImage JavaDoc;
51 import java.io.File JavaDoc;
52 import java.io.FileReader JavaDoc;
53 import java.io.BufferedReader JavaDoc;
54 import java.util.Vector JavaDoc;
55 import javax.swing.*;
56 import java2d.AnimatingControlsSurface;
57 import java2d.CustomControls;
58
59 import static java.lang.Math.random JavaDoc;
60
61
62 /**
63  * Animated Bezier Curve shape with images at the control points.
64  * README.txt file scrolling up. Composited Image fading in and out.
65  */

66 public class BezierScroller extends AnimatingControlsSurface {
67
68     private static String JavaDoc appletStrs[] =
69         { " ", "Java2Demo",
70            "BezierScroller - Animated Bezier Curve shape with images",
71            "For README.txt file scrolling run in application mode", " " };
72     private static final int NUMPTS = 6;
73     private static Color JavaDoc greenBlend = new Color JavaDoc(0, 255, 0, 100);
74     private static Color JavaDoc blueBlend = new Color JavaDoc(0, 0, 255, 100);
75     private static Font font = new Font("serif", Font.PLAIN, 12);
76     private static BasicStroke bs = new BasicStroke(3.0f);
77     private static Image JavaDoc hotj_img;
78     private static BufferedImage JavaDoc img;
79     private static final int UP = 0;
80     private static final int DOWN = 1;
81
82     private float animpts[] = new float[NUMPTS * 2];
83     private float deltas[] = new float[NUMPTS * 2];
84     private BufferedReader JavaDoc reader;
85     private int nStrs;
86     private int strH;
87     private int yy, ix, iy, imgX;
88     private Vector JavaDoc vector, appletVector;
89     private float alpha = 0.2f;
90     private int alphaDirection;
91     protected boolean doImage, doShape, doText;
92     protected boolean buttonToggle;
93
94
95     public BezierScroller() {
96         setBackground(WHITE);
97         doShape = doText = true;
98         hotj_img = getImage("java-logo.gif");
99         Image JavaDoc image = getImage("jumptojavastrip.png");
100         int iw = image.getWidth(this);
101         int ih = image.getHeight(this);
102         img = new BufferedImage JavaDoc(iw, ih, BufferedImage.TYPE_INT_RGB);
103         img.createGraphics().drawImage(image, 0, 0, this);
104         setControls(new Component[] { new DemoControls(this) });
105     }
106
107
108     public void animate(float[] pts, float[] deltas, int index, int limit) {
109         float newpt = pts[index] + deltas[index];
110         if (newpt <= 0) {
111             newpt = -newpt;
112             deltas[index] = (float) (random() * 4.0 + 2.0);
113         } else if (newpt >= (float) limit) {
114             newpt = 2.0f * limit - newpt;
115             deltas[index] = - (float) (random() * 4.0 + 2.0);
116         }
117         pts[index] = newpt;
118     }
119
120
121     public void getFile() {
122         try {
123             String JavaDoc fName = "README.txt";
124             if ((reader = new BufferedReader JavaDoc(new FileReader JavaDoc(fName))) != null) {
125                 getLine();
126             }
127         } catch (Exception JavaDoc e) { reader = null; }
128         if (reader == null) {
129             appletVector = new Vector JavaDoc(100);
130             for (int i = 0; i < 100; i++) {
131                 appletVector.addElement(appletStrs[i%appletStrs.length]);
132             }
133             getLine();
134         }
135         buttonToggle = true;
136     }
137
138
139     public String JavaDoc getLine() {
140         String JavaDoc str = null;
141         if (reader != null) {
142             try {
143                 if ((str = reader.readLine()) != null) {
144                     if (str.length() == 0) {
145                         str = " ";
146                     }
147                     vector.addElement(str);
148                 }
149             } catch (Exception JavaDoc e) { e.printStackTrace(); reader = null; }
150         } else {
151             if (appletVector.size() != 0) {
152                 vector.addElement(str = (String JavaDoc) appletVector.remove(0));
153             }
154         }
155         return str;
156     }
157
158
159     public void reset(int w, int h) {
160         for (int i = 0; i < animpts.length; i += 2) {
161             animpts[i + 0] = (float) (random() * w);
162             animpts[i + 1] = (float) (random() * h);
163              deltas[i + 0] = (float) (random() * 6.0 + 4.0);
164              deltas[i + 1] = (float) (random() * 6.0 + 4.0);
165             if (animpts[i + 0] > w / 2.0f) {
166                 deltas[i + 0] = -deltas[i + 0];
167             }
168             if (animpts[i + 1] > h / 2.0f) {
169                 deltas[i + 1] = -deltas[i + 1];
170             }
171         }
172         FontMetrics fm = getFontMetrics(font);
173         strH = fm.getAscent()+fm.getDescent();
174         nStrs = h/strH+2;
175         vector = new Vector JavaDoc(nStrs);
176         ix = (int) (random() * (w - 80));
177         iy = (int) (random() * (h - 80));
178     }
179
180
181     public void step(int w, int h) {
182         if (doText && vector.size() == 0) {
183             getFile();
184         }
185         if (doText) {
186             String JavaDoc s = getLine();
187             if (s == null || vector.size() == nStrs && vector.size() != 0) {
188                 vector.removeElementAt(0);
189             }
190             yy = (s == null) ? 0 : h - vector.size() * strH;
191         }
192        
193         for (int i = 0; i < animpts.length && doShape; i += 2) {
194             animate(animpts, deltas, i + 0, w);
195             animate(animpts, deltas, i + 1, h);
196         }
197         if (doImage && alphaDirection == UP) {
198             if ((alpha += 0.025) > .99) {
199                 alphaDirection = DOWN;
200                 alpha = 1.0f;
201             }
202         } else if (doImage && alphaDirection == DOWN) {
203             if ((alpha -= .02) < 0.01) {
204                 alphaDirection = UP;
205                 alpha = 0;
206                 ix = (int) (random() * (w - 80));
207                 iy = (int) (random() * (h - 80));
208             }
209         }
210         if (doImage) {
211             if ((imgX += 80) == 800) {
212                 imgX = 0;
213             }
214         }
215     }
216
217
218
219     public void render(int w, int h, Graphics2D g2) {
220
221         if (doText) {
222             g2.setColor(LIGHT_GRAY);
223             g2.setFont(font);
224             float y = yy;
225             for (int i = 0; i < vector.size(); i++) {
226                 g2.drawString((String JavaDoc)vector.get(i), 1, y += strH);
227             }
228         }
229
230         if (doShape) {
231             float[] ctrlpts = animpts;
232             int len = ctrlpts.length;
233             float prevx = ctrlpts[len - 2];
234             float prevy = ctrlpts[len - 1];
235             float curx = ctrlpts[0];
236             float cury = ctrlpts[1];
237             float midx = (curx + prevx) / 2.0f;
238             float midy = (cury + prevy) / 2.0f;
239             GeneralPath JavaDoc gp = new GeneralPath JavaDoc(GeneralPath.WIND_NON_ZERO);
240             gp.moveTo(midx, midy);
241             for (int i = 2; i <= ctrlpts.length; i += 2) {
242                 float x1 = (midx + curx) / 2.0f;
243                 float y1 = (midy + cury) / 2.0f;
244                 prevx = curx;
245                 prevy = cury;
246                 if (i < ctrlpts.length) {
247                     curx = ctrlpts[i + 0];
248                     cury = ctrlpts[i + 1];
249                 } else {
250                     curx = ctrlpts[0];
251                     cury = ctrlpts[1];
252                 }
253                 midx = (curx + prevx) / 2.0f;
254                 midy = (cury + prevy) / 2.0f;
255                 float x2 = (prevx + midx) / 2.0f;
256                 float y2 = (prevy + midy) / 2.0f;
257                 gp.curveTo(x1, y1, x2, y2, midx, midy);
258             }
259             gp.closePath();
260
261             g2.setColor(blueBlend);
262             g2.setStroke(bs);
263             g2.draw(gp);
264             g2.setColor(greenBlend);
265             g2.fill(gp);
266
267             PathIterator JavaDoc pi = gp.getPathIterator(null);
268             float pts[] = new float[6];
269             while ( !pi.isDone() ) {
270                 if (pi.currentSegment(pts) == pi.SEG_CUBICTO) {
271                     g2.drawImage(hotj_img, (int) pts[0], (int) pts[1], this);
272                 }
273                 pi.next();
274             }
275         }
276
277         if (doImage) {
278             AlphaComposite ac = AlphaComposite.getInstance(
279                                    AlphaComposite.SRC_OVER, alpha);
280             g2.setComposite(ac);
281             g2.drawImage(img.getSubimage(imgX,0,80,80), ix, iy, this);
282         }
283     }
284
285
286     public static void main(String JavaDoc argv[]) {
287         createDemoFrame(new BezierScroller());
288     }
289
290
291     static class DemoControls extends CustomControls implements ActionListener {
292
293         BezierScroller demo;
294         JToolBar toolbar;
295         JComboBox combo;
296
297         public DemoControls(BezierScroller demo) {
298             super(demo.name);
299             this.demo = demo;
300             add(toolbar = new JToolBar());
301             toolbar.setFloatable(false);
302             addTool("Image", false);
303             addTool("Shape", true);
304             addTool("Text", true);
305         }
306
307
308         public void addTool(String JavaDoc str, boolean state) {
309             JToggleButton b = (JToggleButton) toolbar.add(new JToggleButton(str));
310             b.setFocusPainted(false);
311             b.setSelected(state);
312             b.addActionListener(this);
313             int width = b.getPreferredSize().width;
314             Dimension prefSize = new Dimension(width, 21);
315             b.setPreferredSize(prefSize);
316             b.setMaximumSize(prefSize);
317             b.setMinimumSize(prefSize);
318         }
319
320
321         public void actionPerformed(ActionEvent e) {
322             JToggleButton b = (JToggleButton) e.getSource();
323             if (b.getText().equals("Image")) {
324                 demo.doImage = b.isSelected();
325             } else if (b.getText().equals("Shape")) {
326                 demo.doShape = b.isSelected();
327             } else {
328                 demo.doText = b.isSelected();
329             }
330             if (demo.animating.thread == null) {
331                 demo.repaint();
332             }
333         }
334
335         public Dimension getPreferredSize() {
336             return new Dimension(200,40);
337         }
338
339
340         public void run() {
341             Thread JavaDoc me = Thread.currentThread();
342             int i = 0;
343             while (thread == me) {
344                 try {
345                     thread.sleep(250);
346                 } catch (InterruptedException JavaDoc e) { return; }
347                 if (demo.buttonToggle) {
348                     ((AbstractButton) toolbar.getComponentAtIndex(i++%2)).doClick();
349                     demo.buttonToggle = false;
350                 }
351             }
352             thread = null;
353         }
354     } // End DemoControls
355
} // End BezierScroller
356
Popular Tags