KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sshtools > ui > swing > 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.swing;
21
22 import java.awt.Component JavaDoc;
23 import java.awt.Dimension JavaDoc;
24 import java.awt.Font JavaDoc;
25 import java.awt.GraphicsConfiguration JavaDoc;
26 import java.awt.GraphicsDevice JavaDoc;
27 import java.awt.GridBagConstraints JavaDoc;
28 import java.awt.GridBagLayout JavaDoc;
29 import java.awt.Image JavaDoc;
30 import java.awt.Rectangle JavaDoc;
31 import java.awt.Toolkit JavaDoc;
32 import java.awt.event.KeyEvent JavaDoc;
33 import java.awt.image.BufferedImage JavaDoc;
34 import java.awt.image.ImageObserver JavaDoc;
35 import java.io.PrintWriter JavaDoc;
36 import java.io.StringWriter JavaDoc;
37 import java.util.StringTokenizer JavaDoc;
38
39 import javax.swing.Icon JavaDoc;
40 import javax.swing.ImageIcon JavaDoc;
41 import javax.swing.JComboBox JavaDoc;
42 import javax.swing.JComponent JavaDoc;
43 import javax.swing.JList JavaDoc;
44 import javax.swing.JOptionPane JavaDoc;
45 import javax.swing.KeyStroke JavaDoc;
46 import javax.swing.SwingConstants JavaDoc;
47 import javax.swing.UIManager JavaDoc;
48 import javax.swing.text.SimpleAttributeSet JavaDoc;
49 import javax.swing.text.StyleConstants JavaDoc;
50
51 /**
52  * Useful UI utilies.
53  *
54  * @author $Author: brett $
55  */

56 public class UIUtil implements SwingConstants JavaDoc {
57
58     /**
59      * Select an item in a {@link JList} given an items string value
60      *
61      * @param string string to select in list
62      * @param list list
63      */

64     public static void selectStringInList(String JavaDoc string, JList JavaDoc list) {
65         for (int i = 0; i < list.getModel().getSize(); i++) {
66             if (String.valueOf(list.getModel().getElementAt(i)).equals(string)) {
67                 list.setSelectedIndex(i);
68                 return;
69             }
70         }
71     }
72
73     /**
74      * Select an item in a {@link JComboBox} given an items string value
75      *
76      * @param string string to select in list
77      * @param list list
78      */

79     public static void selectStringInList(String JavaDoc string, JComboBox JavaDoc list) {
80         for (int i = 0; i < list.getModel().getSize(); i++) {
81             if (String.valueOf(list.getModel().getElementAt(i)).equals(string)) {
82                 list.setSelectedIndex(i);
83                 return;
84             }
85         }
86     }
87
88     /**
89      * Convert a string in the format of <code>x,y,width,height</code> in to a
90      * {@link Rectangle} object. Suitable for retrieving rectangles from
91      * property files, XML files etc. The supplied default value will be
92      * returned if the string is not in the correct format or is
93      * <code>null</code>.
94      *
95      * @param string string in format <code>x,y,width,height</code>
96      * @param defaultValue default rectangle
97      * @return rectangle
98      */

99     public static Rectangle JavaDoc stringToRectangle(String JavaDoc string, Rectangle JavaDoc defaultValue) {
100         if (string == null) {
101             return defaultValue;
102         }
103         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(string, ","); //$NON-NLS-1$
104
try {
105             return new Rectangle JavaDoc(Integer.parseInt(t.nextToken()), Integer.parseInt(t.nextToken()), Integer.parseInt(t.nextToken()),
106                 Integer.parseInt(t.nextToken()));
107         } catch (Exception JavaDoc e) {
108             return defaultValue;
109         }
110     }
111
112     /**
113      * Convert a {@link Rectangle} object to a comma separated string in the
114      * format of <code>x,y,width,height</code>. Suitable for storing
115      * rectangles in property files, XML files etc.
116      *
117      * @param rectangle rectangle
118      * @return comman separated string x,y,width,height
119      */

120     public static String JavaDoc rectangleToString(Rectangle JavaDoc rectangle) {
121         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(String.valueOf(rectangle.x));
122         buf.append(',');
123         buf.append(String.valueOf(rectangle.y));
124         buf.append(',');
125         buf.append(String.valueOf(rectangle.width));
126         buf.append(',');
127         buf.append(String.valueOf(rectangle.height));
128         return buf.toString();
129     }
130
131     /**
132      * Parse a string in the format of <code>[character]</code> to create an
133      * Integer that may be used for an action.
134      *
135      * @param character mnemonic string
136      * @return mnemonic
137      */

138     public static Integer JavaDoc parseMnemonicString(String JavaDoc string) {
139         try {
140             return new Integer JavaDoc(string);
141         } catch (Throwable JavaDoc t) {
142             return new Integer JavaDoc(-1);
143         }
144     }
145
146     /**
147      * Parse a string in the format of [ALT+|CTRL+|SHIFT+] <keycode>to create a
148      * keystroke. This can be used to define accelerators from resource bundles
149      *
150      * @param string accelerator string
151      * @return keystroke
152      */

153     public static KeyStroke JavaDoc parseAcceleratorString(String JavaDoc string) {
154         if (string == null || string.equals("")) { //$NON-NLS-1$
155
return null;
156         }
157         StringTokenizer JavaDoc t = new StringTokenizer JavaDoc(string, "+"); //$NON-NLS-1$
158
int mod = 0;
159         int key = -1;
160         while (t.hasMoreTokens()) {
161             String JavaDoc x = t.nextToken();
162             if (x.equalsIgnoreCase("ctrl")) { //$NON-NLS-1$
163
mod += KeyEvent.CTRL_MASK;
164             } else if (x.equalsIgnoreCase("shift")) { //$NON-NLS-1$
165
mod += KeyEvent.SHIFT_MASK;
166             } else if (x.equalsIgnoreCase("alt")) { //$NON-NLS-1$
167
mod += KeyEvent.ALT_MASK;
168             } else {
169                 try {
170                     java.lang.reflect.Field JavaDoc f = KeyEvent JavaDoc.class.getField(x);
171                     key = f.getInt(null);
172                 } catch (Throwable JavaDoc ex) {
173                     ex.printStackTrace();
174                 }
175             }
176         }
177         if (key != -1) {
178             KeyStroke JavaDoc ks = KeyStroke.getKeyStroke(key, mod);
179             return ks;
180         }
181         return null;
182
183     }
184
185     /**
186      * Add a component to a container that is using a <code>GridBagLayout</code>,
187      * together with its constraints and the
188      * <code>GridBagConstraints.gridwidth</code> value.
189      *
190      * @param parent parent container
191      * @param componentToAdd component to add
192      * @param constraints contraints
193      * @param pos grid width position
194      *
195      * @throws IllegalArgumentException
196      */

197     public static void jGridBagAdd(JComponent JavaDoc parent, Component JavaDoc componentToAdd, GridBagConstraints JavaDoc constraints, int pos) {
198         if (!(parent.getLayout() instanceof GridBagLayout JavaDoc)) {
199             throw new IllegalArgumentException JavaDoc(Messages.getString("UIUtil.parentMustHaveAGridBagLayout")); //$NON-NLS-1$
200
}
201
202         //
203
GridBagLayout JavaDoc layout = (GridBagLayout JavaDoc) parent.getLayout();
204
205         //
206
constraints.gridwidth = pos;
207         layout.setConstraints(componentToAdd, constraints);
208         parent.add(componentToAdd);
209     }
210
211     /**
212      * Position a component on the screen (must be a
213      * <code>java.awt.Window</code> to be useful)
214      *
215      * @param p postion from <code>SwingConstants</code>
216      * @param c component
217      */

218     public static void positionComponent(int p, Component JavaDoc c) {
219
220         positionComponent(p, c, c);
221
222     }
223
224     public static void positionComponent(int p, Component JavaDoc c, Component JavaDoc o) {
225         Rectangle JavaDoc d = null;
226         /*
227          * TODO This is very lame doesnt require the component to position
228          * around, just assuming its a window.
229          */

230         try {
231
232             // #ifdef JAVA1
233
/*
234              * throw new Exception();
235              */

236
237             // #else
238
GraphicsConfiguration JavaDoc config = o.getGraphicsConfiguration();
239             GraphicsDevice JavaDoc dev = config.getDevice();
240             d = config.getBounds();
241
242             // #endif JAVA1
243
} catch (Throwable JavaDoc t) {
244         }
245         positionComponent(p, c, d);
246         
247     }
248
249     public static void positionComponent(int p, Component JavaDoc c, Rectangle JavaDoc d) {
250         if (d == null) {
251             Dimension JavaDoc s = Toolkit.getDefaultToolkit().getScreenSize();
252             d = new Rectangle JavaDoc(0, 0, s != null ? s.width : 800, s != null ? s.height : 600);
253         }
254
255         switch (p) {
256             case NORTH_WEST:
257                 c.setLocation(d.x, d.y);
258                 break;
259             case NORTH:
260                 c.setLocation(d.x + (d.width - c.getSize().width) / 2, d.y);
261                 break;
262             case NORTH_EAST:
263                 c.setLocation(d.x + (d.width - c.getSize().width), d.y);
264                 break;
265             case WEST:
266                 c.setLocation(d.x, d.y + (d.height - c.getSize().height) / 2);
267                 break;
268             case SOUTH_WEST:
269                 c.setLocation(d.x, d.y + (d.height - c.getSize().height));
270                 break;
271             case EAST:
272                 c.setLocation(d.x + d.width - c.getSize().width, d.y + (d.height - c.getSize().height) / 2);
273                 break;
274             case SOUTH_EAST:
275                 c.setLocation(d.x + (d.width - c.getSize().width), d.y + (d.height - c.getSize().height) - 30);
276                 break;
277             case CENTER:
278                 c.setLocation(d.x + (d.width - c.getSize().width) / 2, d.y + (d.height - c.getSize().height) / 2);
279                 break;
280         }
281     }
282     /**
283      * Show an error message with detail
284      *
285      * @param parent
286      * @param title
287      * @param exception
288      */

289     public static void showErrorMessage(Component JavaDoc parent, String JavaDoc title, Throwable JavaDoc exception) {
290         showErrorMessage(parent, null, title, exception);
291     }
292
293     /**
294      * Show an error message with toggable detail
295      *
296      * @param parent
297      * @param mesg
298      * @param title
299      * @param exception
300      */

301     public static void showErrorMessage(Component JavaDoc parent, String JavaDoc mesg, String JavaDoc title, Throwable JavaDoc exception) {
302         boolean details = false;
303         while (true) {
304             String JavaDoc[] opts = new String JavaDoc[] {
305                             details ? "Hide Details" : "Details", "Ok"
306             };
307             StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
308             if (mesg != null) {
309                 buf.append(mesg);
310             }
311             appendException(exception, 0, buf, details);
312             MultilineLabel message = new MultilineLabel(buf.toString());
313             int opt = JOptionPane.showOptionDialog(parent, message, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE,
314                 null, opts, opts[1]);
315             if (opt == 0) {
316                 details = !details;
317             } else {
318                 break;
319             }
320         }
321     }
322
323     private static void appendException(Throwable JavaDoc exception, int level, StringBuffer JavaDoc buf, boolean details) {
324         try {
325             if (((exception != null) && (exception.getMessage() != null)) && (exception.getMessage().length() > 0)) {
326                 if (details && (level > 0)) {
327                     buf.append("\n \nCaused by ...\n");
328                 }
329                 buf.append(exception.getMessage());
330             }
331             if (details) {
332                 if (exception != null) {
333                     if ((exception.getMessage() != null) && (exception.getMessage().length() == 0)) {
334                         buf.append("\n \nCaused by ...");
335                     } else {
336                         buf.append("\n \n");
337                     }
338                 }
339                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
340                 if (exception != null) {
341                     exception.printStackTrace(new PrintWriter JavaDoc(sw));
342                 }
343                 buf.append(sw.toString());
344             }
345             try {
346                 java.lang.reflect.Method JavaDoc method = exception.getClass().getMethod("getCause", new Class JavaDoc[] {});
347                 Throwable JavaDoc cause = (Throwable JavaDoc) method.invoke(exception, (Object JavaDoc[])null);
348                 if (cause != null) {
349                     appendException(cause, level + 1, buf, details);
350                 }
351             } catch (Exception JavaDoc e) {
352             }
353         } catch (Throwable JavaDoc ex) {
354         }
355     }
356
357     public static Image JavaDoc scaleWidth(int width, Image JavaDoc image, ImageObserver JavaDoc observer) {
358         if(image == null) {
359             return null;
360         }
361         double scale = (double)width / (double)image.getWidth(observer);
362         return image.getScaledInstance(width, (int)((double)image.getHeight(observer) * scale), Image.SCALE_SMOOTH);
363     }
364
365     public static Image JavaDoc scaleHeight(int height, Image JavaDoc image, ImageObserver JavaDoc observer) {
366         if(image == null) {
367             return null;
368         }
369         double scale = (double)height / (double)image.getHeight(observer);
370         return image.getScaledInstance((int)((double)image.getWidth(observer) * scale), height, Image.SCALE_SMOOTH);
371     }
372
373     public static SimpleAttributeSet JavaDoc getDefaultAttributeSet() {
374             SimpleAttributeSet JavaDoc attrSet = new SimpleAttributeSet JavaDoc();
375     // Font f = new Font("Arial", Font.PLAIN, 11);
376
Font JavaDoc f = UIManager.getFont("Label.font");
377             StyleConstants.setFontFamily(attrSet, f.getFamily());
378             StyleConstants.setFontSize(attrSet, f.getSize());
379             StyleConstants.setBold(attrSet, false);
380             StyleConstants.setItalic(attrSet, ( f.getStyle() & Font.ITALIC ) != 0);
381             return attrSet;
382         }
383
384     public static Image JavaDoc getImage(ImageIcon JavaDoc imageIcon) {
385         return imageIcon != null ? imageIcon.getImage() : null;
386     }
387
388     public static Image JavaDoc getImage(Icon JavaDoc icon) {
389         BufferedImage JavaDoc bim = new BufferedImage JavaDoc(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
390         icon.paintIcon(null, bim.getGraphics(), 0, 0);
391         return bim;
392     }
393
394     public static Image JavaDoc getFrameImage(Icon JavaDoc icon) {
395         if(icon == null) {
396             return null;
397         }
398         BufferedImage JavaDoc bim = new BufferedImage JavaDoc(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
399         icon.paintIcon(null, bim.getGraphics(), 0, 0);
400         return bim;
401     }
402 }
403
Popular Tags