View Javadoc

1   /**
2    * This program is free software: you can redistribute it and/or modify
3    * it under the terms of the GNU General Public License as published by
4    * the Free Software Foundation, version 3.
5    *
6    * This program is distributed in the hope that it will be useful,
7    * but WITHOUT ANY WARRANTY; without even the implied warranty of
8    * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9    * GNU General Public License for more details.
10   *
11   * You should have received a copy of the GNU General Public License
12   * along with this program. If not, see <http://www.gnu.org/licenses/>.
13   */
14  
15  package net.curre.prefcount.util;
16  
17  import javax.swing.ImageIcon;
18  import javax.swing.JFrame;
19  import javax.swing.JLabel;
20  import javax.swing.JOptionPane;
21  import javax.swing.JPanel;
22  import javax.swing.JTextField;
23  import javax.swing.UIManager;
24  import java.awt.Color;
25  import java.awt.Component;
26  import java.awt.Dimension;
27  import java.awt.Font;
28  import java.awt.FontMetrics;
29  import java.awt.Graphics2D;
30  import java.awt.GraphicsEnvironment;
31  import java.awt.Insets;
32  import java.awt.Rectangle;
33  import java.util.Calendar;
34  import java.util.logging.Logger;
35  
36  import net.curre.prefcount.App;
37  import net.curre.prefcount.PrefCountRegistry;
38  import net.curre.prefcount.gui.aa.AAJLabel;
39  import net.curre.prefcount.gui.aa.AAJPanel;
40  import net.curre.prefcount.gui.type.UIItem;
41  
42  import org.apache.commons.lang.StringUtils;
43  import org.apache.commons.lang.time.FastDateFormat;
44  
45  /**
46   * Object of this class represents a set of
47   * common utilities for prefcount.
48   * <p/>
49   * Created date: Apr 7, 2007
50   *
51   * @author Yevgeny Nyden
52   */
53  public class Utilities {
54  
55    /** Private class logger. */
56    private static Logger log = Logger.getLogger(Utilities.class.toString());
57  
58    /** Enumeration tha represents a field type. */
59    public static enum FieldType {
60  
61      UNDEFINED, INTEGER, DOUBLE
62    }
63  
64    /** Enumeration tha represents a platform/os type. */
65    public static enum PlatformType {
66  
67      MAC_OS, LINUX, WINDOWS, UNKNOWN
68    }
69  
70    /** Helper object to be used in the printTime() method. */
71    public static Calendar lastTime = Calendar.getInstance();
72  
73    /**
74     * Validates if the passed component value is valid.
75     *
76     * @param field Input field, which value to validate.
77     * @param type  Type of the value to check (i.e. Utilities.TYPE_INTEGER).
78     * @return true If the component value is valid; false otherwise.
79     */
80    public static boolean validateTextField(JTextField field, FieldType type) {
81      String str = field.getText().trim();
82      switch (type) {
83        case INTEGER:
84          return StringUtils.isNumeric(str);
85        case DOUBLE:
86          try {
87            Double.parseDouble(str);
88            return true;
89          } catch (NumberFormatException e) {
90            return false;
91          }
92        default:
93          log.severe("ERROR: validateTextField: Unknown type: " + type);
94      }
95      return false;
96    }
97  
98    /**
99     * Computes the X coordinate for the object so that it
100    * gets centered in the container, which is basically:
101    * (containerWidth - objectWidth) / 2;
102    *
103    * @param containerWidth container width (where the object is drawn).
104    * @param objectWidth    the object width (what is being centered).
105    * @return X coordinate for the object, so it is centered in the container.
106    */
107   public static int computeCenterX(int containerWidth, int objectWidth) {
108     return (containerWidth - objectWidth) / 2;
109   }
110 
111   /**
112    * Returns capitalized first letter from the passed text field
113    * or null if the text field is empty.
114    *
115    * @param field Text field to read.
116    * @return Capitalized first letter from the passed text field
117    *         or null if the text field is empty.
118    */
119   public static String getFirstLetterFromField(JTextField field) {
120     String str = field.getText();
121     if (StringUtils.isBlank(str)) {
122       return null;
123     }
124     return str.trim().substring(0, 1).toUpperCase();
125   }
126 
127   /**
128    * Gets and parses text from the given text field.
129    * If the text field is null or contains an empty
130    * string or white space only, 0 if returned.
131    *
132    * @param field Text field to parse.
133    * @return Parsed integer.
134    * @throws NumberFormatException If text field contains an invalid integer.
135    */
136   public static int parseIntFromTextField(JTextField field) {
137     if (field != null) {
138       String value = field.getText().trim();
139       if (value.length() != 0) {
140         return Integer.parseInt(value);
141       }
142     }
143     return 0;
144   }
145 
146   /**
147    * Computes the size of the passed String.
148    *
149    * @param g2  Graphics object to use.
150    * @param str String to be measured.
151    * @return The size of the passed string as a <code>Dimension</code> object.
152    */
153   public static Dimension determineSizeOfString(Graphics2D g2, String str) {
154     FontMetrics metrics = g2.getFontMetrics(g2.getFont());
155     int height = metrics.getHeight();
156     int width = metrics.stringWidth(str);
157     return new Dimension(width, height);
158   }
159 
160   /**
161    * Creates a gif image for the given file name
162    * (image file is expected to be in the images/ directory
163    * relative to the net.curre.prefcount.App class).
164    *
165    * @param fileName File name without extention.
166    * @return The created ImageIcon object.
167    */
168   public static ImageIcon createImage(String fileName) {
169     return new ImageIcon(App.class.getResource("images/" + fileName + ".gif"));
170   }
171 
172   /**
173    * Underlines a letter in the given string at
174    * the given position; note, that the string is
175    * converted to html.
176    *
177    * @param str String to underline.
178    * @param ind Letter index, which to underline.
179    * @return A string with underlined letter at the given position.
180    */
181   public static String underlineLetter(String str, int ind) {
182     return "<HTML>" + str.substring(0, ind) + "<U>" + str.charAt(ind) +
183         "</U>" + str.substring(ind + 1);
184 
185   }
186 
187   /**
188    * Creates a new color that is darker than the
189    * passed color according to the passed int parameter.
190    *
191    * @param color    Model color.
192    * @param decrease Value to be subtracted from the RGB chanels of the model color.
193    * @return New darker color.
194    */
195   public static Color createDarkerColor(Color color, int decrease) {
196     return new Color(color.getRed() - decrease,
197                      color.getGreen() - decrease,
198                      color.getBlue() - decrease);
199   }
200 
201   /**
202    * Opens a new frame and displays a warning message in it
203    * (given its resource key) with two buttons OK and CANCEL.
204    *
205    * @param messageKey Message key.
206    * @param yesKey     Yes button test key.
207    * @param cancelKey  Cancel button text key.
208    * @return return true if the user has chosen to continue (hit the OK button);
209    *         false if the CANCEL optoins was chosen.
210    */
211   public static boolean displayOkCancelMessage(String messageKey, String yesKey, String cancelKey) {
212     String msg = LocaleExt.getString(messageKey);
213     String yes = LocaleExt.getString(yesKey);
214     String cancel = LocaleExt.getString(cancelKey);
215 
216     int answer = JOptionPane.showOptionDialog(
217         PrefCountRegistry.getInstance().getMainWindow(), msg, "Warning", JOptionPane.OK_CANCEL_OPTION,
218         JOptionPane.WARNING_MESSAGE, null, new Object[]{yes, cancel}, cancel);
219 
220     return answer == JOptionPane.OK_OPTION;
221   }
222 
223   /**
224    * This method is used for debugging purposes
225    * to print timestamps and the elapsed time since the last
226    * call to this method.
227    *
228    * @param msg Message to add to the print statement.
229    */
230   public static void printTime(String msg) {
231     Calendar currTime = Calendar.getInstance();
232     Calendar diff = Calendar.getInstance();
233     long currMls = currTime.getTimeInMillis();
234     diff.setTimeInMillis(currMls - lastTime.getTimeInMillis());
235     FastDateFormat f = FastDateFormat.getInstance("mm:ss:SSS");
236     System.out.println("TIME:::::: " + f.format(currTime.getTime()) +
237         " (" + f.format(diff) + ") - " + msg);
238     lastTime.setTimeInMillis(currMls);
239   }
240 
241   /** Prints available looks and feels. */
242   public static void printLookAndFeels() {
243     UIManager.LookAndFeelInfo laf[] = UIManager.getInstalledLookAndFeels();
244     for (int i = 0, n = laf.length; i < n; i++) {
245       System.out.print("LAF Name: " + laf[i].getName() + "\t");
246       System.out.println("  LAF Class name: " + laf[i].getClassName());
247     }
248   }
249 
250   /** Displays available fonts in a frame. */
251   public static void printAvailableFonts() {
252     JFrame f = new JFrame("Testing Fonts");
253     f.setSize(400, 400);
254     JPanel mainPanel = new AAJPanel();
255     f.add(mainPanel);
256     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
257     String fontNames[] = ge.getAvailableFontFamilyNames();
258     int j = fontNames.length;
259     for (int i = 0; i < j; ++i) {
260       JPanel panel = new JPanel();
261       JLabel label = new AAJLabel(fontNames[i]);
262       label.setFont(new Font(fontNames[i], Font.PLAIN, 16));
263       panel.add(label);
264       mainPanel.add(panel);
265 
266       System.out.println(fontNames[i]);
267     }
268     f.pack();
269     f.setVisible(true);
270   }
271 
272   /**
273    * Determines the platform/os type we are running on.
274    *
275    * @return A PlatformType enumeration that represents the platform/os.
276    */
277   public static PlatformType getPlatformType() {
278     if (System.getProperty("mrj.version") == null) {
279       String osProp = System.getProperty("os.name").toLowerCase();
280       if (osProp.indexOf("windows") != -1) {
281         return PlatformType.WINDOWS;
282       } else if (osProp.indexOf("mac") != -1) {
283         return PlatformType.MAC_OS;
284       } else if (osProp.indexOf("linux") != -1) {
285         return PlatformType.LINUX;
286       } else {
287         return PlatformType.UNKNOWN;
288       }
289     }
290     return PlatformType.MAC_OS;
291   }
292 
293   /**
294    * Returns true if we are running on Mac OS; false otehrwise.
295    *
296    * @return True if we are on Mac OS; false otherwise.
297    */
298   public static boolean isMacOs() {
299     return getPlatformType() == PlatformType.MAC_OS;
300   }
301 
302   /**
303    * Computes preferred size.
304    *
305    * @param panel panel to compute the preferred size of.
306    * @return dimension object that represent the size.
307    */
308   public static Dimension getPreferredSize(JPanel panel) {
309     Dimension preferredSize = new Dimension();
310     for (Component component : panel.getComponents()) {
311       Rectangle bounds = component.getBounds();
312       preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
313       preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
314     }
315     Insets insets = panel.getInsets();
316     preferredSize.width += insets.right;
317     preferredSize.height += insets.bottom;
318     return preferredSize;
319   }
320 
321   /**
322    * Generates button label text for the given UI item.
323    *
324    * @param item UI item to generate text for.
325    * @return label according to the current locale.
326    */
327   public static String generateButtonText(UIItem item) {
328     String label = LocaleExt.getString(item.getTextKey());
329 
330     String shortcutKey = item.getShortcutKey();
331     if (shortcutKey != null) {
332       String shortcut = LocaleExt.getString(shortcutKey);
333       String shortcutIndexKey = item.getShortcutIndexKey();
334       if (shortcutIndexKey != null) {
335         String shortcutIndex = LocaleExt.getString(shortcutIndexKey);
336         int index = Integer.valueOf(shortcutIndex);
337         if (index < 0) {
338           label += " (" + shortcut + ")";
339           label = Utilities.underlineLetter(label, label.lastIndexOf(shortcut));
340 
341         } else {
342           label = Utilities.underlineLetter(label, index);
343         }
344       }
345     }
346 
347     return label;
348   }
349 
350 }