PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/ipassbook/src/com/wateray/ipassbook/ui/GuiUtils.java

http://ipassbook.googlecode.com/
Java | 495 lines | 233 code | 53 blank | 209 comment | 17 complexity | d3c70d4e69777742cd38b365c613c38f MD5 | raw file
  1. /*
  2. * aTunes 1.12.0
  3. * Copyright (C) 2006-2009 Alex Aranda, Sylvain Gaudard, Thomas Beckers and contributors
  4. *
  5. * See http://www.atunes.org/wiki/index.php?title=Contributing for information about contributors
  6. *
  7. * http://www.atunes.org
  8. * http://sourceforge.net/projects/atunes
  9. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public License
  12. * as published by the Free Software Foundation; either version 2
  13. * of the License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. */
  20. package com.wateray.ipassbook.ui;
  21. import java.awt.Color;
  22. import java.awt.ComponentOrientation;
  23. import java.awt.Container;
  24. import java.awt.GraphicsEnvironment;
  25. import java.awt.Rectangle;
  26. import java.awt.Shape;
  27. import java.awt.Window;
  28. import java.awt.event.ActionEvent;
  29. import java.awt.event.KeyEvent;
  30. import java.lang.reflect.InvocationTargetException;
  31. import java.lang.reflect.Method;
  32. import java.util.Enumeration;
  33. import java.util.HashMap;
  34. import java.util.Map;
  35. import java.util.Locale;
  36. import javax.swing.AbstractAction;
  37. import javax.swing.Action;
  38. import javax.swing.JComponent;
  39. import javax.swing.JDialog;
  40. import javax.swing.JFrame;
  41. import javax.swing.JTree;
  42. import javax.swing.KeyStroke;
  43. import javax.swing.SwingConstants;
  44. import javax.swing.UIManager;
  45. import javax.swing.plaf.FontUIResource;
  46. import org.apache.log4j.Logger;
  47. import com.wateray.ipassbook.util.log4j.Log;
  48. /**
  49. * GUI related utility methods.
  50. */
  51. public class GuiUtils {
  52. private static Logger logger = Log.getLogger();
  53. // /** The border color. */
  54. // private static Color borderColor = Color.BLACK;
  55. /** The lookAndFeelColorRegister.*/
  56. private static HashMap<String, Color> lookAndFeelColorRegister = new HashMap<String, Color>();
  57. /** The component orientation. */
  58. private static ComponentOrientation componentOrientation;
  59. /** The set window shape method. */
  60. private static Method setWindowShapeMethod;
  61. /** The set window opacity method. */
  62. private static Method setWindowOpacityMethod;
  63. /** The set window opaque method. */
  64. private static Method setWindowOpaqueMethod;
  65. /**
  66. * Bounds of the main screen device, used to calculate sizes
  67. */
  68. private static Rectangle mainDeviceBounds;
  69. public static final int MAX_COMPONENTS_WIDTH = 1280;
  70. public static final Color errorMessageColor = Color.RED;
  71. public static final Color AlertMessageColor = Color.RED;
  72. static {
  73. try {
  74. Class<?> awtUtilities = Class.forName("com.sun.awt.AWTUtilities");
  75. setWindowShapeMethod = awtUtilities.getDeclaredMethod("setWindowShape", Window.class, Shape.class);
  76. setWindowOpacityMethod = awtUtilities.getDeclaredMethod("setWindowOpacity", Window.class, float.class);
  77. setWindowOpaqueMethod = awtUtilities.getDeclaredMethod("setWindowOpaque", Window.class, boolean.class);
  78. } catch (ClassNotFoundException e) {
  79. logger.info("class com.sun.awt.AWTUtilities not found");
  80. } catch (SecurityException e) {
  81. logger.error(e.getMessage(), e);
  82. } catch (NoSuchMethodException e) {
  83. logger.error(e.getMessage(),e);
  84. }
  85. mainDeviceBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration().getBounds();
  86. }
  87. /**
  88. * Returns the width in pixels of the main device
  89. *
  90. * @return
  91. */
  92. public static int getDeviceWidth() {
  93. return mainDeviceBounds.width;
  94. }
  95. /**
  96. * Returns the height in pixels of the main device
  97. *
  98. * @return
  99. */
  100. public static int getDeviceHeight() {
  101. return mainDeviceBounds.height;
  102. }
  103. /**
  104. * Sets location of a window centered in main screen device. Window must
  105. * have size different of (0,0)
  106. *
  107. * @param window
  108. */
  109. public static void setLocation(Window window) {
  110. window.setLocation(mainDeviceBounds.width / 2 - window.getWidth() / 2, mainDeviceBounds.height / 2 - window.getHeight() / 2);
  111. }
  112. /**
  113. * Adds the close action with escape key.
  114. *
  115. * @param dialog
  116. * the dialog
  117. */
  118. public static void addCloseActionWithEscapeKey(final JDialog dialog) {
  119. // Handle escape key to close the dialog
  120. KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
  121. Action escapeAction = new AbstractAction() {
  122. private static final long serialVersionUID = 0L;
  123. @Override
  124. public void actionPerformed(ActionEvent e) {
  125. dialog.setVisible(false);
  126. }
  127. };
  128. dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
  129. dialog.getRootPane().getActionMap().put("ESCAPE", escapeAction);
  130. }
  131. /**
  132. * Adds the close action with escape key.
  133. *
  134. * @param frame
  135. * the frame
  136. */
  137. public static void addCloseActionWithEscapeKey(final JFrame frame) {
  138. // Handle escape key to close the dialog
  139. KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
  140. Action escapeAction = new AbstractAction() {
  141. private static final long serialVersionUID = 0L;
  142. @Override
  143. public void actionPerformed(ActionEvent e) {
  144. frame.setVisible(false);
  145. }
  146. };
  147. frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
  148. frame.getRootPane().getActionMap().put("ESCAPE", escapeAction);
  149. }
  150. /**
  151. * Adds the dispose action with escape key.
  152. *
  153. * @param dialog
  154. * the dialog
  155. */
  156. public static void addDisposeActionWithEscapeKey(final JDialog dialog) {
  157. // Handle escape key to close the dialog
  158. KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
  159. Action disposeAction = new AbstractAction() {
  160. private static final long serialVersionUID = 0L;
  161. @Override
  162. public void actionPerformed(ActionEvent e) {
  163. dialog.dispose();
  164. }
  165. };
  166. dialog.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
  167. dialog.getRootPane().getActionMap().put("ESCAPE", disposeAction);
  168. }
  169. /**
  170. * Adds the dispose action with escape key.
  171. *
  172. * @param frame
  173. * the frame
  174. */
  175. public static void addDisposeActionWithEscapeKey(final JFrame frame) {
  176. // Handle escape key to close the dialog
  177. KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
  178. Action disposeAction = new AbstractAction() {
  179. private static final long serialVersionUID = 0L;
  180. @Override
  181. public void actionPerformed(ActionEvent e) {
  182. frame.dispose();
  183. }
  184. };
  185. frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, "ESCAPE");
  186. frame.getRootPane().getActionMap().put("ESCAPE", disposeAction);
  187. }
  188. /**
  189. * Applies Locale specific component orientation to containers.
  190. *
  191. * @param containers
  192. * One or more containers
  193. */
  194. public static void applyComponentOrientation(Container... containers) {
  195. if (componentOrientation == null) {
  196. setComponentOrientation();
  197. }
  198. for (Container container : containers) {
  199. container.applyComponentOrientation(componentOrientation);
  200. }
  201. }
  202. /**
  203. * Collapses all nodes in a tree.
  204. *
  205. * @param tree
  206. * the tree
  207. */
  208. public static void collapseTree(JTree tree) {
  209. for (int i = tree.getRowCount() - 1; i > 0; i--) {
  210. tree.collapseRow(i);
  211. }
  212. tree.setSelectionRow(0);
  213. }
  214. /**
  215. * Expands all nodes in a tree.
  216. *
  217. * @param tree
  218. * A tree
  219. */
  220. public static void expandTree(JTree tree) {
  221. for (int i = 1; i < tree.getRowCount(); i++) {
  222. tree.expandRow(i);
  223. }
  224. tree.setSelectionRow(0);
  225. }
  226. /**
  227. * Returns background color for panels, as set by Look And Feel.
  228. *
  229. * @return the background color
  230. */
  231. public static Color getBackgroundColor() {
  232. return (Color) UIManager.get("Panel.background");
  233. }
  234. /**
  235. * Returns foreground color for labels, as set by Look And Feel
  236. *
  237. * @return the forefround color
  238. */
  239. public static Color getForegroundColor() {
  240. return (Color) UIManager.get("Label.foreground");
  241. }
  242. // /**
  243. // * Returns border color for panels, based on background color.
  244. // *
  245. // * @return the border color
  246. // */
  247. // public static Color getBorderColor() {
  248. // return borderColor;
  249. // }
  250. /** get lookAndFeelColor by color name.*/
  251. public static Color getLookAndFeelColor(String colorName){
  252. Color c = (Color)lookAndFeelColorRegister.get(colorName!=null?colorName.trim():" ");
  253. // if(c == null){
  254. // c = Color.LIGHT_GRAY;
  255. // }
  256. return c;
  257. }
  258. /** store lookAndFeelColor.*/
  259. public static void putLookAndFeelColor(String colorName, Color c){
  260. lookAndFeelColorRegister.put(colorName, c);
  261. }
  262. /**
  263. * Returns the component orientation.
  264. *
  265. * @return The component orientation
  266. */
  267. public static ComponentOrientation getComponentOrientation() {
  268. if (componentOrientation == null) {
  269. setComponentOrientation();
  270. }
  271. return componentOrientation;
  272. }
  273. /**
  274. * Returns the component orientation as a SwingConstant.
  275. *
  276. * @return The component orientation as a SwingConstant
  277. */
  278. public static int getComponentOrientationAsSwingConstant() {
  279. if (componentOrientation == null) {
  280. setComponentOrientation();
  281. }
  282. return componentOrientation.isLeftToRight() ? SwingConstants.LEFT : SwingConstants.RIGHT;
  283. }
  284. /**
  285. * Returns a proportional width according to screenWidth and desiredSize for
  286. * the current screen resolution.
  287. *
  288. * @param screenWidth
  289. * the screen width
  290. * @param desiredWidth
  291. * the desired width
  292. *
  293. * @return the component width for resolution
  294. */
  295. public static int getComponentWidthForResolution(int screenWidth, int desiredWidth) {
  296. int currentScreenWidth = mainDeviceBounds.width > MAX_COMPONENTS_WIDTH ? MAX_COMPONENTS_WIDTH : mainDeviceBounds.width;
  297. int result = desiredWidth * currentScreenWidth / screenWidth;
  298. return result;
  299. }
  300. /**
  301. * Returns a proportional height according to screenHeight and desiredHeight
  302. * for the current screen resolution.
  303. *
  304. * @param screenHeight
  305. * the screen height
  306. * @param desiredHeight
  307. * the desired height
  308. *
  309. * @return the component height for resolution
  310. */
  311. public static int getComponentHeightForResolution(int screenHeight, int desiredHeight) {
  312. int currentScreenHeight = mainDeviceBounds.height;
  313. int result = desiredHeight * currentScreenHeight / screenHeight;
  314. return result;
  315. }
  316. // /**
  317. // * Sets the border color.
  318. // *
  319. // * @param borderColor
  320. // * the borderColor to set
  321. // */
  322. // public static void setBorderColor(Color borderColor) {
  323. // GuiUtils.borderColor = borderColor;
  324. // }
  325. /**
  326. * Sets the component orientation.
  327. */
  328. private static void setComponentOrientation() {
  329. componentOrientation = ComponentOrientation.getOrientation(Locale.getDefault());
  330. // if (Kernel.getInstance() == null) {
  331. // componentOrientation = ComponentOrientation.getOrientation(Locale.getDefault());
  332. // } else {
  333. // if ("ug".equalsIgnoreCase(Kernel.getInstance().state.getLocale().getLocale().getLanguage())) {
  334. // componentOrientation = ComponentOrientation.RIGHT_TO_LEFT;
  335. // } else {
  336. // componentOrientation = ComponentOrientation.getOrientation(Kernel.getInstance().state.getLocale().getLocale());
  337. // }
  338. //
  339. // }
  340. }
  341. /**
  342. * Sets the default font for all Swing components.
  343. *
  344. * @param f
  345. * the f
  346. */
  347. public static void setUIFont(FontUIResource f) {
  348. Enumeration<Object> keys = UIManager.getDefaults().keys();
  349. while (keys.hasMoreElements()) {
  350. Object key = keys.nextElement();
  351. Object value = UIManager.get(key);
  352. if (value instanceof FontUIResource) {
  353. UIManager.put(key, f);
  354. }
  355. }
  356. }
  357. /**
  358. * Sets the window shape if possible.
  359. *
  360. * @param window
  361. * A mindow
  362. * @param mask
  363. * A mask
  364. */
  365. public static void setWindowShape(Window window, Shape mask) {
  366. if (setWindowShapeMethod != null) {
  367. try {
  368. setWindowShapeMethod.invoke(null, window, mask);
  369. } catch (SecurityException e) {
  370. logger.error(e.getMessage(), e);
  371. } catch (IllegalArgumentException e) {
  372. logger.error(e.getMessage(), e);
  373. } catch (IllegalAccessException e) {
  374. logger.error(e.getMessage(), e);
  375. } catch (InvocationTargetException e) {
  376. logger.error(e.getMessage(), e);
  377. } catch (UnsupportedOperationException e) {
  378. logger.error(e.getMessage(), e);
  379. }
  380. }
  381. }
  382. /**
  383. * Sets the window opacity if possible.
  384. *
  385. * @param window
  386. * A window
  387. * @param opacity
  388. * Opacity from 0 to 1
  389. */
  390. public static void setWindowOpacity(Window window, float opacity) {
  391. if (setWindowOpacityMethod != null) {
  392. try {
  393. setWindowOpacityMethod.invoke(null, window, opacity);
  394. } catch (SecurityException e) {
  395. logger.error(e.getMessage(), e);
  396. } catch (IllegalArgumentException e) {
  397. logger.error(e.getMessage(), e);
  398. } catch (IllegalAccessException e) {
  399. logger.error(e.getMessage(), e);
  400. } catch (InvocationTargetException e) {
  401. logger.error(e.getMessage(), e);
  402. // In some systems where window opacity is not supported
  403. // This method launches InvocationTargetException continuosly
  404. // So the first time exception is thrown, we disable
  405. // call to setWindowOpacityMethod
  406. setWindowOpacityMethod = null;
  407. } catch (UnsupportedOperationException e) {
  408. logger.error(e.getMessage(), e);
  409. }
  410. }
  411. }
  412. /**
  413. * Sets the window opaque if possible.
  414. *
  415. * @param window
  416. * A window
  417. * @param opaque
  418. * If the window should be opaque
  419. */
  420. public static void setWindowOpaque(Window window, boolean opaque) {
  421. if (setWindowOpaqueMethod != null) {
  422. try {
  423. setWindowOpaqueMethod.invoke(null, window, opaque);
  424. } catch (SecurityException e) {
  425. logger.error(e.getMessage(), e);
  426. } catch (IllegalArgumentException e) {
  427. logger.error(e.getMessage(), e);
  428. } catch (IllegalAccessException e) {
  429. logger.error(e.getMessage(), e);
  430. } catch (InvocationTargetException e) {
  431. logger.error(e.getMessage(), e);
  432. // In some systems where window opacity is not supported
  433. // This method launches InvocationTargetException continuosly
  434. // So the first time exception is thrown, we disable
  435. // call to setWindowOpaqueMethod
  436. setWindowOpaqueMethod = null;
  437. } catch (UnsupportedOperationException e) {
  438. logger.error(e.getMessage(), e);
  439. }
  440. }
  441. }
  442. }