KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java2d > Java2Demo


1 /*
2  * @(#)Java2Demo.java 1.50 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  * @(#)Java2Demo.java 1.50 06/08/29
39  */

40
41
42 package java2d;
43
44 import java.awt.*;
45 import java.awt.event.*;
46 import java.awt.font.TextLayout JavaDoc;
47 import java.awt.font.FontRenderContext JavaDoc;
48 import javax.swing.*;
49 import javax.swing.border.*;
50
51 import static java2d.CustomControlsContext.State.*;
52
53
54 /**
55  * A demo that shows Java 2D(TM) features.
56  *
57  * @version @(#)Java2Demo.java 1.33 99/08/16
58  * @author Brian Lichtenwalter (Framework, Intro, demos)
59  * @author Jim Graham (demos)
60  */

61 public class Java2Demo extends JPanel implements ItemListener, ActionListener
62 {
63
64     static Java2Demo demo;
65     static GlobalControls controls;
66     static MemoryMonitor memorymonitor;
67     static PerformanceMonitor performancemonitor;
68     static JTabbedPane tabbedPane;
69     static JLabel progressLabel;
70     static JProgressBar progressBar;
71     static DemoGroup group[];
72     static JCheckBoxMenuItem verboseCB;
73     static JCheckBoxMenuItem ccthreadCB;
74     static JCheckBoxMenuItem printCB = new JCheckBoxMenuItem("Default Printer");
75     static Color backgroundColor;
76     static JCheckBoxMenuItem memoryCB, perfCB;
77     static Intro intro;
78     static String JavaDoc[][] demos =
79     {
80         {"Arcs_Curves", "Arcs", "BezierAnim", "Curves", "Ellipses"},
81         {"Clipping", "Areas", "ClipAnim", "Intersection", "Text"},
82         {"Colors", "BullsEye", "ColorConvert", "Rotator3D"},
83         {"Composite", "ACimages", "ACrules", "FadeAnim"},
84         {"Fonts", "AttributedStr", "Highlighting", "Outline", "Tree"},
85         {"Images", "DukeAnim", "ImageOps", "JPEGFlip", "WarpImage"},
86         {"Lines", "Caps", "Dash", "Joins", "LineAnim"},
87         {"Mix", "Balls", "BezierScroller", "Stars3D"},
88         {"Paint", "GradAnim", "Gradient", "Texture", "TextureAnim"},
89         {"Paths", "Append", "CurveQuadTo", "FillStroke", "WindingRule"},
90         {"Transforms", "Rotate", "SelectTx", "TransformAnim"}
91     };
92
93     private JCheckBoxMenuItem controlsCB;
94     private JMenuItem runMI, cloneMI, fileMI, backgMI;
95     private JMenuItem ccthreadMI, verboseMI;
96     private RunWindow runwindow;
97     private CloningFeature cloningfeature;
98     private JFrame rf, cf;
99     private GlobalPanel gp;
100
101
102
103     /**
104      * Construct the Java2D Demo.
105      */

106     public Java2Demo() {
107
108         setLayout(new BorderLayout());
109         setBorder(new EtchedBorder());
110
111         add(createMenuBar(), BorderLayout.NORTH);
112
113         // hard coding 14 = 11 demo dirs + images + fonts + Intro
114
progressBar.setMaximum(13);
115         progressLabel.setText("Loading images");
116         new DemoImages();
117         progressBar.setValue(progressBar.getValue() + 1);
118         progressLabel.setText("Loading fonts");
119         new DemoFonts();
120         progressBar.setValue(progressBar.getValue() + 1);
121         progressLabel.setText("Loading Intro");
122         intro = new Intro();
123         progressBar.setValue(progressBar.getValue() + 1);
124         UIManager.put("Button.margin", new Insets(0,0,0,0));
125        
126         controls = new GlobalControls();
127         memorymonitor = new MemoryMonitor();
128         performancemonitor = new PerformanceMonitor();
129
130         GlobalPanel gp = new GlobalPanel();
131
132         tabbedPane = new JTabbedPane();
133         tabbedPane.setFont(new Font("serif", Font.PLAIN, 12));
134         tabbedPane.addTab("", new J2DIcon(), gp);
135         tabbedPane.addChangeListener(gp);
136
137         group = new DemoGroup[demos.length];
138         for (int i = 0; i < demos.length; i++) {
139             progressLabel.setText("Loading demos." + demos[i][0]);
140             group[i] = new DemoGroup(demos[i][0]);
141             tabbedPane.addTab(demos[i][0], null);
142             progressBar.setValue(progressBar.getValue() + 1);
143         }
144
145         add(tabbedPane, BorderLayout.CENTER);
146     }
147
148  
149     private JMenuBar createMenuBar() {
150
151         JPopupMenu.setDefaultLightWeightPopupEnabled(false);
152         JMenuBar menuBar = new JMenuBar();
153
154         if (Java2DemoApplet.applet == null) {
155             JMenu file = (JMenu) menuBar.add(new JMenu("File"));
156             fileMI = (JMenuItem) file.add(new JMenuItem("Exit"));
157             fileMI.addActionListener(this);
158         }
159
160         JMenu options = (JMenu) menuBar.add(new JMenu("Options"));
161
162         controlsCB = (JCheckBoxMenuItem) options.add(
163                 new JCheckBoxMenuItem("Global Controls", true));
164         controlsCB.addItemListener(this);
165
166         memoryCB = (JCheckBoxMenuItem) options.add(
167                 new JCheckBoxMenuItem("Memory Monitor", true));
168         memoryCB.addItemListener(this);
169
170         perfCB = (JCheckBoxMenuItem) options.add(
171                 new JCheckBoxMenuItem("Performance Monitor", true));
172         perfCB.addItemListener(this);
173
174         options.add(new JSeparator());
175
176         ccthreadCB = (JCheckBoxMenuItem) options.add(
177                 new JCheckBoxMenuItem("Custom Controls Thread"));
178         ccthreadCB.addItemListener(this);
179
180         printCB = (JCheckBoxMenuItem) options.add(printCB);
181
182         verboseCB = (JCheckBoxMenuItem) options.add(
183                 new JCheckBoxMenuItem("Verbose"));
184
185         options.add(new JSeparator());
186
187         backgMI = (JMenuItem) options.add(new JMenuItem("Background Color"));
188     backgMI.addActionListener(this);
189
190         runMI = (JMenuItem) options.add(new JMenuItem("Run Window"));
191         runMI.addActionListener(this);
192
193         cloneMI = (JMenuItem) options.add(new JMenuItem("Cloning Feature"));
194         cloneMI.addActionListener(this);
195
196         return menuBar;
197     }
198
199
200     public void createRunWindow() {
201         if (rf != null) {
202             rf.toFront();
203             return;
204         }
205         runwindow = new RunWindow();
206         WindowListener l = new WindowAdapter() {
207             public void windowClosing(WindowEvent e) {
208                 runwindow.stop(); rf.dispose();
209             }
210             public void windowClosed(WindowEvent e) {
211                 rf = null;
212             }
213         };
214         rf = new JFrame("Run");
215         rf.addWindowListener(l);
216         rf.getContentPane().add("Center", runwindow);
217         rf.pack();
218         if (Java2DemoApplet.applet == null) {
219             rf.setSize(new Dimension(200,125));
220         } else {
221             rf.setSize(new Dimension(200,150));
222         }
223         rf.setVisible(true);
224     }
225
226
227     public void startRunWindow() {
228         SwingUtilities.invokeLater(new Runnable JavaDoc() {
229             public void run() {
230                 runwindow.doRunAction();
231             }
232         });
233     }
234
235
236     public void actionPerformed(ActionEvent e) {
237         if (e.getSource().equals(fileMI)) {
238             System.exit(0);
239         } else if (e.getSource().equals(runMI)) {
240             createRunWindow();
241         } else if (e.getSource().equals(cloneMI)) {
242             if (cloningfeature == null) {
243                 cloningfeature = new CloningFeature();
244                 WindowListener l = new WindowAdapter() {
245                     public void windowClosing(WindowEvent e) {
246                         cloningfeature.stop(); cf.dispose();
247                     }
248                     public void windowClosed(WindowEvent e) {
249                         cloningfeature = null;
250                     }
251                 };
252                 cf = new JFrame("Cloning Demo");
253                 cf.addWindowListener(l);
254                 cf.getContentPane().add("Center", cloningfeature);
255                 cf.pack();
256                 cf.setSize(new Dimension(320,330));
257                 cf.setVisible(true);
258             } else {
259                 cf.toFront();
260             }
261         } else if (e.getSource().equals(backgMI)) {
262         backgroundColor =
263                 JColorChooser.showDialog(this, "Background Color", Color.white);
264             for (int i = 1; i < tabbedPane.getTabCount(); i++) {
265                 JPanel p = group[i-1].getPanel();
266                 for (int j = 0; j < p.getComponentCount(); j++) {
267                     DemoPanel dp = (DemoPanel) p.getComponent(j);
268                     if (dp.surface != null) {
269                         dp.surface.setBackground(backgroundColor);
270                     }
271                 }
272             }
273         }
274     }
275
276
277     public void itemStateChanged(ItemEvent e) {
278         if (e.getSource().equals(controlsCB)) {
279             boolean newVisibility = !controls.isVisible();
280             controls.setVisible(newVisibility);
281             for (Component cmp : controls.texturechooser.getComponents()) {
282                 cmp.setVisible(newVisibility);
283             }
284         } else if (e.getSource().equals(memoryCB)) {
285             if (memorymonitor.isVisible()) {
286                 memorymonitor.setVisible(false);
287                 memorymonitor.surf.setVisible(false);
288                 memorymonitor.surf.stop();
289             } else {
290                 memorymonitor.setVisible(true);
291                 memorymonitor.surf.setVisible(true);
292                 memorymonitor.surf.start();
293             }
294         } else if (e.getSource().equals(perfCB)) {
295             if (performancemonitor.isVisible()) {
296                 performancemonitor.setVisible(false);
297                 performancemonitor.surf.setVisible(false);
298                 performancemonitor.surf.stop();
299             } else {
300                 performancemonitor.setVisible(true);
301                 performancemonitor.surf.setVisible(true);
302                 performancemonitor.surf.start();
303             }
304         } else if (e.getSource().equals(ccthreadCB)) {
305             CustomControlsContext.State state =
306                 ccthreadCB.isSelected() ? START : STOP;
307             if (tabbedPane.getSelectedIndex() != 0) {
308                 JPanel p = group[tabbedPane.getSelectedIndex()-1].getPanel();
309                 for (int i = 0; i < p.getComponentCount(); i++) {
310                     DemoPanel dp = (DemoPanel) p.getComponent(i);
311                     if (dp.ccc != null) {
312                         dp.ccc.handleThread(state);
313                     }
314                 }
315             }
316         }
317         revalidate();
318     }
319
320
321     public void start() {
322         if (tabbedPane.getSelectedIndex() == 0) {
323             intro.start();
324         } else {
325             group[tabbedPane.getSelectedIndex()-1].setup(false);
326             if (memorymonitor.surf.thread == null && memoryCB.getState()) {
327                 memorymonitor.surf.start();
328             }
329             if (performancemonitor.surf.thread == null && perfCB.getState()) {
330                 performancemonitor.surf.start();
331             }
332         }
333     }
334
335
336     public void stop() {
337         if (tabbedPane.getSelectedIndex() == 0) {
338             intro.stop();
339         } else {
340             memorymonitor.surf.stop();
341             performancemonitor.surf.stop();
342             int i = tabbedPane.getSelectedIndex()-1;
343             group[i].shutDown(group[i].getPanel());
344         }
345     }
346
347
348     static void addToGridBag(JPanel panel, Component comp,
349             int x, int y, int w, int h, double weightx, double weighty) {
350
351         GridBagLayout gbl = (GridBagLayout) panel.getLayout();
352         GridBagConstraints c = new GridBagConstraints();
353         c.fill = GridBagConstraints.BOTH;
354         c.gridx = x;
355         c.gridy = y;
356         c.gridwidth = w;
357         c.gridheight = h;
358         c.weightx = weightx;
359         c.weighty = weighty;
360         panel.add(comp);
361         gbl.setConstraints(comp, c);
362     }
363
364
365     /**
366      * The Icon for the Intro tab.
367      */

368     static class J2DIcon implements Icon {
369
370         private static Color myBlue = new Color(94, 105, 176);
371         private static Color myBlack = new Color(20, 20, 20);
372         private static Font font = new Font("serif", Font.BOLD, 12);
373         private FontRenderContext JavaDoc frc = new FontRenderContext JavaDoc(null,true,true);
374         private TextLayout JavaDoc tl = new TextLayout JavaDoc("Java2D", font, frc);
375
376         public void paintIcon(Component c, Graphics g, int x, int y ) {
377             Graphics2D g2 = (Graphics2D) g;
378             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
379                                 RenderingHints.VALUE_ANTIALIAS_ON);
380             g2.setFont(font);
381             if (tabbedPane.getSelectedIndex() == 0) {
382                 g2.setColor(myBlue);
383             } else {
384                 g2.setColor(myBlack);
385             }
386             tl.draw(g2, x, y + 15);
387         }
388
389         public int getIconWidth() {
390             return 40;
391         }
392
393         public int getIconHeight() {
394             return 22;
395         }
396     }
397
398
399
400     public static void main(String JavaDoc args[]) {
401         for (int i = 0; i < args.length; i++) {
402             if (args[i].startsWith("-h") || args[i].startsWith("-help")) {
403                 String JavaDoc s = "\njava -jar Java2Demo.jar -runs=5 -delay=5 -screen=5 " +
404                            "-antialias=true -rendering=true -texture=true " +
405                            "-composite=true -verbose -print -columns=3 " +
406                            "-buffers=5,10 -ccthread -zoom -maxscreen \n";
407                 System.out.println(s);
408                 s = " -runs=5 Number of runs to execute\n" +
409                     " -delay=5 Sleep amount between tabs\n" +
410                     " -antialias= true or false for antialiasing\n" +
411                     " -rendering= true or false for quality or speed\n" +
412                     " -texture= true or false for texturing\n" +
413                     " -composite= true or false for compositing\n" +
414                     " -verbose output Surface graphic states \n" +
415                     " -print during run print the Surface, " +
416                     "use the Default Printer\n" +
417                     " -columns=3 # of columns to use in clone layout \n" +
418                     " -screen=3 demos all use this screen type \n" +
419                     " -buffers=5,10 during run - clone to see screens " +
420                     "five through ten\n" +
421                     " -ccthread Invoke the Custom Controls Thread \n" +
422                     " -zoom mouseClick on surface for zoom in \n" +
423                     " -maxscreen take up the entire monitor screen \n";
424                 System.out.println(s);
425                 s = "Examples : \n" +
426                     " Print all of the demos : \n" +
427                     " java -jar Java2Demo.jar -runs=1 -delay=60 -print \n" +
428                     " Run zoomed in with custom control thread \n" +
429                     " java -jar Java2Demo.jar -runs=10 -zoom -ccthread\n";
430                 System.out.println(s);
431                 System.exit(0);
432             } else if (args[i].startsWith("-delay=")) {
433                 String JavaDoc s = args[i].substring(args[i].indexOf('=')+1);
434                 RunWindow.delay = Integer.parseInt(s);
435             }
436         }
437
438         JFrame frame = new JFrame("Java 2D(TM) Demo");
439         frame.getAccessibleContext().setAccessibleDescription("A sample application to demonstrate Java2D features");
440         int WIDTH = 400, HEIGHT = 200;
441         frame.setSize(WIDTH, HEIGHT);
442         Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
443         frame.setLocation(d.width/2 - WIDTH/2, d.height/2 - HEIGHT/2);
444         frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
445         frame.addWindowListener(new WindowAdapter() {
446             public void windowClosing(WindowEvent e) {System.exit(0);}
447             public void windowDeiconified(WindowEvent e) {
448                 if (demo != null) { demo.start(); }
449             }
450             public void windowIconified(WindowEvent e) {
451                 if (demo != null) { demo.stop(); }
452             }
453         });
454         JOptionPane.setRootFrame(frame);
455
456         JPanel progressPanel = new JPanel() {
457             public Insets getInsets() {
458                 return new Insets(40,30,20,30);
459             }
460         };
461         progressPanel.setLayout(new BoxLayout(progressPanel, BoxLayout.Y_AXIS));
462         frame.getContentPane().add(progressPanel, BorderLayout.CENTER);
463
464         Dimension labelSize = new Dimension(400, 20);
465         progressLabel = new JLabel("Loading, please wait...");
466         progressLabel.setAlignmentX(CENTER_ALIGNMENT);
467         progressLabel.setMaximumSize(labelSize);
468         progressLabel.setPreferredSize(labelSize);
469         progressPanel.add(progressLabel);
470         progressPanel.add(Box.createRigidArea(new Dimension(1,20)));
471
472         progressBar = new JProgressBar();
473         progressBar.setStringPainted(true);
474         progressLabel.setLabelFor(progressBar);
475         progressBar.setAlignmentX(CENTER_ALIGNMENT);
476         progressBar.setMinimum(0);
477         progressBar.setValue(0);
478         progressBar.getAccessibleContext().setAccessibleName("Java2D loading progress");
479         progressPanel.add(progressBar);
480
481         frame.setVisible(true);
482
483         demo = new Java2Demo();
484
485         frame.getContentPane().removeAll();
486         frame.getContentPane().setLayout(new BorderLayout());
487         frame.getContentPane().add(demo, BorderLayout.CENTER);
488         WIDTH = 730; HEIGHT = 570;
489         frame.setLocation(d.width/2 - WIDTH/2, d.height/2 - HEIGHT/2);
490         frame.setSize(WIDTH, HEIGHT);
491         frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
492
493         for (int i = 0; i < args.length; i++) {
494             String JavaDoc arg = args[i];
495             String JavaDoc s = arg.substring(arg.indexOf('=')+1);
496             if (arg.startsWith("-runs=")) {
497                 RunWindow.numRuns = Integer.parseInt(s);
498                 RunWindow.exit = true;
499                 demo.createRunWindow();
500             } else if (arg.startsWith("-screen=")) {
501                 demo.controls.screenCombo.setSelectedIndex(Integer.parseInt(s));
502             } else if (arg.startsWith("-antialias=")) {
503                 demo.controls.aliasCB.setSelected(s.endsWith("true"));
504             } else if (arg.startsWith("-rendering=")) {
505                 demo.controls.renderCB.setSelected(s.endsWith("true"));
506             } else if (arg.startsWith("-texture=")) {
507                 demo.controls.textureCB.setSelected(s.endsWith("true"));
508             } else if (arg.startsWith("-composite=")) {
509                 demo.controls.compositeCB.setSelected(s.endsWith("true"));
510             } else if (arg.startsWith("-verbose")) {
511                 demo.verboseCB.setSelected(true);
512             } else if (arg.startsWith("-print")) {
513                 demo.printCB.setSelected(true);
514                 RunWindow.printCB.setSelected(true);
515             } else if (arg.startsWith("-columns=")) {
516                 DemoGroup.columns = Integer.parseInt(s);
517             } else if (arg.startsWith("-buffers=")) {
518                 // usage -buffers=3,10
519
RunWindow.buffersFlag = true;
520                 int i1 = arg.indexOf('=')+1;
521                 int i2 = arg.indexOf(',');
522                 String JavaDoc s1 = arg.substring(i1, i2);
523                 RunWindow.bufBeg = Integer.parseInt(s1);
524                 s1 = arg.substring(i2+1, arg.length());
525                 RunWindow.bufEnd = Integer.parseInt(s1);
526             } else if (arg.startsWith("-ccthread")) {
527                 demo.ccthreadCB.setSelected(true);
528             } else if (arg.startsWith("-zoom")) {
529                 RunWindow.zoomCB.setSelected(true);
530             } else if (arg.startsWith("-maxscreen")) {
531                 frame.setLocation(0, 0);
532                 frame.setSize(d.width, d.height);
533             }
534         }
535
536         frame.validate();
537         frame.repaint();
538         frame.getFocusTraversalPolicy()
539              .getDefaultComponent(frame)
540              .requestFocus();
541         demo.start();
542
543         if (RunWindow.exit) {
544             demo.startRunWindow();
545         }
546     }
547 }
548
Popular Tags