1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package ch.elca.el4j.services.gui.swing.splash;
18
19 import java.awt.Dimension;
20 import java.awt.EventQueue;
21 import java.awt.Frame;
22 import java.awt.Graphics;
23 import java.awt.Image;
24 import java.awt.MediaTracker;
25 import java.awt.Rectangle;
26 import java.awt.Toolkit;
27 import java.awt.Window;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 public class ImageSplashScreen {
43
44
45
46
47 public static final String DEFAULT_SPLASH_SCREEN
48 = "/ch/elca/el4j/gui/swing/splash/resources/splash-screen.png";
49
50
51
52
53 private Frame m_frame;
54
55
56
57
58 private Image m_image;
59
60
61
62
63 private String m_imageResourcePath;
64
65
66
67
68 private static class SplashWindow extends Window {
69
70
71
72 private Image m_splashImage;
73
74
75
76
77
78 public SplashWindow(Frame parent, Image image) {
79 super(parent);
80 this.m_splashImage = image;
81 setSize(parent.getSize());
82 setLocation(parent.getLocation());
83 setVisible(true);
84 }
85
86
87 @Override
88 public void paint(Graphics graphics) {
89 if (m_splashImage != null) {
90 graphics.drawImage(m_splashImage, 0, 0, this);
91 }
92 }
93 }
94
95
96
97
98
99 public ImageSplashScreen() {
100 this(DEFAULT_SPLASH_SCREEN);
101 }
102
103
104
105
106
107
108
109 public ImageSplashScreen(String imageResourcePath) {
110 this.m_imageResourcePath = imageResourcePath;
111 splash();
112 }
113
114
115
116
117
118
119
120 public ImageSplashScreen(Image image) {
121 this.m_image = image;
122 splash();
123 }
124
125
126
127
128 protected void splash() {
129 m_frame = new Frame();
130 if (m_image == null) {
131 m_image = loadImage(m_imageResourcePath);
132 if (m_image == null) {
133 return;
134 }
135 }
136 MediaTracker mediaTracker = new MediaTracker(m_frame);
137 mediaTracker.addImage(m_image, 0);
138 try {
139 mediaTracker.waitForID(0);
140 } catch (InterruptedException e) {
141 return;
142 }
143 m_frame.setSize(m_image.getWidth(null), m_image.getHeight(null));
144 center();
145 new SplashWindow(m_frame, m_image);
146 }
147
148
149
150
151 public void dispose() {
152 EventQueue.invokeLater(new Runnable() {
153 public void run() {
154 m_frame.dispose();
155 m_frame = null;
156 }
157 });
158 }
159
160
161
162
163
164 private Image loadImage(String path) {
165 java.net.URL url = getClass().getResource(path);
166 if (url == null) {
167 return null;
168 } else {
169 return Toolkit.getDefaultToolkit().createImage(url);
170 }
171 }
172
173
174
175
176 private void center() {
177 Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
178 Rectangle r = m_frame.getBounds();
179 m_frame.setLocation((screen.width - r.width) / 2,
180 (screen.height - r.height) / 2);
181 }
182 }