View Javadoc

1   package com.explosion.utilities;
2   
3   /*
4    * =============================================================================
5    * 
6    * Copyright 2004 Stephen Cowx
7    * 
8    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
9    * use this file except in compliance with the License. You may obtain a copy of
10   * the License at
11   * 
12   * http://www.apache.org/licenses/LICENSE-2.0
13   * 
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17   * License for the specific language governing permissions and limitations under
18   * the License.
19   * 
20   * =============================================================================
21   */
22  
23  import java.awt.Component;
24  import java.awt.Dialog;
25  import java.awt.Dimension;
26  import java.awt.FontMetrics;
27  import java.awt.Toolkit;
28  import java.awt.Window;
29  import java.io.File;
30  import java.util.Enumeration;
31  import java.util.Properties;
32  import java.util.Vector;
33  
34  import javax.swing.JDialog;
35  import javax.swing.JFrame;
36  import javax.swing.JTable;
37  import javax.swing.table.DefaultTableModel;
38  import javax.swing.table.TableColumn;
39  import javax.swing.table.TableModel;
40  
41  /***
42   * Stuff I dont want to write more than once
43   */
44  
45  public class GeneralUtils
46  {
47  
48      public static void setStandardTableProperties(JTable table, Properties theseProperties)
49      {
50      //    table.setGridColor(new
51      // Color(Integer.parseInt(theseProperties.getProperty(Constants.COLOR_SELECTEDBACKGROUND,
52      // Constants.BLACK))));
53      //    table.setForeground(new
54      // Color(Integer.parseInt(theseProperties.getProperty(Constants.COLORS_FOREGROUND,
55      // Constants.BLACK))));
56      //    table.setBackground(new
57      // Color(Integer.parseInt(theseProperties.getProperty(Constants.COLORS_BACKGROUND,
58      // Constants.WHITE))));
59      //    table.setSelectionForeground(new
60      // Color(Integer.parseInt(theseProperties.getProperty(Constants.COLOR_SELECTEDFORGROUND,
61      // Constants.LIGHTGREY))));
62      //    table.setSelectionBackground(new
63      // Color(Integer.parseInt(theseProperties.getProperty(Constants.COLOR_SELECTEDBACKGROUND,
64      // Constants.WHITE))));
65      //    table.setShowGrid(true);
66      //    //table.setShowHorizontalLines(false);
67      //table.setShowVerticalLines(false);
68      }
69      
70      /***
71       * Works out a safe directory
72       * @return
73       */
74      public static File getSafeUserDir()
75      {
76          File currentDirectory = new File(System.getProperty("user.dir"));
77          if (!currentDirectory.exists())
78          {
79              currentDirectory = new File(System.getProperty("java.io.tmpdir"));
80          }
81          else if (currentDirectory.isFile())
82          {
83              currentDirectory = new File(currentDirectory.getParent());
84          }
85          return currentDirectory;
86      }
87  
88      /***
89       * Returns a boolean of true if the value provided is one of
90       * 1,yes,y,true,t. It is case insensitive otherwise it returns false 
91       * @param string
92       * @return
93       */
94      public static boolean getLenientBoolean(String string)
95      {
96          if (string == null) return false;
97  
98          String truth = string.trim().toLowerCase();
99          if (truth.equals("yes") || truth.equals("true") || truth.equals("t") || truth.equals("y") || truth.equals("1"))
100             return true;
101         else
102             return false;
103     }
104 
105     public static TableModel getEmptyModel(String message)
106     {
107         Vector cols = new Vector();
108         cols.addElement("");
109         Vector rows = new Vector();
110         Vector row = new Vector();
111         row.addElement(message);
112         rows.addElement(row);
113         return new DefaultTableModel(rows, cols);
114     }
115 
116     public static boolean checkJREVersion(double desiredVersion)
117     {
118         Double d = new Double(System.getProperty("java.specification.version"));
119         if (d.doubleValue() < desiredVersion)
120         {
121             return false;
122         } else
123             return true;
124     }
125 
126     /***
127      * Returns the number of lines in the string. It does this by counting the
128      * number of line feeds. It ignores carriage returns.
129      */
130     public static int lineCount(String string)
131     {
132         int count = 1;
133         for (int i = 0; i < string.length(); i++)
134         {
135             if (string.charAt(i) == 10) count++;
136         }
137         return count;
138     }
139 
140     /***
141      * This method sizes a tables columns sensibly. It requires quite a lot of
142      * info.
143      */
144     public static void sizeColumnsToFitWidths(JTable table, String[] longestColumnEntries, Vector columnNames, int maxWidth, boolean includeColumnNames) 
145     {
146         if (table == null || longestColumnEntries == null) return;
147 
148         if (includeColumnNames && columnNames == null) 
149             throw new IllegalArgumentException("Invalid use of method, includeColumnNames is true but no names have been provided.");
150 
151         FontMetrics fontMetrics = table.getFontMetrics(table.getFont());
152         Enumeration columns = table.getColumnModel().getColumns();
153         int i = 0;
154         int width = 0;
155 
156         while (columns.hasMoreElements())
157         {
158             TableColumn column = (TableColumn) columns.nextElement();
159             if (includeColumnNames && longestColumnEntries[i].length() < ((String) columnNames.elementAt(i)).length())
160                 width = fontMetrics.stringWidth((String) columnNames.elementAt(i)) + 10;// the
161                                                                                         // 10
162                                                                                         // is so
163                                                                                         // that
164                                                                                         // is
165                                                                                         // not
166                                                                                         // squashed
167                                                                                         // against
168                                                                                         // the
169                                                                                         // side
170             else
171                 width = fontMetrics.stringWidth(longestColumnEntries[i]) + 10;// the 10
172                                                                               // isso
173                                                                               // that
174                                                                               // is
175                                                                               // not
176                                                                               // squashed
177                                                                               // against
178                                                                               // the
179                                                                               // side
180 
181             if (width > maxWidth)
182             {
183                 column.setWidth(maxWidth);
184                 column.setPreferredWidth(maxWidth);
185             } else
186             {
187                 column.setWidth(width);
188                 column.setPreferredWidth(width);
189             }
190             i++;
191         }
192     }
193 
194     /***
195      * This method centres the frame in the middle of the screen
196      * @deprecated use centreWindowOnScreen instead
197      */
198     public static void centreFrameOnScreen(JFrame frame) throws Exception
199     {
200         int xpos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - frame.getSize().getWidth()) / 2;
201         int ypos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() - frame.getSize().getHeight()) / 2;
202         frame.setLocation(xpos, ypos);
203     }
204 
205     /***
206      * This method centres the dialog in the middle of the screen
207      * @deprecated use centreWindowOnScreen instead
208      */
209     public static void centreDialogOnScreen(Dialog dialog) 
210     {
211         int xpos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - dialog.getSize().getWidth()) / 2;
212         int ypos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() - dialog.getSize().getHeight()) / 2;
213         dialog.setLocation(xpos, ypos);
214     }
215     
216     /***
217      * This method centres the window in the middle of the screen
218      */
219     public static void centreWindowOnScreen(Window window) 
220     {
221         int xpos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - window.getSize().getWidth()) / 2;
222         int ypos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() - window.getSize().getHeight()) / 2;
223         window.setLocation(xpos, ypos);
224     }
225     
226     /***
227      * This method centres the window in the middle of it's parent if there is a parent
228      * It also does some cleverness by not letting it be positioned off the screen.
229      * If there is no parent it in the middle of the screen
230      */
231     public static void centreWindowInParent(Window window) 
232     {
233     	centreWindowInParent(window, window.getParent());
234     }
235     
236     /***
237      * This method centres the window in the middle of it's parent if there is a parent
238      * It also does some cleverness by not letting it be positioned off the screen.
239      * If there is no parent it in the middle of the screen
240      */
241     public static void centreWindowInParent(Window window, Component parent) 
242     {
243     	boolean isRealParent = parent instanceof JFrame || parent instanceof JDialog;
244     	if (parent != null && isRealParent)
245         {
246         	int heightOfParent = parent.getHeight();
247             int yposOfParent = parent.getY();
248             int yCentreOfParent = yposOfParent + (heightOfParent/2);
249         	
250 	        int widthOfParent = parent.getWidth();
251             int xposOfParent = parent.getX();
252             int xCentreOfParent = xposOfParent + (widthOfParent/2);
253 	        
254 	        int xpos = (int) xCentreOfParent - (window.getWidth() / 2);
255 	        int ypos = (int) yCentreOfParent - (window.getHeight() / 2);
256 	        
257 	        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
258 	        
259 	        /* Check X bounds */
260 	        xpos = xpos < 0 ? 0 : xpos;
261 	        xpos = xpos > (int) screenSize.getWidth() ? (int) screenSize.getWidth()-window.getWidth() : xpos;
262 	        
263 	        /* Check Y bounds */
264 	        ypos = ypos < 0 ? 0 : ypos;
265 	        ypos = ypos > (int)screenSize.getHeight() ? (int)screenSize.getHeight()-window.getHeight() : ypos;
266 	        
267 	        
268 	        window.setLocation(xpos, ypos);
269         }
270         else
271         {
272     	  int xpos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getWidth() - window.getSize().getWidth()) / 2;
273           int ypos = (int) (Toolkit.getDefaultToolkit().getScreenSize().getHeight() - window.getSize().getHeight()) / 2;
274           window.setLocation(xpos, ypos);
275         }
276     }
277 
278     /***
279      * This method returns a standard error path. Of the format
280      * "[user.home]/.[prefix]/[prefix].err" If the directory does not exist, it
281      * will create it.
282      */
283     public static String getStandardErrorPath(String prefix)
284     {
285         File errorDirectory = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix);
286         if (!errorDirectory.exists()) errorDirectory.mkdirs();
287 
288         //    log.debug(System.getProperty("user.home") +
289         // System.getProperty("file.separator") + "." + prefix +
290         // System.getProperty("file.separator") + prefix + ".err");
291         return System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix + System.getProperty("file.separator") + prefix + ".err";
292     }
293 
294     /***
295      * This method returns a std out path. Of the format
296      * "[user.home]/.[prefix]/[prefix].out" If the directory does not exist, it
297      * will create it.
298      */
299     public static String getStandardOutPath(String prefix)
300     {
301         File outDirectory = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix);
302         if (!outDirectory.exists()) outDirectory.mkdirs();
303 
304         //    log.debug(System.getProperty("user.home") +
305         // System.getProperty("file.separator") + "." + prefix +
306         // System.getProperty("file.separator") + prefix + ".out");
307         return System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix + System.getProperty("file.separator") + prefix + ".out";
308     }
309 
310     /***
311      * This method returns a the path of a file out path. Of the format
312      * "[user.home]/.[prefix]/[filename]" If the directory does not exist, it
313      * will create it.
314      */
315     public static String getStandardPath(String prefix, String filename)
316     {
317         File errorDirectory = new File(System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix);
318         if (!errorDirectory.exists()) errorDirectory.mkdir();
319 
320         return System.getProperty("user.home") + System.getProperty("file.separator") + "." + prefix + System.getProperty("file.separator") + filename;
321     }
322 
323 }