KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sshtools > ui > awt > UIUtil


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sshtools.ui.awt;
21
22 import java.awt.Component JavaDoc;
23 import java.awt.Container JavaDoc;
24 import java.awt.Dimension JavaDoc;
25 import java.awt.Frame JavaDoc;
26 import java.awt.GridBagConstraints JavaDoc;
27 import java.awt.GridBagLayout JavaDoc;
28 import java.awt.Image JavaDoc;
29 import java.awt.MediaTracker JavaDoc;
30 import java.awt.Rectangle JavaDoc;
31 import java.awt.Toolkit JavaDoc;
32 import java.awt.Window JavaDoc;
33 import java.net.MalformedURLException JavaDoc;
34 import java.net.URL JavaDoc;
35 import java.text.MessageFormat JavaDoc;
36 import java.util.Hashtable JavaDoc;
37
38 /**
39  * Useful UI utilies for AWT.
40  *
41  * @author $Author: brett $
42  */

43 public class UIUtil {
44   
45   private static URL JavaDoc codebase;
46   private static Hashtable JavaDoc imageCache = new Hashtable JavaDoc();
47   private static Hashtable JavaDoc stockIds = new Hashtable JavaDoc();
48   private static Frame JavaDoc sharedFrame;
49
50   /**
51    * The central position in an area. Used for
52    * both compass-direction constants (NORTH, etc.)
53    * and box-orientation constants (TOP, etc.).
54    */

55   public static final int CENTER = 0;
56
57   /**
58    * Compass-direction North (up).
59    */

60   public static final int NORTH = 1;
61   /**
62    * Compass-direction north-east (upper right).
63    */

64   public static final int NORTH_EAST = 2;
65   /**
66    * Compass-direction east (right).
67    */

68   public static final int EAST = 3;
69   /**
70    * Compass-direction south-east (lower right).
71    */

72   public static final int SOUTH_EAST = 4;
73   /**
74    * Compass-direction south (down).
75    */

76   public static final int SOUTH = 5;
77   /**
78    * Compass-direction south-west (lower left).
79    */

80   public static final int SOUTH_WEST = 6;
81   /**
82    * Compass-direction west (left).
83    */

84   public static final int WEST = 7;
85   /**
86    * Compass-direction north west (upper left).
87    */

88   public static final int NORTH_WEST = 8;
89
90   /**
91    * Wait for an image to load.
92    *
93    * @param image image to wait for
94    * @param component image producer component
95    * @return image or <code>null</code> if the image did not load
96    */

97   public static Image JavaDoc waitFor(Image JavaDoc image, Component JavaDoc component) {
98     if (image != null) {
99       MediaTracker JavaDoc tracker = new MediaTracker JavaDoc(component);
100       tracker.addImage(image, 0);
101       try {
102         tracker.waitForAll();
103         return image;
104       }
105       catch (InterruptedException JavaDoc ie) {
106         ie.printStackTrace();
107       }
108       if (tracker.isErrorAny()) {
109         /* DEBUG */System.err.println(MessageFormat.format(Messages.getString("UIUtil.imageDidNotLoad"), new Object JavaDoc[] { image.toString() } ) ); //$NON-NLS-1$
110
}
111     }
112     /* DEBUG */System.err.println(Messages.getString("UIUtil.noImage")); //$NON-NLS-1$
113
return null;
114   }
115
116   /**
117    * If images are to be loaded in an applet, the this method should be called
118    * during the applets initialisation so they can be located.
119    *
120    * @param codebase applet codebase
121    */

122   public static void setCodeBase(URL JavaDoc codebase) {
123     UIUtil.codebase = codebase;
124   }
125
126   /**
127    * Load an image using the specified <code>Class</code>es <code>ClassLoader</code>
128        * and the given resource name. <code>null</code> will be returned if the image
129    * could not be loaded.
130    *
131    * @param clazz class to get class loader from
132    * @param resource resource name
133    */

134   public static Image JavaDoc loadImage(Class JavaDoc clazz, String JavaDoc resource) {
135     String JavaDoc path = resource;
136
137     /*
138     String path = null;
139     if (resource.startsWith("/")) {
140       path = resource;
141     }
142     else {
143       int idx = clazz.getName().lastIndexOf('.');
144       String packageName = idx == -1 ? null : clazz.getName().substring(0, idx);
145       path = packageName == null ? "" : "/" + packageName;
146       path = path.replace('.', '/');
147       path += ("/" + resource);
148     }
149     */

150     URL JavaDoc url = clazz.getResource(path);
151     Image JavaDoc img = null;
152     if (url != null) {
153       img = (Image JavaDoc)imageCache.get(url.toExternalForm());
154       if(img == null) {
155         img = Toolkit.getDefaultToolkit().getImage(url);
156         if(img != null) {
157           imageCache.put(url.toExternalForm(), img);
158         }
159       }
160     }
161     else {
162       if(codebase != null) {
163         URL JavaDoc loc;
164         try {
165           loc = new URL JavaDoc(codebase, resource);
166           img = (Image JavaDoc)imageCache.get(loc.toExternalForm());
167           if(img == null) {
168             img = Toolkit.getDefaultToolkit().getImage(loc);
169             if(img != null) {
170               imageCache.put(loc.toExternalForm(), img);
171             }
172           }
173         } catch (MalformedURLException JavaDoc e) {
174           e.printStackTrace();
175           img = null;
176         }
177         
178       }
179     }
180     if(img == null) {
181       img = (Image JavaDoc)imageCache.get(path);
182       if(img == null) {
183         img = Toolkit.getDefaultToolkit().getImage(path);
184         if(img != null) {
185           imageCache.put(path, img);
186         }
187       }
188     }
189     
190     if(img == null) {
191       System.err.println(MessageFormat.format(Messages.getString("UIUtil.couldNotLocateImage"), new Object JavaDoc[] { resource } ) ); //$NON-NLS-1$
192
}
193     return img;
194   }
195
196   /**
197    * Add a component to a container that is using a <code>GridBagLayout</code>, together with its constraints and the <code>GridBagConstraints.gridwidth</code>
198    * value.
199    *
200    * @param parent parent container
201    * @param componentToAdd component to add
202    * @param constraints contraints
203    * @param pos grid width position
204    *
205    * @throws IllegalArgumentException
206    */

207   public static void gridBagAdd(Container JavaDoc parent, Component JavaDoc componentToAdd,
208                                 GridBagConstraints JavaDoc constraints, int pos) {
209     if (! (parent.getLayout()instanceof GridBagLayout JavaDoc)) {
210       throw new IllegalArgumentException JavaDoc(Messages.getString("UIUtil.parentMustHaveGridBagLayout")); //$NON-NLS-1$
211
}
212
213     //
214
GridBagLayout JavaDoc layout = (GridBagLayout JavaDoc) parent.getLayout();
215
216     //
217
constraints.gridwidth = pos;
218     layout.setConstraints(componentToAdd, constraints);
219     parent.add(componentToAdd);
220   }
221
222   /**
223    * Get the top level window that contains the given component.
224    *
225    * @param c component
226    * @return window
227    */

228   public static Window JavaDoc getWindowAncestor(Component JavaDoc c) {
229     for (Container JavaDoc p = c.getParent(); p != null; p = p.getParent()) {
230       if (p instanceof Window JavaDoc) {
231         return (Window JavaDoc) p;
232       }
233     }
234     return null;
235   }
236
237   /**
238    * Get the top level fra,e that contains the given component.
239    *
240    * @param c component
241    * @return frame
242    */

243   public static Frame JavaDoc getFrameAncestor(Component JavaDoc c) {
244     if(c == null) {
245       return null;
246     }
247     for (Container JavaDoc p = c.getParent(); p != null; p = p.getParent()) {
248       if (p instanceof Frame JavaDoc) {
249         return (Frame JavaDoc) p;
250       }
251     }
252     return null;
253   }
254
255
256   /**
257        * Position a component on the screen (must be a <code>java.awt.Window</code> to
258    * be useful)
259    *
260    * @param p postion from <code>SwingConstants</code>
261    * @param c component
262    */

263   public static void positionComponent(int p, Component JavaDoc c) {
264
265     /* TODO This is very lame doesnt require the component to position around, just assuming
266      * its a window.
267      */

268
269     Rectangle JavaDoc d = null;
270     try {
271 //#ifdef JAVA1
272
/*
273 throw new Exception();
274 */

275 //#else
276
d = c.getGraphicsConfiguration().getDevice().getDefaultConfiguration().
277           getBounds();
278 //#endif JAVA1
279
}
280     catch (Throwable JavaDoc t) {
281     }
282     if(d == null) {
283       Dimension JavaDoc s = Toolkit.getDefaultToolkit().getScreenSize();
284       d = new Rectangle JavaDoc(0, 0, s != null ? s.width : 800, s != null ? s.height : 600);
285       // TODO Find a better way of taking care of centering on dual-head displays
286
if( d.width > ( 2 * d.height ) ) {
287         d.width = d.width / 2;
288       }
289     }
290
291     switch (p) {
292       case NORTH_WEST:
293         c.setLocation(d.x, d.y);
294         break;
295       case NORTH:
296         c.setLocation(d.x + (d.width - c.getSize().width) / 2, d.y);
297         break;
298       case NORTH_EAST:
299         c.setLocation(d.x + (d.width - c.getSize().width), d.y);
300         break;
301       case WEST:
302         c.setLocation(d.x, d.y + (d.height - c.getSize().height) / 2);
303         break;
304       case SOUTH_WEST:
305         c.setLocation(d.x, d.y + (d.height - c.getSize().height));
306         break;
307       case EAST:
308         c.setLocation(d.x + d.width - c.getSize().width,
309                       d.y + (d.height - c.getSize().height) / 2);
310         break;
311       case SOUTH_EAST:
312         c.setLocation(d.x + (d.width - c.getSize().width),
313                       d.y + (d.height - c.getSize().height) - 30);
314         break;
315       case CENTER:
316         c.setLocation(d.x + (d.width - c.getSize().width) / 2,
317                       d.y + (d.height - c.getSize().height) / 2);
318         break;
319     }
320   }
321
322   /**
323    * @return
324    */

325   public static Frame JavaDoc getSharedFrame() {
326     if(sharedFrame == null) {
327       sharedFrame = new Frame JavaDoc();
328     }
329     return sharedFrame;
330   }
331   
332   /**
333    * Get a stock image
334    *
335    * @param id stock image id. See {@link com.sshtools.ui.StockIcons} for constants.
336    * @param clazz the {@link Class} to derive a {@link ClassLoader} from to load the image with.
337    */

338   public static Image JavaDoc getStockImage(String JavaDoc id, Class JavaDoc clazz) {
339       String JavaDoc resource = (String JavaDoc)stockIds.get(id);
340       return loadImage(clazz, resource == null ? id : resource);
341   }
342   
343   /**
344    * Set an alternative stock image resource. Setting a <code>null</code>
345    * resource will remove any custom resource and rever to the default.
346    *
347    * @param id stock image id. See {@link com.sshtools.ui.StockIcons} for constants.
348    * @param resource the resource path to use to load the image.
349    */

350   public static void setStockImage(String JavaDoc id, String JavaDoc resource) {
351       if(resource == null) {
352           stockIds.remove(id);
353       }
354       else {
355           stockIds.put(id, resource);
356       }
357   }
358 }
359
Popular Tags