KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jgoodies > looks > LookUtils


1 /*
2  * Copyright (c) 2001-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * o Redistributions of source code must retain the above copyright notice,
8  * this list of conditions and the following disclaimer.
9  *
10  * o Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * o Neither the name of JGoodies Karsten Lentzsch nor the names of
15  * its contributors may be used to endorse or promote products derived
16  * from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
27  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */

30
31 package com.jgoodies.looks;
32
33 import java.awt.Color JavaDoc;
34 import java.awt.Component JavaDoc;
35 import java.awt.Insets JavaDoc;
36 import java.awt.Toolkit JavaDoc;
37 import java.util.Collections JavaDoc;
38 import java.util.List JavaDoc;
39
40 import javax.swing.AbstractButton JavaDoc;
41 import javax.swing.LookAndFeel JavaDoc;
42 import javax.swing.UIManager JavaDoc;
43 import javax.swing.UnsupportedLookAndFeelException JavaDoc;
44 import javax.swing.plaf.InsetsUIResource JavaDoc;
45 import javax.swing.plaf.UIResource JavaDoc;
46
47 import com.jgoodies.looks.plastic.PlasticLookAndFeel;
48 import com.jgoodies.looks.plastic.PlasticTheme;
49
50 /**
51  * Provides convenience behavior used by the JGoodies Looks.
52  *
53  * @author Karsten Lentzsch
54  * @version $Revision: 1.6 $
55  *
56  * @see com.jgoodies.looks.FontUtils
57  */

58
59 public final class LookUtils {
60     
61     // Basics System Properties **********************************************
62

63     /**
64      * The <code>java.version</code> System Property.<p>
65      *
66      * Defaults to <code>null</code> if the runtime does not have security
67      * access to read this property or the property does not exist.
68      */

69     private static final String JavaDoc JAVA_VERSION = getSystemProperty("java.version");
70     
71     /**
72      * The <code>os.name</code> System Property. Operating system name.<p>
73      *
74      * Defaults to <code>null</code> if the runtime does not have security
75      * access to read this property or the property does not exist.
76      */

77     private static final String JavaDoc OS_NAME = getSystemProperty("os.name");
78
79     /**
80      * The <code>os.version</code> System Property. Operating system version.<p>
81      *
82      * Defaults to <code>null</code> if the runtime does not have security
83      * access to read this property or the property does not exist.
84      */

85     private static final String JavaDoc OS_VERSION = getSystemProperty("os.version");
86
87     
88     // Requesting the Java Version ********************************************
89

90     /**
91      * True if this is Java 1.4.
92      */

93     public static final boolean IS_JAVA_1_4 =
94         startsWith(JAVA_VERSION, "1.4");
95     
96     /**
97      * True if this is Java 1.4.0_*.
98      */

99     static final boolean IS_JAVA_1_4_0 = startsWith(JAVA_VERSION, "1.4.0");
100     
101     /**
102      * True if this is Java 1.4.2 or later. Since we assume Java 1.4
103      * we just check for 1.4.0 and 1.4.1.
104      */

105     public static final boolean IS_JAVA_1_4_2_OR_LATER =
106         !startsWith(JAVA_VERSION, "1.4.0") &&
107         !startsWith(JAVA_VERSION, "1.4.1");
108
109     /**
110      * True if this is Java 5.x. Java 5 still used the old version numbers,
111      * and so we check for a prefix of 1.5.
112      */

113     public static final boolean IS_JAVA_5 =
114         startsWith(JAVA_VERSION, "1.5");
115
116
117     // Requesting the Operating System Name ***********************************
118

119     /**
120      * True if this is FreeBSD.
121      */

122     public static final boolean IS_OS_FREEBSD =
123         startsWithIgnoreCase(OS_NAME, "FreeBSD");
124
125     /**
126      * True if this is Linux.
127      */

128     public static final boolean IS_OS_LINUX =
129         startsWithIgnoreCase(OS_NAME, "Linux");
130
131     /**
132      * True if this is OS/2.
133      */

134     public static final boolean IS_OS_OS2 =
135         startsWith(OS_NAME, "OS/2");
136
137     /**
138      * True if this is the Mac OS X.
139      */

140     public static final boolean IS_OS_MAC =
141         startsWith(OS_NAME, "Mac");
142
143     /**
144      * True if this is Windows.
145      */

146     public static final boolean IS_OS_WINDOWS =
147         startsWith(OS_NAME, "Windows");
148
149     /**
150      * True if this is Windows 98/ME/2000/XP.
151      */

152     public static final boolean IS_OS_WINDOWS_MODERN =
153         startsWith(OS_NAME, "Windows") && !startsWith(OS_VERSION, "4.0");
154
155     /**
156      * True if this is Windows XP.
157      */

158     public static final boolean IS_OS_WINDOWS_XP =
159         startsWith(OS_NAME, "Windows") && startsWith(OS_VERSION, "5.1");
160     
161     /**
162      * True if this is Solaris.
163      */

164     public static final boolean IS_OS_SOLARIS =
165         startsWith(OS_NAME, "Solaris");
166     
167     
168     // Other Properties *******************************************************
169

170     /**
171      * True if the Windows XP Look&amp;Feel is enabled.
172      */

173     public static final boolean IS_LAF_WINDOWS_XP_ENABLED = isWindowsXPLafEnabled();
174     
175     /**
176      * True if if the screen resolution is smaller than 120 dpi.
177      *
178      * @see Toolkit#getScreenResolution()
179      */

180     public static final boolean IS_LOW_RESOLUTION = isLowResolution();
181     
182     private static boolean loggingEnabled = true;
183     
184
185     private LookUtils() {
186         // Override default constructor; prevents instantiation.
187
}
188     
189     
190     // Accessing System Configuration *****************************************
191

192     /**
193      * Tries to look up the System property for the given key.
194      * In untrusted environments this may throw a SecurityException.
195      * In this case we catch the exception and answer <code>null</code>.
196      *
197      * @param key the name of the system property
198      * @return the system property's String value, or <code>null</code> if there's
199      * no such value, or a SecurityException has been catched
200      */

201     public static String JavaDoc getSystemProperty(String JavaDoc key) {
202         try {
203             return System.getProperty(key);
204         } catch (SecurityException JavaDoc e) {
205             log("Can't read the System property " + key + ".");
206             return null;
207         }
208     }
209
210     /**
211      * Tries to look up the System property for the given key.
212      * In untrusted environments this may throw a SecurityException.
213      * In this case, we catch the exception and answer the default value.
214      *
215      * @param key the name of the system property
216      * @param defaultValue the default value if no property exists.
217      * @return the system property's String value, or the defaultValue
218      * if there's no such value, or a SecurityException has been catched
219      */

220     public static String JavaDoc getSystemProperty(String JavaDoc key, String JavaDoc defaultValue) {
221         try {
222             return System.getProperty(key, defaultValue);
223         } catch (SecurityException JavaDoc e) {
224             log("Can't read the System property " + key + ".");
225             return defaultValue;
226         }
227     }
228     
229     /**
230      * Checks if a boolean system property has been set for the given key,
231      * and returns the associated Boolean, or <code>null</code> if no value
232      * has been set. The test for the property ignores case.
233      * If a Boolean value has been set, a message is logged
234      * with the given prefix.
235      *
236      * @param key the key used to lookup the system property value
237      * @param logMessage a prefix used when a message is logged
238      * @return <code>Boolean.TRUE</code> if the system property has been set to
239      * "true" (case ignored), <code>Boolean.FALSE</code> if it has been set to
240      * "false", <code>null</code> otherwise
241      */

242     public static Boolean JavaDoc getBooleanSystemProperty(String JavaDoc key, String JavaDoc logMessage) {
243         String JavaDoc value = getSystemProperty(key, "");
244         Boolean JavaDoc result;
245         if (value.equalsIgnoreCase("false"))
246             result = Boolean.FALSE;
247         else if (value.equalsIgnoreCase("true"))
248             result = Boolean.TRUE;
249         else
250             result = null;
251         if (result != null) {
252             LookUtils.log(
253                 logMessage
254                     + " have been "
255                     + (result.booleanValue() ? "en" : "dis")
256                     + "abled in the system properties.");
257         }
258         return result;
259     }
260     
261
262     /**
263      * Checks and answers whether the Windows XP style is enabled.
264      * This method is intended to be called only if a Windows look&feel
265      * is about to be installed or already active in the UIManager.
266      * The XP style of the Windows look&amp;feel is enabled by default on
267      * Windows XP platforms since the J2SE 1.4.2; it can be disabled either
268      * in the Windows desktop as well as in the Java runtime by setting
269      * a System property.<p>
270      *
271      * First checks the platform, platform version and Java version. Then
272      * checks whether the desktop property <tt>win.xpstyle.themeActive</tt>
273      * is set or not.
274      *
275      * @return true if the Windows XP style is enabled
276      */

277     private static boolean isWindowsXPLafEnabled() {
278         return IS_OS_WINDOWS_XP
279              && IS_JAVA_1_4_2_OR_LATER
280              && Boolean.TRUE.equals(Toolkit.getDefaultToolkit().
281                      getDesktopProperty("win.xpstyle.themeActive"))
282              && getSystemProperty("swing.noxp") == null;
283     }
284     
285     
286     /**
287      * Checks and answers whether we have a true color system.
288      *
289      * @param c the component used to determine the toolkit
290      * @return true if the component's toolkit has a pixel size >= 24
291      */

292     public static boolean isTrueColor(Component JavaDoc c) {
293         return c.getToolkit().getColorModel().getPixelSize() >= 24;
294     }
295     
296     
297     // Working with Button Margins ******************************************
298

299     /**
300      * Installs a narrow margin, if property <code>isNarrow</code> has been set.
301      *
302      * @param b the button that shall get a narrow margin
303      * @param propertyPrefix the component type prefeix for the UIDefaults
304      */

305     public static void installNarrowMargin(
306         AbstractButton JavaDoc b,
307         String JavaDoc propertyPrefix) {
308         Object JavaDoc value = b.getClientProperty(Options.IS_NARROW_KEY);
309         boolean isNarrow = Boolean.TRUE.equals(value);
310         String JavaDoc defaultsKey =
311             propertyPrefix + (isNarrow ? "narrowMargin" : "margin");
312         Insets JavaDoc insets = b.getMargin();
313         if (insets == null || insets instanceof UIResource JavaDoc) {
314             b.setMargin(UIManager.getInsets(defaultsKey));
315         }
316     }
317
318     /**
319      * Creates and returns the margin used by JButton and JToggleButton.
320      * Honors the screen resolution and the global property
321      * <code>isNarrowButtonsEnabled</code>.<p>
322      *
323      * Sun's L&F implementations use wide button margins.
324      *
325      * @param narrow true to create a narrow margin, false for a wide margin
326      * @return an Insets object used to create a button margin
327      * @see Options#getUseNarrowButtons()
328      */

329     public static Insets JavaDoc createButtonMargin(boolean narrow) {
330         int pad = narrow || Options.getUseNarrowButtons() ? 4 : 14;
331         return IS_LOW_RESOLUTION
332             ? new InsetsUIResource JavaDoc(2, pad, 1, pad)
333             : new InsetsUIResource JavaDoc(3, pad, 3, pad);
334     }
335
336     // Color Modifications **************************************************
337

338     /**
339      * Computes and returns a Color that is slightly brighter
340      * than the specified Color.
341      *
342      * @param color the color used as basis for the brightened color
343      * @return a slightly brighter color
344      */

345     public static Color JavaDoc getSlightlyBrighter(Color JavaDoc color) {
346         return getSlightlyBrighter(color, 1.1f);
347     }
348
349     /**
350      * Computes and returns a Color that is slightly brighter
351      * than the specified Color.
352      *
353      * @param color the color used as basis for the brightened color
354      * @param factor the factor used to compute the brightness
355      * @return a slightly brighter color
356      */

357     public static Color JavaDoc getSlightlyBrighter(Color JavaDoc color, float factor) {
358         float[] hsbValues = new float[3];
359         Color.RGBtoHSB(
360             color.getRed(),
361             color.getGreen(),
362             color.getBlue(),
363             hsbValues);
364         float hue = hsbValues[0];
365         float saturation = hsbValues[1];
366         float brightness = hsbValues[2];
367         float newBrightness = Math.min(brightness * factor, 1.0f);
368         return Color.getHSBColor(hue, saturation, newBrightness);
369     }
370
371     
372     // Accessing Look, Theme, and Font Settings *****************************
373

374     public static void setLookAndTheme(LookAndFeel JavaDoc laf, Object JavaDoc theme)
375         throws UnsupportedLookAndFeelException JavaDoc {
376         if ((laf instanceof PlasticLookAndFeel)
377             && (theme != null)
378             && (theme instanceof PlasticTheme)) {
379             PlasticLookAndFeel.setMyCurrentTheme((PlasticTheme) theme);
380         }
381         UIManager.setLookAndFeel(laf);
382     }
383
384     public static Object JavaDoc getDefaultTheme(LookAndFeel JavaDoc laf) {
385         return laf instanceof PlasticLookAndFeel
386             ? PlasticLookAndFeel.createMyDefaultTheme()
387             : null;
388     }
389
390     public static List JavaDoc getInstalledThemes(LookAndFeel JavaDoc laf) {
391         return laf instanceof PlasticLookAndFeel
392             ? PlasticLookAndFeel.getInstalledThemes()
393             : Collections.EMPTY_LIST;
394     }
395
396     // Minimal logging ******************************************************
397

398     /**
399      * Enables or disables the Looks logging.
400      *
401      * @param enabled true to enable logging, false to disable it
402      */

403     public static void setLoggingEnabled(boolean enabled) {
404         loggingEnabled = enabled;
405     }
406
407     /**
408      * Prints a new line to the console if logging is enabled.
409      */

410     public static void log() {
411         if (loggingEnabled) {
412             System.out.println();
413         }
414     }
415
416     /**
417      * Prints the given message to the console if logging is enabled.
418      *
419      * @param message the message to print
420      */

421     public static void log(String JavaDoc message) {
422         if (loggingEnabled) {
423             System.out.println("JGoodies Looks: " + message);
424         }
425     }
426
427     // Private Helper Methods ***********************************************
428

429     /**
430      * Checks and answers whether the screen resolution is low or high.
431      * Resolutions below 120 dpi are considere low, all others are high.
432      *
433      * @return true if the screen resolution is smaller than 120 dpi
434      */

435     private static boolean isLowResolution() {
436         return Toolkit.getDefaultToolkit().getScreenResolution() < 120;
437     }
438
439     private static boolean startsWith(String JavaDoc str, String JavaDoc prefix) {
440         return str != null && str.startsWith(prefix);
441     }
442     
443     private static boolean startsWithIgnoreCase(String JavaDoc str, String JavaDoc prefix) {
444         return str != null && str.toUpperCase().startsWith(prefix.toUpperCase());
445     }
446     
447 }
Popular Tags