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 java.awt.*;
18  import java.util.Calendar;
19  import java.util.ResourceBundle;
20  import java.util.logging.Logger;
21  import javax.swing.*;
22  
23  import net.curre.prefcount.App;
24  import net.curre.prefcount.gui.aa.AAJPanel;
25  import net.curre.prefcount.gui.aa.AAJLabel;
26  
27  import org.apache.commons.lang.StringUtils;
28  import org.apache.commons.lang.time.FastDateFormat;
29  
30  /**
31   * Object of this class represents a set of
32   * common utilities for prefcount.
33   * <p/>
34   * Created date: Apr 7, 2007
35   *
36   * @author Yevgeny Nyden
37   */
38  public class Utilities {
39  
40    /** Private class logger. */
41    private static Logger log = Logger.getLogger(Utilities.class.toString());
42  
43    /** Enumeration tha represents a field type. */
44    public static enum FieldType {
45  
46      UNDEFINED, INTEGER
47    }
48  
49    /** Enumeration tha represents a platform/os type. */
50    public static enum PlatformType {
51  
52      MAC_OS, LINUX, WINDOWS, UNKNOWN
53    }
54  
55    /** Helper object to be used in the printTime() method. */
56    public static Calendar lastTime = Calendar.getInstance();
57  
58    /**
59     * Validates if the passed component value is valid.
60     *
61     * @param field Input field, which value to validate.
62     * @param type  Type of the value to check (i.e. Utilities.TYPE_INTEGER).
63     * @return true If the component value is valid; false otherwise.
64     */
65    public static boolean validateTextField(JTextField field, FieldType type) {
66      String str = field.getText().trim();
67      switch (type) {
68        case INTEGER:
69          return StringUtils.isNumeric(str);
70        default:
71          log.severe("ERROR: validateTextField: Unknown type: " + type);
72      }
73      return false;
74    }
75  
76    /**
77     * Returns capitalized first letter from the passed text field
78     * or null if the text field is empty.
79     *
80     * @param field Text field to read.
81     * @return Capitalized first letter from the passed text field
82     *         or null if the text field is empty.
83     */
84    public static String getFirstLetterFromField(JTextField field) {
85      String str = field.getText();
86      if (StringUtils.isBlank(str)) {
87        return null;
88      }
89      return str.trim().substring(0, 1).toUpperCase();
90    }
91  
92    /**
93     * Gets and parses text from the given text field.
94     * If the text field is null or contains an empty
95     * string or white space only, 0 if returned.
96     *
97     * @param field Text field to parse.
98     * @return Parsed integer.
99     * @throws NumberFormatException If text field contains an invalid integer.
100    */
101   public static int parseIntFromTextField(JTextField field) {
102     if (field != null) {
103       String value = field.getText().trim();
104       if (value.length() != 0) {
105         return Integer.parseInt(value);
106       }
107     }
108     return 0;
109   }
110 
111   /**
112    * Computes the size of the passed String.
113    *
114    * @param g2  Graphics object to use.
115    * @param str String to be measured.
116    * @return The size of the passed string as a <code>Dimension</code> object.
117    */
118   public static Dimension determineSizeOfString(Graphics2D g2, String str) {
119     FontMetrics metrics = g2.getFontMetrics(g2.getFont());
120     int height = metrics.getHeight();
121     int width = metrics.stringWidth(str);
122     return new Dimension(width, height);
123   }
124 
125   /**
126    * Creates a gif image for the given file name
127    * (image file is expected to be in the images/ directory
128    * relative to the net.curre.prefcount.App class).
129    *
130    * @param fileName File name without extention.
131    * @return The created ImageIcon object.
132    */
133   public static ImageIcon createImage(String fileName) {
134     return new ImageIcon(App.class.getResource("images/" + fileName + ".gif"));
135   }
136 
137   /**
138    * Underlines a letter in the given string at
139    * the given position; note, that the string is
140    * converted to html.
141    *
142    * @param str String to underline.
143    * @param ind Letter index, which to underline.
144    * @return A string with underlined letter at the given position.
145    */
146   public static String underlineLetter(String str, int ind) {
147     return "<HTML>" + str.substring(0, ind) + "<U>" + str.charAt(ind) +
148            "</U>" + str.substring(ind + 1);
149 
150   }
151 
152   /**
153    * Creates a new color that is darker than the
154    * passed color according to the passed int parameter.
155    *
156    * @param color    Model color.
157    * @param decrease Value to be subtracted from the RGB chanels of the model color.
158    * @return New darker color.
159    */
160   public static Color createDarkerColor(Color color, int decrease) {
161     return new Color(color.getRed() - decrease,
162                      color.getGreen() - decrease,
163                      color.getBlue() - decrease);
164   }
165 
166   /**
167    * Opens a new frame and displayes a message in it
168    * (given its resource key).
169    *
170    * @param messageKey Message key.
171    */
172   public static void displayMessageInFrame(String messageKey) {
173     String msg = ResourceBundle.getBundle("default").getString(messageKey);
174     // todo - implement displaying messaging GUI box
175   }
176 
177   /**
178    * This method is used for debugging purposes
179    * to print timestamps and the elapsed time since the last
180    * call to this method.
181    *
182    * @param msg Message to add to the print statement.
183    */
184   public static void printTime(String msg) {
185     Calendar currTime = Calendar.getInstance();
186     Calendar diff = Calendar.getInstance();
187     long currMls = currTime.getTimeInMillis();
188     diff.setTimeInMillis(currMls - lastTime.getTimeInMillis());
189     FastDateFormat f = FastDateFormat.getInstance("mm:ss:SSS");
190     System.out.println("TIME:::::: " + f.format(currTime.getTime()) +
191                        " (" + f.format(diff) + ") - " + msg);
192     lastTime.setTimeInMillis(currMls);
193   }
194 
195   /** Prints available looks and feels. */
196   public static void printLookAndFeels() {
197     UIManager.LookAndFeelInfo laf[] = UIManager.getInstalledLookAndFeels();
198     for (int i = 0, n = laf.length; i < n; i++) {
199       System.out.print("LAF Name: " + laf[i].getName() + "\t");
200       System.out.println("  LAF Class name: " + laf[i].getClassName());
201     }
202   }
203 
204   /** Displays available fonts in a frame. */
205   public static void printAvailableFonts() {
206     JFrame f = new JFrame("Testing Fonts");
207     f.setSize(400, 400);
208     JPanel mainPanel = new AAJPanel();
209     f.add(mainPanel);
210     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
211     String fontNames[] = ge.getAvailableFontFamilyNames();
212     int j = fontNames.length;
213     for (int i = 0; i < j; ++i) {
214       JPanel panel = new JPanel();
215       JLabel label = new AAJLabel(fontNames[i]);
216       label.setFont(new Font(fontNames[i], Font.PLAIN, 16));
217       panel.add(label);
218       mainPanel.add(panel);
219 
220       System.out.println(fontNames[i]);
221     }
222     f.pack();
223     f.setVisible(true);
224   }
225 
226   /**
227    * Determines the platform/os type we are running on.
228    *
229    * @return A PlatformType enumeration that represents the platform/os.
230    */
231   public static PlatformType getPlatformType() {
232     if (System.getProperty("mrj.version") == null) {
233       String osProp = System.getProperty("os.name").toLowerCase();
234       if (osProp.indexOf("windows") != -1) {
235         return PlatformType.WINDOWS;
236       } else if (osProp.indexOf("mac") != -1) {
237         return PlatformType.MAC_OS;
238       } else if (osProp.indexOf("linux") != -1) {
239         return PlatformType.LINUX;
240       } else {
241         return PlatformType.UNKNOWN;
242       }
243     }
244     return PlatformType.MAC_OS;
245   }
246 
247   /**
248    * Returns true if we are running on Mac OS; false otehrwise.
249    *
250    * @return True if we are on Mac OS; false otherwise.
251    */
252   public static boolean isMacOs() {
253     return getPlatformType() == PlatformType.MAC_OS;
254   }
255 
256 }