780b1bbd050556e1a42cd45cfe97dc3ae5bdb47a
[fanfix.git] / src / be / nikiroo / fanfix_swing / images / IconGenerator.java
1 package be.nikiroo.fanfix_swing.images;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.util.HashMap;
6 import java.util.Map;
7
8 import javax.swing.ImageIcon;
9
10 import be.nikiroo.utils.IOUtils;
11
12 /**
13 * Icons generator for this project.
14 *
15 * @author niki
16 */
17 public class IconGenerator {
18 /**
19 * The available icons.
20 *
21 * @author niki
22 */
23 public enum Icon {
24 /** Icon used to clear text fields */
25 clear,
26 /** Search icon (magnifying glass) */
27 search,
28 /** An interrogation point */
29 unknown,
30 /** A small, left-pointed arrow */
31 arrow_left,
32 /** A small, right-pointed arrow */
33 arrow_right,
34 /** A small, up-pointed arrow */
35 arrow_up,
36 /** A small, down-pointed arrow */
37 arrow_down,
38 /** An empty (transparent) icon */
39 empty,
40 }
41
42 /**
43 * The available sizes.
44 *
45 * @author niki
46 */
47 public enum Size {
48 /** 4x4 pixels, only for {@link Icon#empty} */
49 x4(4),
50 /** 8x8 pixels, only for {@link Icon#empty} */
51 x8(8),
52 /** 16x16 pixels */
53 x16(16),
54 /** 24x24 pixels */
55 x24(24),
56 /** 32x32 pixels */
57 x32(32),
58 /** 64x64 pixels */
59 x64(64);
60
61 private int size;
62
63 private Size(int size) {
64 this.size = size;
65 }
66
67 /**
68 * Return the size in pixels.
69 *
70 * @return the size
71 */
72 public int getSize() {
73 return size;
74 }
75 }
76
77 static private Map<String, ImageIcon> map = new HashMap<String, ImageIcon>();
78
79 /**
80 * Generate a new image.
81 *
82 * @param name the name of the resource
83 * @param size the requested size
84 *
85 * @return the image, or NULL if it does not exist or does not exist at that
86 * size
87 */
88 static public ImageIcon get(Icon name, Size size) {
89 String key = String.format("%s-%dx%d.png", name.name(), size.getSize(), size.getSize());
90 if (!map.containsKey(key)) {
91 map.put(key, generate(key));
92 }
93
94 return map.get(key);
95 }
96
97 /**
98 * Generate a new image.
99 *
100 * @param filename the file name of the resource (no directory)
101 *
102 * @return the image, or NULL if it does not exist or does not exist at that
103 * size
104 */
105 static private ImageIcon generate(String filename) {
106 try {
107 InputStream in = IOUtils.openResource(IconGenerator.class, filename);
108 if (in != null) {
109 try {
110 return new ImageIcon(IOUtils.toByteArray(in));
111 } finally {
112 in.close();
113 }
114 }
115 } catch (IOException e) {
116 e.printStackTrace();
117 }
118
119 return null;
120 }
121 }