Debian Codegraph @

src/com/jidesoft/icons/IconsFactory.java

raw
1 /*
2 * @(#)IconsFactory.java
3 *
4 * Copyright 2002 JIDE Software Inc. All rights reserved.
5 */
6 package com.jidesoft.icons;
7
8 import com.jidesoft.swing.JideSwingUtilities;
9 import com.jidesoft.utils.SecurityUtils;
10
11 import javax.imageio.ImageIO;
12 import javax.swing.*;
13 import java.awt.*;
14 import java.awt.geom.AffineTransform;
15 import java.awt.image.BufferedImage;
16 import java.io.*;
17 import java.lang.reflect.Field;
18 import java.net.URL;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.StringTokenizer;
22 import java.util.logging.Logger;
23
24 /**
25 * <code>IconsFactory</code> provides a consistent way to access icon resource in any application.
26 * <p>
27 * Any application usually need to access image files. One way to do it is to put those image files in the installation
28 * and access them use direct file access. However this is not a good way because you have to know the full path to the
29 * image file. So a better way that most Java applications take is to bundle the image files with in the jar and use
30 * class loader to load them.
31 * <p>
32 * For example, if a class Foo needs to access image files foo.gif and bar.png, we put the image files right below the
33 * source code under icons subfolder. See an example directory structure below.
34 * <pre>
35 * /src/com/jidesoft/Foo.java
36 * /icons/foo.gif
37 * /icons/bar.png
38 * </pre>
39 * When you compile the java class, you copy those images to class output directory like this.
40 * <pre>
41 * /classes/com/jidesoft/Foo.class
42 * /icons/foo.gif
43 * /icons/bar.png
44 * </pre>
45 * Notes:<i> In IntelliJ IDEA's "Compile" tab of "Project Property" dialog, there is a way to set "Resource Pattern".
46 * Here is the setting on my computer - "?*.properties;?*.xml;?*.html;?*.tree;?*.gif;?*.png;?*.jpeg;?*.jpg;?*.vm;?*.xsd;?*.ilayout;?*.gz;?*.txt"
47 * for your reference. If so, all your images will get copies automatically to class output folder. Although I haven't
48 * tried, I believe most Java IDEs have the same or similar feature. This feature will make the usage of IconsFactory
49 * much easier. </i>
50 * <p>
51 * If you setup directory structure as above, you can now use IconsFactory to access the images like this.
52 * <pre><code>
53 * ImageIcon icon = IconsFactory.get(Foo.class, "icons/foo.gif");
54 * </code></pre>
55 * IconsFactory will cache the icon for you. So next time if you get the same icon, it will get from cache instead of
56 * reading from disk again.
57 * <p>
58 * There are a few methods on IconsFactory to create difference variation from the original icon. For example, {@link
59 * #getDisabledImageIcon(Class, String)} will get the image icon with disabled effect.
60 * <p>
61 * We also suggest you to use the template below to create a number of IconsFactory classes in your application. The
62 * idea is that you should have one for each functional area so that all your image files can be grouped into each
63 * functional area. All images used in that functional area should be put under the folder where this IconsFactory is.
64 * Here is an template.
65 * <pre><code>
66 * class TemplateIconsFactory {
67 * public static class Group1 {
68 * public static final String IMAGE1 = "icons/image11.png";
69 * public static final String IMAGE2 = "icons/image12.png";
70 * public static final String IMAGE3 = "icons/image13.png";
71 * }
72 * <p>
73 * public static class Group2 {
74 * public static final String IMAGE1 = "icons/image21.png";
75 * public static final String IMAGE2 = "icons/image22.png";
76 * public static final String IMAGE3 = "icons/image23.png";
77 * }
78 * <p>
79 * public static ImageIcon getImageIcon(String name) {
80 * if (name != null)
81 * return IconsFactory.getImageIcon(TemplateIconsFactory.class, name);
82 * else
83 * return null;
84 * }
85 * <p>
86 * public static void main(String[] argv) {
87 * IconsFactory.generateHTML(TemplateIconsFactory.class);
88 * }
89 * }
90 * </code></pre>
91 * In your own IconsFactory, you can further divide images into different groups. The example above has two groups.
92 * There is also a convenient method getImageIcon() which takes just the icon name.
93 * <p>
94 * In the template, we defined the image names as constants. When you have a lot of images, it's hard to remember all of
95 * them when writing code. If using the IconsFactory above, you can use
96 * <pre><code>
97 * ImageIcon icon = TemplateIconsFactory.getImageIcon(TemplateIconsFactory.Group1.IMAGE1);
98 * </code></pre>
99 * without saying the actual image file name. With the help of intelli-sense (or code completion) feature in most Java
100 * IDE, you will find it is much easier to find the icons you want. You can refer to JIDE Components Developer Guide to
101 * see a screenshot of what it looks like in IntelliJ IDEA.
102 * <p>
103 * You probably also notice this is a main() method in this template. You can run it. When you run, you will see a
104 * message printed out like this.
105 * <pre><code>
106 * "File is generated at "... some directory ...\com.jidesoft.icons.TemplateIconsFactory.html".
107 * Please copy it to the same directory as TemplateIconsFactory.java"
108 * </code></pre>
109 * if you follow the instruction and copy the html file to the same location as the source code and open the html, you
110 * will see the all image files defined in this IconsFactory are listed nicely in the page.
111 * <p>
112 * By default, all image files are loaded using ImageIO. However if you set system property "jide.useImageIO" to
113 * "false", we will disable the usage of ImageIO and use Toolkit.getDefaultToolkit().createImage method to create the
114 * image file.
115 */
116 public class IconsFactory {
117
118 static final double DEGREE_90 = 90.0 * Math.PI / 180.0;
119 public static ImageIcon EMPTY_ICON = new ImageIcon() {
120 private static final long serialVersionUID = 5081581607741629368L;
121
122 @Override
123 public int getIconHeight() {
124 return 16;
125 }
126
127 @Override
128 public int getIconWidth() {
129 return 16;
130 }
131
132 @Override
133 public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
134 }
135 };
136 static Map<String, ImageIcon> _icons = new HashMap<String, ImageIcon>();
137 static Map<String, ImageIcon> _disableIcons = new HashMap<String, ImageIcon>();
138 static Map<String, ImageIcon> _brighterIcons = new HashMap<String, ImageIcon>();
139 static Map<String, ImageIcon> _tintedIcons = new HashMap<String, ImageIcon>();
140
141 /**
142 * Gets ImageIcon by passing class and a relative image file path.
143 * <p>
144 * Please note, getImageIcon will print out error message to stderr if image is not found. The reason we did so is
145 * because we want you to make sure all image files are there in your application. If you ever see the error
146 * message, you should correct it before shipping the product. But if you just want to test if the image file is
147 * there, you don't want any error message print out. If so, you can use {@link #findImageIcon(Class, String)}
148 * method. It will throw IOException when image is not found.
149 * <p>
150 * We used this method to create all the icons we used in JIDE's code. If you ever want to use your own icon instead
151 * of JIDE's default icon, you just need to put it onto UIManager. For example, AutoFilterTableHeader uses an icon
152 * on the table header. This is how it was called. <br/> <code> IconsFactory.getImageIcon(AutoFilterTableHeader.class,
153 * "icons/filterYes_over.png") </code>
154 * <p>
155 * The key for this icon is "com.jidesoft.grid.AutoFilterTableHeader:icons/filterYes_over.png". So you can call the
156 * code below to register your own icon. <p/> <code> UIManager.put("com.jidesoft.grid.AutoFilterTableHeader:icons/filterYes_over.png",
157 * your_new_icon); </code>
158 * <p>
159 * If you don't know what key to use, just put a breakpoint at this method, run it to inspect the id variable
160 * below.
161 *
162 * @param clazz the Class<?>
163 * @param fileName relative file name
164 * @return the ImageIcon
165 */
166 public static ImageIcon getImageIcon(Class<?> clazz, String fileName) {
167 String id = clazz.getName() + ":" + fileName;
168 Object iconInUIDefaults = UIManager.getDefaults().get(id);
169 if (iconInUIDefaults instanceof ImageIcon) {
170 return (ImageIcon) iconInUIDefaults;
171 }
172 Icon saved = _icons.get(id);
173 if (saved != null)
174 return (ImageIcon) saved;
175 else {
176 ImageIcon icon = createImageIcon(clazz, fileName);
177 _icons.put(id, icon);
178 return icon;
179 }
180 }
181
182 /**
183 * Gets ImageIcon by passing class and a relative image file path.
184 *
185 * @param clazz the Class<?>
186 * @param fileName relative file name
187 * @return the ImageIcon
188 * @throws IOException when image file is not found.
189 */
190 public static ImageIcon findImageIcon(Class<?> clazz, String fileName) throws IOException {
191 String id = clazz.getName() + ":" + fileName;
192 Object iconInUIDefaults = UIManager.getDefaults().get(id);
193 if (iconInUIDefaults instanceof ImageIcon) {
194 return (ImageIcon) iconInUIDefaults;
195 }
196 ImageIcon saved = _icons.get(id);
197 if (saved != null)
198 return saved;
199 else {
200 ImageIcon icon = createImageIconWithException(clazz, fileName);
201 _icons.put(id, icon);
202 return icon;
203 }
204 }
205
206 /**
207 * Gets a disabled version of ImageIcon by passing class and a relative image file path.
208 *
209 * @param clazz the Class<?>
210 * @param fileName relative file name
211 * @return the ImageIcon
212 */
213 public static ImageIcon getDisabledImageIcon(Class<?> clazz, String fileName) {
214 String id = clazz.getName() + ":" + fileName;
215 ImageIcon saved = _disableIcons.get(id);
216 if (saved != null)
217 return saved;
218 else {
219 ImageIcon icon = createGrayImage(getImageIcon(clazz, fileName));
220 _disableIcons.put(id, icon);
221 return icon;
222 }
223 }
224
225 /**
226 * Gets a brighter ImageIcon by passing class and a relative image file path.
227 *
228 * @param clazz the Class<?>
229 * @param fileName relative file name
230 * @return the ImageIcon
231 */
232 public static ImageIcon getBrighterImageIcon(Class<?> clazz, String fileName) {
233 String id = clazz.getName() + ":" + fileName + ":" + ColorFilter.getPercent();
234 ImageIcon saved = _brighterIcons.get(id);
235 if (saved != null)
236 return saved;
237 else {
238 ImageIcon icon = createBrighterImage(getImageIcon(clazz, fileName));
239 _brighterIcons.put(id, icon);
240 return icon;
241 }
242 }
243
244 /**
245 * Gets a brighter ImageIcon by passing class, a relative image file path and a percentage of brightness.
246 *
247 * @param clazz the Class<?>
248 * @param fileName relative file name
249 * @param percent percentage of brightness
250 * @return the ImageIcon
251 */
252 public static ImageIcon getBrighterImageIcon(Class<?> clazz, String fileName, int percent) {
253 String id = clazz.getName() + ":" + fileName + ":" + percent;
254 ImageIcon saved = _brighterIcons.get(id);
255 if (saved != null)
256 return saved;
257 else {
258 ImageIcon icon = createBrighterImage(getImageIcon(clazz, fileName), percent);
259 _brighterIcons.put(id, icon);
260 return icon;
261 }
262 }
263
264 /**
265 * Gets a tinted ImageIcon by passing class, a relative image file path and a color.
266 *
267 * @param clazz the Class<?>
268 * @param fileName relative file name
269 * @param color the color
270 * @return the ImageIcon
271 */
272 public static ImageIcon getTintedImageIcon(Class<?> clazz, String fileName, Color color) {
273 String id = clazz.getName() + ":" + fileName + ":" + color.toString();
274 ImageIcon saved = _tintedIcons.get(id);
275 if (saved != null)
276 return saved;
277 else {
278 ImageIcon icon = createTintedImage(getImageIcon(clazz, fileName), color);
279 _tintedIcons.put(id, icon);
280 return icon;
281 }
282 }
283
284 /**
285 * Creates a gray version from an input image. Usually gray icon indicates disabled. If input image is null, a blank
286 * ImageIcon will be returned.
287 *
288 * @param image image
289 * @return gray version of the image
290 */
291 public static ImageIcon createGrayImage(Image image) {
292 if (image == null)
293 return EMPTY_ICON;
294 return new ImageIcon(GrayFilter.createDisabledImage(image));
295 }
296
297 /**
298 * Creates a gray version from an input ImageIcon. Usually gray icon indicates disabled. If input icon is null, a
299 * blank ImageIcon will be returned.
300 *
301 * @param icon image
302 * @return gray version of the image
303 */
304 private static ImageIcon createGrayImage(ImageIcon icon) {
305 if (icon == null)
306 return EMPTY_ICON;
307 return new ImageIcon(GrayFilter.createDisabledImage(icon.getImage()));
308 }
309
310 /**
311 * Creates a gray version from an input image. Usually gray icon indicates disabled. If input icon is null, a blank
312 * ImageIcon will be returned.
313 *
314 * @param c The component to get properties useful for painting, e.g. the foreground or background color.
315 * @param icon icon
316 * @return gray version of the image
317 */
318 public static ImageIcon createGrayImage(Component c, Icon icon) {
319 if (icon == null)
320 return EMPTY_ICON;
321
322 int w = icon.getIconWidth(), h = icon.getIconHeight();
323 if ((w == 0) || (h == 0))
324 return EMPTY_ICON;
325
326 BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
327 icon.paintIcon(c, image.getGraphics(), 0, 0);
328 return new ImageIcon(GrayFilter.createDisabledImage(image));
329 }
330
331 /**
332 * Creates a brighter image from an input image. If input image is null, a blank ImageIcon will be returned.
333 *
334 * @param image image
335 * @return dimmed version of the image
336 */
337 public static ImageIcon createBrighterImage(Image image) {
338 if (image == null)
339 return EMPTY_ICON;
340 return new ImageIcon(ColorFilter.createBrighterImage(image));
341 }
342
343 /**
344 * Creates a brighter image from an input image with a given percentage of brightness. If input image is null, a
345 * blank ImageIcon will be returned.
346 *
347 * @param image image
348 * @param percent percentage of brightness
349 * @return dimmed version of the image
350 */
351 public static ImageIcon createBrighterImage(Image image, int percent) {
352 if (image == null)
353 return EMPTY_ICON;
354 return new ImageIcon(ColorFilter.createBrighterImage(image, percent));
355 }
356
357 /**
358 * Creates a gray version from an input image. Usually gray icon indicates disabled. If input icon is null, a blank
359 * ImageIcon will be returned.
360 *
361 * @param c The component to get properties useful for painting, e.g. the foreground or background color.
362 * @param icon icon
363 * @return gray version of the image
364 */
365 public static ImageIcon createBrighterImage(Component c, Icon icon) {
366 if (icon == null)
367 return EMPTY_ICON;
368 BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
369 icon.paintIcon(c, image.getGraphics(), 0, 0);
370 return new ImageIcon(ColorFilter.createBrighterImage(image));
371 }
372
373 /**
374 * Creates a gray version from an input image with a given percentage of brightness. Usually gray icon indicates
375 * disabled. If input icon is null, a blank ImageIcon will be returned.
376 *
377 * @param c The component to get properties useful for painting, e.g. the foreground or background color.
378 * @param icon icon
379 * @param percent percentage of brightness
380 * @return gray version of the image
381 */
382 public static ImageIcon createBrighterImage(Component c, Icon icon, int percent) {
383 if (icon == null)
384 return EMPTY_ICON;
385 BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
386 icon.paintIcon(c, image.getGraphics(), 0, 0);
387 return new ImageIcon(ColorFilter.createBrighterImage(image, percent));
388 }
389
390 /**
391 * Creates a brighten version from an input ImageIcon. If input icon is null, a blank ImageIcon will be returned.
392 *
393 * @param icon image
394 * @return dimmed version of the image
395 */
396 public static ImageIcon createBrighterImage(ImageIcon icon) {
397 if (icon == null)
398 return EMPTY_ICON;
399 return new ImageIcon(ColorFilter.createBrighterImage(icon.getImage()));
400 }
401
402 /**
403 * Creates a brighter image from an input image with a given percentage of brightness. If input image is null, a
404 * blank ImageIcon will be returned.
405 *
406 * @param icon image
407 * @param percent percentage of brightness
408 * @return dimmed version of the image
409 */
410 public static ImageIcon createBrighterImage(ImageIcon icon, int percent) {
411 if (icon == null)
412 return EMPTY_ICON;
413 return new ImageIcon(ColorFilter.createBrighterImage(icon.getImage(), percent));
414 }
415
416 /**
417 * Creates a tinted image from an input image with a given color. If input image is null, a blank ImageIcon will be
418 * returned.
419 *
420 * @param icon image
421 * @param color the color
422 * @return a tinted version of the image
423 */
424 public static ImageIcon createTintedImage(ImageIcon icon, Color color) {
425 if (icon == null)
426 return EMPTY_ICON;
427 return new ImageIcon(TintFilter.createTintedImage(icon.getImage(), color, null));
428 }
429
430 /**
431 * Creates a gray version from an input image. Usually gray icon indicates disabled. If input image is null, a blank
432 * ImageIcon will be returned.
433 *
434 * @param image image
435 * @return gray version of the image
436 */
437 public static ImageIcon createNegativeImage(Image image) {
438 if (image == null)
439 return EMPTY_ICON;
440 return new ImageIcon(MaskFilter.createNegativeImage(image));
441 }
442
443 /**
444 * Creates a version from an input image which replaces one color with another color.
445 *
446 * @param c The component to get properties useful for painting, e.g. the foreground or background color.
447 * @param icon icon
448 * @param oldColor the old color to be replaced.
449 * @param newColor the new color that will replace the old color.
450 * @return the image after replacing the color.
451 */
452 public static ImageIcon createMaskImage(Component c, Icon icon, Color oldColor, Color newColor) {
453 BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
454 icon.paintIcon(c, image.getGraphics(), 0, 0);
455 return new ImageIcon(MaskFilter.createImage(image, oldColor, newColor));
456 }
457
458 /**
459 * Creates a rotated version of the input image.
460 *
461 * @param c The component to get properties useful for painting, e.g. the foreground or background
462 * color.
463 * @param icon the image to be rotated.
464 * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we will mod it with 360
465 * before using it.
466 * @return the image after rotating.
467 */
468 public static ImageIcon createRotatedImage(Component c, Icon icon, double rotatedAngle) {
469 // convert rotatedAngle to a value from 0 to 360
470 double originalAngle = rotatedAngle % 360;
471 if (rotatedAngle != 0 && originalAngle == 0) {
472 originalAngle = 360.0;
473 }
474
475 // convert originalAngle to a value from 0 to 90
476 double angle = originalAngle % 90;
477 if (originalAngle != 0.0 && angle == 0.0) {
478 angle = 90.0;
479 }
480
481 double radian = Math.toRadians(angle);
482
483 int iw = icon.getIconWidth();
484 int ih = icon.getIconHeight();
485 int w;
486 int h;
487
488 if ((originalAngle >= 0 && originalAngle <= 90) || (originalAngle > 180 && originalAngle <= 270)) {
489 w = (int) Math.round((iw * Math.sin(DEGREE_90 - radian) + ih * Math.sin(radian)));
490 h = (int) Math.round((iw * Math.sin(radian) + ih * Math.sin(DEGREE_90 - radian)));
491 }
492 else {
493 w = (int) (ih * Math.sin(DEGREE_90 - radian) + iw * Math.sin(radian));
494 h = (int) (ih * Math.sin(radian) + iw * Math.sin(DEGREE_90 - radian));
495 }
496
497 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
498 Graphics g = image.getGraphics();
499 Graphics2D g2d = (Graphics2D) g.create();
500
501 // calculate the center of the icon.
502 int cx = iw / 2;
503 int cy = ih / 2;
504
505 // account for images that have a center point in the middle of a pixel.
506 // for these images (not divisible by two) we need to account for the
507 // "down and to the right" bias of the graphics context.
508 int xOffset = iw % 2 != 0 && originalAngle >= 90 && originalAngle <= 180
509 ? 1 : 0;
510 int yOffset = iw % 2 != 0 && originalAngle >= 180 && originalAngle < 360
511 ? 1 : 0;
512
513 // move the graphics center point to the center of the icon.
514 g2d.translate(w / 2 + xOffset, h / 2 + yOffset);
515
516 // rotate the graphics about the center point of the icon
517 g2d.rotate(Math.toRadians(originalAngle));
518
519 g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
520 RenderingHints.VALUE_INTERPOLATION_BICUBIC);
521
522 icon.paintIcon(c, g2d, -cx, -cy);
523
524 g2d.dispose();
525 return new ImageIcon(image);
526 }
527
528 /**
529 * Creates a negative version from an input black image which basically replaces black pixel with white pixel.
530 *
531 * @param c The component to get properties useful for painting, e.g. the foreground or background color.
532 * @param icon icon
533 * @return the negative version of the image
534 */
535 public static ImageIcon createNegativeImage(Component c, Icon icon) {
536 BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
537 icon.paintIcon(c, image.getGraphics(), 0, 0);
538 return new ImageIcon(MaskFilter.createNegativeImage(image));
539 }
540
541 private static ImageIcon createImageIcon(final Class<?> baseClass, final String file) {
542 try {
543 return createImageIconWithException(baseClass, file);
544 }
545 catch (IOException e) {
546 System.err.println(e.getLocalizedMessage());
547 return null;
548 }
549 }
550
551 private static ImageIcon createImageIconWithException(final Class<?> baseClass, final String file) throws IOException {
552 InputStream resource = baseClass.getResourceAsStream(file);
553 if (resource == null) {
554 throw new FileNotFoundException(file);
555 }
556 else {
557 Image image;
558 if ("true".equals(SecurityUtils.getProperty("jide.useImageIO", "true"))) {
559 image = ImageIO.read(resource);
560 }
561 else {
562 image = readImageIcon(baseClass, file, resource);
563 }
564 resource.close();
565 return new ImageIcon(image);
566 }
567 }
568
569
570 private static Image readImageIcon(Class clazz, String file, InputStream resource) throws IOException {
571 final byte[][] buffer = new byte[1][];
572 try {
573 BufferedInputStream in = new BufferedInputStream(resource);
574 ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
575
576 buffer[0] = new byte[1024];
577 int n;
578 while ((n = in.read(buffer[0])) > 0) {
579
580 out.write(buffer[0], 0, n);
581 }
582 in.close();
583 out.flush();
584 buffer[0] = out.toByteArray();
585 }
586 catch (IOException ioe) {
587 throw ioe;
588 }
589
590 if (buffer[0] == null || buffer[0].length == 0) {
591 Package pkg = clazz.getPackage();
592 String pkgName = "";
593 if (pkg != null) {
594 pkgName = pkg.getName().replace('.', '/');
595 }
596 if (buffer[0] == null) {
597 throw new IOException("Warning: Resource " + pkgName + "/" + file + " not found.");
598 }
599 if (buffer[0].length == 0) {
600 throw new IOException("Warning: Resource " + pkgName + "/" + file + " is zero-length");
601 }
602 }
603
604 return Toolkit.getDefaultToolkit().createImage(buffer[0]);
605 }
606
607 /**
608 * Generates HTML that lists all icons in IconsFactory.
609 *
610 * @param clazz the IconsFactory class
611 */
612 public static void generateHTML(Class<?> clazz) {
613 String fullClassName = clazz.getName();
614 String className = getClassName(fullClassName);
615 File file = new File(fullClassName + ".html");
616
617 try {
618 FileWriter writer = new FileWriter(file);
619 try {
620 writer.write("<html>\n<body>\n<p><b><font size=\"5\" face=\"Verdana\">Icons in " +
621 fullClassName + "</font></b></p>");
622 writer.write("<p><b><font size=\"3\" face=\"Verdana\">Generated by JIDE Icons</font></b></p>");
623 writer.write("<p><b><font size=\"3\" color=\"#AAAAAA\" face=\"Verdana\">1. If you cannot view the images in this page, " +
624 "make sure the file is at the same directory as " + className + ".java</font></b></p>");
625 writer.write("<p><b><font size=\"3\" color=\"#AAAAAA\" face=\"Verdana\">2. To get a particular icon in your code, call " +
626 className + ".getImageIcon(FULL_CONSTANT_NAME). Replace FULL_CONSTANT_NAME with the actual " +
627 "full constant name as in the table below" + "</font></b></p>");
628 generate(clazz, writer, className);
629 writer.write("\n</body>\n</html>");
630 }
631 catch (IOException e) {
632 System.err.println(e);
633 }
634 finally {
635 writer.close();
636 }
637 System.out.println("File is generated at \"" + file.getAbsolutePath() + "\". Please copy it to the same directory as " + className + ".java");
638 }
639 catch (IOException e) {
640 System.err.println(e);
641 }
642 }
643
644 private static String getClassName(String fullName) {
645 int last = fullName.lastIndexOf(".");
646 if (last != -1) {
647 fullName = fullName.substring(last + 1);
648 }
649 StringTokenizer tokenizer = new StringTokenizer(fullName, "$");
650 StringBuffer buffer = new StringBuffer();
651 while (tokenizer.hasMoreTokens()) {
652 buffer.append(tokenizer.nextToken());
653 buffer.append(".");
654 }
655 return buffer.substring(0, buffer.length() - 1);
656 }
657
658 private static void generate(Class<?> aClass, FileWriter writer, String prefix) throws IOException {
659 Class<?>[] classes = aClass.getDeclaredClasses();
660 // don't know why but the order is exactly the reverse of the order of definitions.
661 for (int i = classes.length - 1; i >= 0; i--) {
662 Class<?> clazz = classes[i];
663 generate(clazz, writer, getClassName(clazz.getName()));
664 }
665
666 Field[] fields = aClass.getFields();
667 writer.write("<p><font face=\"Verdana\"><b>" + prefix + "</b></font></p>");
668 writer.write("<table border=\"1\" cellpadding=\"0\" cellspacing=\"0\" bordercolor=\"#CCCCCC\" width=\"66%\">");
669 writer.write("<tr>\n");
670 writer.write("<td width=\"24%\" align=\"center\"><b><font face=\"Verdana\" color=\"#003399\">Name</font></b></td>\n");
671 writer.write("<td width=\"13%\" align=\"center\"><b><font face=\"Verdana\" color=\"#003399\">Image</font></b></td>\n");
672 writer.write("<td width=\"32%\" align=\"center\"><b><font face=\"Verdana\" color=\"#003399\">File Name</font></b></td>\n");
673 writer.write("<td width=\"31%\" align=\"center\"><b><font face=\"Verdana\" color=\"#003399\">Full Constant Name</font></b></td>\n");
674 writer.write("</tr>\n");
675 for (Field field : fields) {
676 try {
677 Object name = field.getName();
678 Object value = field.get(aClass);
679 writer.write("<tr>\n");
680 writer.write("<td align=\"left\"><font face=\"Verdana\">" + name + "</font></td>\n");
681 writer.write("<td align=\"center\"><font face=\"Verdana\"><img border=\"0\" src=\"" + value + "\"></font></td>\n");
682 writer.write("<td align=\"left\"><font face=\"Verdana\">" + value + "</font></td>\n");
683 writer.write("<td align=\"left\"><font face=\"Verdana\">" + prefix + "." + name + "</font></td>\n");
684 writer.write("</tr>\n");
685 }
686 catch (IllegalArgumentException e) {
687 e.printStackTrace();
688 }
689 catch (IllegalAccessException e) {
690 e.printStackTrace();
691 }
692 }
693 writer.write("</table><br><p>\n");
694 }
695
696 /**
697 * Gets part of the image from input image icon. It basically takes a snapshot of the input image at {x, y} location
698 * and the size is width x height.
699 *
700 * @param c the component where the returned icon will be used. The component is used as the ImageObserver. It
701 * could be null.
702 * @param icon the original icon. This is the larger icon where a sub-image will be created using this method.
703 * @param x the x location of the sub-image, relative to the original icon.
704 * @param y the y location of the sub-image, relative to the original icon.
705 * @param width the width of the sub-image. It should be less than the width of the original icon.
706 * @param height the height of the sub-image. It should be less than the height of the original icon.
707 * @return an new image icon that was part of the input image icon.
708 */
709 public static ImageIcon getIcon(Component c, ImageIcon icon, int x, int y, int width, int height) {
710 return getIcon(c, icon, x, y, width, height, width, height);
711 }
712
713 /**
714 * Gets part of the image from input image icon. It basically takes a snapshot of the input image at {x, y} location
715 * and the size is width x height, then resize it to a size of destWidth x destHeight.
716 *
717 * @param c the component where the returned icon will be used. The component is used as the ImageObserver.
718 * It could be null.
719 * @param icon the original icon. This is the larger icon where a sub-image will be created using this
720 * method.
721 * @param x the x location of the sub-image, relative to the original icon.
722 * @param y the y location of the sub-image, relative to the original icon.
723 * @param width the width of the sub-image. It should be less than the width of the original icon.
724 * @param height the height of the sub-image. It should be less than the height of the original icon.
725 * @param destWidth the width of the returned icon. The sub-image will be resize if the destWidth is not the same
726 * as the width.
727 * @param destHeight the height of the returned icon. The sub-image will be resize if the destHeight is not the same
728 * as the height.
729 * @return an new image icon that was part of the input image icon.
730 */
731 public static ImageIcon getIcon(Component c, ImageIcon icon, int x, int y, int width, int height, int destWidth, int destHeight) {
732 return getIcon(c, icon, x, y, width, height, BufferedImage.TYPE_INT_ARGB, destWidth, destHeight);
733 }
734
735 /**
736 * Gets part of the image from input image icon. It basically takes a snapshot of the input image at {x, y} location
737 * and the size is width x height.
738 *
739 * @param c the component where the returned icon will be used. The component is used as the ImageObserver.
740 * It could be null.
741 * @param icon the original icon. This is the larger icon where a small icon will be created using this
742 * method.
743 * @param x the x location of the smaller icon, relative to the original icon.
744 * @param y the y location of the smaller icon, relative to the original icon.
745 * @param width the width of the smaller icon. It should be less than the width of the original icon.
746 * @param height the height of the smaller icon. It should be less than the height of the original icon.
747 * @param imageType image type is defined in {@link BufferedImage}, such as {@link BufferedImage#TYPE_INT_ARGB},
748 * {@link BufferedImage#TYPE_INT_RGB} etc.
749 * @return an new image icon that was part of the input image icon.
750 */
751 public static ImageIcon getIcon(Component c, ImageIcon icon, int x, int y, int width, int height, int imageType) {
752 return getIcon(c, icon, x, y, width, height, imageType, width, height);
753 }
754
755 /**
756 * Gets part of the image from input image icon. It basically takes a snapshot of the input image at {x, y} location
757 * and the size is width x height, then resize it to a size of destWidth x destHeight. if the original icon is null
758 * or the specified location is outside the original icon, EMPTY_ICON will be returned.
759 *
760 * @param c the component where the returned icon will be used. The component is used as the ImageObserver.
761 * It could be null.
762 * @param icon the original icon. This is the larger icon where a sub-image will be created using this
763 * method.
764 * @param x the x location of the sub-image, relative to the original icon.
765 * @param y the y location of the sub-image, relative to the original icon.
766 * @param width the width of the sub-image. It should be less than the width of the original icon.
767 * @param height the height of the sub-image. It should be less than the height of the original icon.
768 * @param imageType image type is defined in {@link BufferedImage}, such as {@link BufferedImage#TYPE_INT_ARGB},
769 * {@link BufferedImage#TYPE_INT_RGB} etc.
770 * @param destWidth the width of the returned icon. The sub-image will be resize if the destWidth is not the same
771 * as the width.
772 * @param destHeight the height of the returned icon. The sub-image will be resize if the destHeight is not the same
773 * as the height.
774 * @return an new image icon that was part of the input image icon.
775 */
776 public static ImageIcon getIcon(Component c, ImageIcon icon, int x, int y, int width, int height, int imageType, int destWidth, int destHeight) {
777 if (icon == null || x < 0 || x + width > icon.getIconWidth() || y < 0 || y + height > icon.getIconHeight()) { // outside the original icon.
778 return EMPTY_ICON;
779 }
780 BufferedImage image = new BufferedImage(destWidth, destHeight, imageType);
781 image.getGraphics().drawImage(icon.getImage(), 0, 0, destWidth, destHeight, x, y, x + width, y + height, c);
782 return new ImageIcon(image);
783 }
784
785 /**
786 * Gets a new icon with the overlayIcon paints over the original icon.
787 *
788 * @param c the component where the returned icon will be used. The component is used as the
789 * ImageObserver. It could be null.
790 * @param icon the original icon
791 * @param overlayIcon the overlay icon.
792 * @param location the location as defined in SwingConstants - CENTER, NORTH, SOUTH, WEST, EAST, NORTH_EAST,
793 * NORTH_WEST, SOUTH_WEST and SOUTH_EAST.
794 * @return the new icon.
795 */
796 public static ImageIcon getOverlayIcon(Component c, ImageIcon icon, ImageIcon overlayIcon, int location) {
797 return getOverlayIcon(c, icon, overlayIcon, location, new Insets(0, 0, 0, 0));
798 }
799
800 /**
801 * Gets a new icon with the overlayIcon paints over the original icon.
802 *
803 * @param c the component where the returned icon will be used. The component is used as the
804 * ImageObserver. It could be null.
805 * @param icon the original icon
806 * @param overlayIcon the overlay icon.
807 * @param location the location as defined in SwingConstants - CENTER, NORTH, SOUTH, WEST, EAST, NORTH_EAST,
808 * NORTH_WEST, SOUTH_WEST and SOUTH_EAST.
809 * @param insets the insets to the border. This parameter has no effect if the location is CENTER. For example,
810 * if the location is WEST, insets.left will be the gap of the left side of the original icon and
811 * the left side of the overlay icon.
812 * @return the new icon.
813 */
814 public static ImageIcon getOverlayIcon(Component c, ImageIcon icon, ImageIcon overlayIcon, int location, Insets insets) {
815 int x = -1, y = -1;
816 int w = icon.getIconWidth();
817 int h = icon.getIconHeight();
818 int sw = overlayIcon.getIconWidth();
819 int sh = overlayIcon.getIconHeight();
820 switch (location) {
821 case SwingConstants.CENTER:
822 x = (w - sw) / 2;
823 y = (h - sh) / 2;
824 break;
825 case SwingConstants.NORTH:
826 x = (w - sw) / 2;
827 y = insets.top;
828 break;
829 case SwingConstants.SOUTH:
830 x = (w - sw) / 2;
831 y = h - insets.bottom - sh;
832 break;
833 case SwingConstants.WEST:
834 x = insets.left;
835 y = (h - sh) / 2;
836 break;
837 case SwingConstants.EAST:
838 x = w - insets.right - sw;
839 y = (h - sh) / 2;
840 break;
841 case SwingConstants.NORTH_EAST:
842 x = w - insets.right - sw;
843 y = insets.top;
844 break;
845 case SwingConstants.NORTH_WEST:
846 x = insets.left;
847 y = insets.top;
848 break;
849 case SwingConstants.SOUTH_WEST:
850 x = insets.left;
851 y = h - insets.bottom - sh;
852 break;
853 case SwingConstants.SOUTH_EAST:
854 x = w - insets.right - sw;
855 y = h - insets.bottom - sh;
856 break;
857 }
858 return getOverlayIcon(c, icon, overlayIcon, x, y);
859 }
860
861 /**
862 * Gets a new icon with the overlayIcon paints over the original icon.
863 *
864 * @param c the component where the returned icon will be used. The component is used as the
865 * ImageObserver. It could be null.
866 * @param icon the original icon
867 * @param overlayIcon the overlay icon.
868 * @param x the x location relative to the original icon where the overlayIcon will be pained.
869 * @param y the y location relative to the original icon where the overlayIcon will be pained.
870 * @return the overlay icon
871 */
872 public static ImageIcon getOverlayIcon(Component c, ImageIcon icon, ImageIcon overlayIcon, int x, int y) {
873 int w = icon == null ? overlayIcon.getIconWidth() : icon.getIconWidth();
874 int h = icon == null ? overlayIcon.getIconHeight() : icon.getIconHeight();
875 int sw = overlayIcon.getIconWidth();
876 int sh = overlayIcon.getIconHeight();
877 if (x != -1 && y != -1) {
878 BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
879 if (icon != null) {
880 image.getGraphics().drawImage(icon.getImage(), 0, 0, w, h, c);
881 }
882 image.getGraphics().drawImage(overlayIcon.getImage(), x, y, sw, sh, c);
883 return new ImageIcon(image);
884 }
885 else {
886 return icon;
887 }
888 }
889
890 /**
891 * Gets a new icon with the icon2 painting right or down to the icon1.
892 *
893 * @param c the component where the returned icon will be used. The component is used as the
894 * ImageObserver. It could be null
895 * @param icon1 the left side or up side icon
896 * @param icon2 the right side or down side icon
897 * @param orientation the orientation as defined in SwingConstants - HORIZONTAL, VERTICAL
898 * @param gap the gap between the two icons
899 * @return the new icon.
900 */
901 public static ImageIcon getCombinedIcon(Component c, ImageIcon icon1, ImageIcon icon2, int orientation, int gap) {
902 if (icon1 == null) {
903 return icon2;
904 }
905 if (icon2 == null) {
906 return icon1;
907 }
908 int x1, y1, x2, y2, width, height;
909 int w1 = icon1.getIconWidth();
910 int h1 = icon1.getIconHeight();
911 int w2 = icon2.getIconWidth();
912 int h2 = icon2.getIconHeight();
913
914 if (orientation == SwingConstants.HORIZONTAL) {
915 width = w1 + w2 + gap;
916 height = Math.max(h1, h2);
917 x1 = 0;
918 x2 = w1 + gap;
919 y1 = h1 > h2 ? 0 : (h2 - h1) / 2;
920 y2 = h1 < h2 ? 0 : (h1 - h2) / 2;
921 }
922 else {
923 width = Math.max(w1, w2);
924 height = h1 + h2 + gap;
925 x1 = w1 > w2 ? 0 : (w2 - w1) / 2;
926 x2 = w1 < w2 ? 0 : (w1 - w2) / 2;
927 y1 = 0;
928 y2 = h1 + gap;
929 }
930
931 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
932 image.getGraphics().drawImage(icon1.getImage(), x1, y1, w1, h1, c);
933 image.getGraphics().drawImage(icon2.getImage(), x2, y2, w2, h2, c);
934 return new ImageIcon(image);
935 }
936
937 /**
938 * Gets a scaled version of the existing icon.
939 *
940 * @param c the component where the returned icon will be used. The component is used as the ImageObserver. It
941 * could be null.
942 * @param icon the original icon
943 * @param w the new width
944 * @param h the new height
945 * @return the scaled icon
946 */
947 public static ImageIcon getScaledImage(Component c, ImageIcon icon, int w, int h) {
948 if (w >= icon.getIconWidth() / 2) {
949 BufferedImage temp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
950 Graphics2D g2 = temp.createGraphics();
951 g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
952 g2.drawImage(icon.getImage(), 0, 0, temp.getWidth(), temp.getHeight(), c);
953 g2.dispose();
954 return new ImageIcon(temp);
955 }
956 else {
957 BufferedImage temp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
958 Graphics2D g2 = temp.createGraphics();
959 g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
960 g2.drawImage(icon.getImage(), 0, 0, temp.getWidth(), temp.getHeight(), c);
961 g2.dispose();
962 return new ImageIcon(JideSwingUtilities.getFasterScaledInstance(temp, w, h, RenderingHints.VALUE_INTERPOLATION_BILINEAR, true));
963 }
964 }
965
966 /**
967 * Writes a GIF image of the supplied component to the given file. In particular, you can use this method to take a
968 * 'screen shot' of a Chart component as a GIF Image.
969 *
970 * @param c the component to save as an image
971 * @param file the file to save it to
972 * @throws FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist
973 * but cannot be created, or cannot be opened for any other reason
974 */
975 public static void writeGifToFile(Component c, File file) throws FileNotFoundException {
976 FileOutputStream fos = new FileOutputStream(file);
977 writeToStream(c, "gif", fos);
978 try {
979 fos.close();
980 }
981 catch (IOException e) {
982 Logger.getAnonymousLogger().severe(e.getMessage());
983 }
984 }
985
986 /**
987 * Writes a JPEG image of the supplied component to the given file. In particular, you can use this method to take a
988 * 'screen shot' of a Chart component as a JPEG Image.
989 *
990 * @param c the component to save as an image
991 * @param file the file to save it to
992 * @throws FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist
993 * but cannot be created, or cannot be opened for any other reason
994 */
995 public static void writeJpegToFile(Component c, File file) throws FileNotFoundException {
996 FileOutputStream fos = new FileOutputStream(file);
997 writeToStream(c, "jpg", fos);
998 try {
999 fos.close();
1000 }
1001 catch (IOException e) {
1002 Logger.getAnonymousLogger().severe(e.getMessage());
1003 }
1004 }
1005
1006 /**
1007 * Writes a PNG image of the supplied component to the given file. In particular, you can use this method to take a
1008 * 'screen shot' of a Chart component as a PNG Image.
1009 *
1010 * @param c the component to save as an image
1011 * @param file the file to save it to
1012 * @throws FileNotFoundException if the file exists but is a directory rather than a regular file, does not exist
1013 * but cannot be created, or cannot be opened for any other reason
1014 */
1015 public static void writePngToFile(Component c, File file) throws FileNotFoundException {
1016 FileOutputStream fos = new FileOutputStream(file);
1017 writeToStream(c, "png", fos);
1018 try {
1019 fos.close();
1020 }
1021 catch (IOException e) {
1022 Logger.getAnonymousLogger().severe(e.getMessage());
1023 }
1024 }
1025
1026
1027 /**
1028 * Paints the component as a PNG image to the supplied output stream
1029 *
1030 * @param c the component to capture as a PNG image
1031 * @param stream the stream to write the PNG data to
1032 */
1033 public static void writeToStream(Component c, OutputStream stream) {
1034 writeToStream(c, "png", stream);
1035 }
1036
1037 /**
1038 * Paints the component to the supplied output stream
1039 *
1040 * @param c the component to capture as an image
1041 * @param format the format of the image output data, currently "png", "jpg" or "gif"
1042 * @param stream the stream to write the image data to
1043 */
1044 private static void writeToStream(Component c, String format, OutputStream stream) {
1045 BufferedImage img = createImage(c);
1046 try {
1047 ImageIO.write(img, format, stream);
1048 }
1049 catch (IOException e) {
1050 // could happen if the output format is not supported
1051 Logger.getAnonymousLogger().severe(e.getMessage());
1052 }
1053 }
1054
1055 /**
1056 * Creates a buffered image of type TYPE_INT_RGB from the supplied component.
1057 *
1058 * @param component the component to draw
1059 * @return an image of the component
1060 */
1061 public static BufferedImage createImage(Component component) {
1062 return createImage(component, BufferedImage.TYPE_INT_RGB);
1063 }
1064
1065 /**
1066 * Creates a buffered image (of the specified type) from the supplied component.
1067 *
1068 * @param component the component to draw
1069 * @param bounds the area relative to the component where the image will be created.
1070 * @param imageType the type of buffered image to draw
1071 * @return an image of the component
1072 */
1073 public static BufferedImage createImage(final Component component, Rectangle bounds, int imageType) {
1074 return createImage(component, bounds, imageType, 1);
1075 }
1076
1077 /**
1078 * Creates a buffered image (of the specified type) from the supplied component.
1079 *
1080 * @param component the component to draw
1081 * @param imageType the type of buffered image to draw
1082 * @return an image of the component
1083 */
1084 public static BufferedImage createImage(final Component component, int imageType) {
1085 Dimension componentSize = component.getSize();
1086 return createImage(component, new Rectangle(0, 0, componentSize.width, componentSize.height), imageType, 1);
1087 }
1088
1089 /**
1090 * Creates a buffered image (of the specified type) from the supplied component.
1091 * <p>
1092 * This method will consider the scale factor for hi-def display such as retina display.
1093 * If the scale factor is 2, the returned image size will double the size of the bounds.
1094 * When you paint the returned image, you should call g.scale(0.5, 0.5) or SystemInfo.endScale(g, SystemInfo.getDisplayScale())
1095 * to paint the image to its normal size. For performance consideration, you may want to keep the
1096 * return value of SystemInfo.getDisplayScale() instead of calling it all the time.
1097 *
1098 * @param component the component to draw
1099 * @param bounds the area relative to the component where the image will be created.
1100 * @param imageType the type of buffered image to draw
1101 * @param scale the scale factor of the display
1102 * @return an image of the component
1103 */
1104 public static BufferedImage createImage(final Component component, Rectangle bounds, int imageType, int scale) {
1105 BufferedImage img = new BufferedImage(bounds.width * scale,
1106 bounds.height * scale,
1107 imageType);
1108 final Graphics2D g = img.createGraphics();
1109 g.scale(scale, scale);
1110 g.fillRect(0, 0, img.getWidth(), img.getHeight());
1111 // If we are painting a JComponent then switch off double buffering because it
1112 // causes a failure when running headlessly on Linux
1113 if (component instanceof JComponent) {
1114 JComponent c = (JComponent) component;
1115 boolean isDoubleBuffered = c.isDoubleBuffered();
1116 c.setDoubleBuffered(false);
1117 g.translate(-bounds.x, -bounds.y);
1118 g.setClip(bounds.x, bounds.y, bounds.width, bounds.height);
1119 c.paint(g);
1120 c.setDoubleBuffered(isDoubleBuffered);
1121 }
1122 else {
1123 component.paint(g);
1124 }
1125 g.dispose();
1126 return img;
1127 }
1128
1129 /**
1130 * Creates a thumbnail from the supplied component (such as a chart). If you want to display the thumbnail as a
1131 * component you can pass the created ImageIcon as a parameter to the constructor of a JLabel.
1132 *
1133 * @param component the component from which we would like to generate a thumbnail
1134 * @param width the width of the thumbnail
1135 * @param height the height of the thumbnail
1136 * @return a thumbnail Image of the supplied component
1137 */
1138 public static Image createThumbnailImage(Component component, int width, int height) {
1139 BufferedImage image = createImage(component);
1140 BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
1141 Graphics2D g = thumbnailImage.createGraphics();
1142 g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
1143 g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
1144 g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
1145 double w = (double) width / image.getWidth();
1146 double h = (double) height / image.getHeight();
1147 assert w <= 1.0 : "The thumbnail should be smaller than the original";
1148 assert h <= 1.0 : "The thumbnail should be smaller than the original";
1149 AffineTransform transform = AffineTransform.getScaleInstance(w, h);
1150 g.drawRenderedImage(image, transform);
1151 return thumbnailImage;
1152 }
1153
1154 /**
1155 * Creates a thumbnail from the supplied component (such as a chart). If you want to display the thumbnail as a
1156 * component you can pass the created ImageIcon as a parameter to the constructor of a JLabel.
1157 *
1158 * @param component the component from which we would like to generate a thumbnail
1159 * @param width the width of the thumbnail
1160 * @param height the height of the thumbnail
1161 * @return an ImageIcon of the supplied component
1162 */
1163 public static ImageIcon createThumbnail(Component component, int width, int height) {
1164 return new ImageIcon(createThumbnailImage(component, width, height));
1165 }
1166
1167
1168 /**
1169 * Utility method to create a texture paint from a graphics file
1170 *
1171 * @param observer the observer to be informed when the texture image has been drawn
1172 * @param fileName the name of a file on the classpath, e.g., com/mycompany/project/images/widget.gif
1173 * @return a TexturePaint instance
1174 */
1175
1176 public static TexturePaint createTexture(JComponent observer, String fileName) {
1177 Image image = createImage(fileName);
1178 MediaTracker tracker = new MediaTracker(observer);
1179 tracker.addImage(image, 1);
1180 try {
1181 tracker.waitForAll();
1182 }
1183 catch (Exception e) {
1184 }
1185 int w = image.getWidth(observer);
1186 int h = image.getHeight(observer);
1187 BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
1188 Graphics2D big = bi.createGraphics();
1189 big.drawImage(image, 0, 0, observer);
1190 return new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight()));
1191 }
1192
1193 /**
1194 * Creates an image from a file on the classpath
1195 *
1196 * @param path the path to the file
1197 * @return an Image object
1198 */
1199 public static Image createImage(String path) {
1200 ClassLoader loader = IconsFactory.class.getClassLoader();
1201 if (loader != null) {
1202 URL url = loader.getResource(path);
1203 if (url == null) {
1204 url = loader.getResource("/" + path);
1205 }
1206 return Toolkit.getDefaultToolkit().createImage(url);
1207 }
1208 return null;
1209 }
1210
1211 }