1. /*
  2. * @(#)SwingUtilities.java 1.95 00/07/26
  3. *
  4. * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. package javax.swing;
  11. import java.applet.*;
  12. import java.awt.*;
  13. import java.awt.event.*;
  14. import java.util.Vector;
  15. import java.util.Hashtable;
  16. import java.lang.reflect.*;
  17. import javax.accessibility.*;
  18. import javax.swing.plaf.UIResource;
  19. import javax.swing.text.View;
  20. /**
  21. * A collection of utility methods for Swing.
  22. *
  23. * @version 1.95 07/26/00
  24. * @author unknown
  25. */
  26. public class SwingUtilities implements SwingConstants
  27. {
  28. // These states are system-wide, rather than AppContext wide.
  29. private static boolean canAccessEventQueue = false;
  30. private static boolean eventQueueTested = false;
  31. /**
  32. * Return true if <code>a</code> contains <code>b</code>
  33. */
  34. public static final boolean isRectangleContainingRectangle(Rectangle a,Rectangle b) {
  35. if (b.x >= a.x && (b.x + b.width) <= (a.x + a.width) &&
  36. b.y >= a.y && (b.y + b.height) <= (a.y + a.height)) {
  37. return true;
  38. }
  39. return false;
  40. }
  41. /**
  42. * Return the rectangle (0,0,bounds.width,bounds.height) for the component <code>aComponent</code>
  43. */
  44. public static Rectangle getLocalBounds(Component aComponent) {
  45. Rectangle b = new Rectangle(aComponent.getBounds());
  46. b.x = b.y = 0;
  47. return b;
  48. }
  49. /**
  50. * @return the first Window ancestor of c, or null if component is not contained inside a window
  51. */
  52. public static Window getWindowAncestor(Component c) {
  53. for(Container p = c.getParent(); p != null; p = p.getParent()) {
  54. if (p instanceof Window) {
  55. return (Window)p;
  56. }
  57. }
  58. return null;
  59. }
  60. /**
  61. * Convert a <code>aPoint</code> in <code>source</code> coordinate system to
  62. * <code>destination</code> coordinate system.
  63. * If <code>source></code>is null,<code>aPoint</code> is assumed to be in <code>destination</code>'s
  64. * root component coordinate system.
  65. * If <code>destination</code>is null, <code>aPoint</code> will be converted to <code>source</code>'s
  66. * root component coordinate system.
  67. * If both <code>source</code> and <code>destination</code> are null, return <code>aPoint</code>
  68. * without any conversion.
  69. */
  70. public static Point convertPoint(Component source,Point aPoint,Component destination) {
  71. Point p;
  72. if(source == null && destination == null)
  73. return aPoint;
  74. if(source == null) {
  75. source = getWindowAncestor(destination);
  76. if(source == null)
  77. throw new Error("Source component not connected to component tree hierarchy");
  78. }
  79. p = new Point(aPoint);
  80. convertPointToScreen(p,source);
  81. if(destination == null) {
  82. destination = getWindowAncestor(source);
  83. if(destination == null)
  84. throw new Error("Destination component not connected to component tree hierarchy");
  85. }
  86. convertPointFromScreen(p,destination);
  87. return p;
  88. }
  89. /**
  90. * Convert the point <code>(x,y)</code> in <code>source</code> coordinate system to
  91. * <code>destination</code> coordinate system.
  92. * If <code>source></code>is null,<code>(x,y)</code> is assumed to be in <code>destination</code>'s
  93. * root component coordinate system.
  94. * If <code>destination</code>is null, <code>(x,y)</code> will be converted to <code>source</code>'s
  95. * root component coordinate system.
  96. * If both <code>source</code> and <code>destination</code> are null, return <code>(x,y)</code>
  97. * without any conversion.
  98. */
  99. public static Point convertPoint(Component source,int x, int y,Component destination) {
  100. Point point = new Point(x,y);
  101. return convertPoint(source,point,destination);
  102. }
  103. /**
  104. * Convert the rectangle <code>aRectangle</code> in <code>source</code> coordinate system to
  105. * <code>destination</code> coordinate system.
  106. * If <code>source></code>is null,<code>aRectangle</code> is assumed to be in <code>destination</code>'s
  107. * root component coordinate system.
  108. * If <code>destination</code>is null, <code>aRectangle</code> will be converted to <code>source</code>'s
  109. * root component coordinate system.
  110. * If both <code>source</code> and <code>destination</code> are null, return <code>aRectangle</code>
  111. * without any conversion.
  112. */
  113. public static Rectangle convertRectangle(Component source,Rectangle aRectangle,Component destination) {
  114. Point point = new Point(aRectangle.x,aRectangle.y);
  115. point = convertPoint(source,point,destination);
  116. return new Rectangle(point.x,point.y,aRectangle.width,aRectangle.height);
  117. }
  118. /**
  119. * Convenience method for searching above <code>comp</code> in the
  120. * component hierarchy and returns the first object of class <code>c</code> it
  121. * finds. Can return null, if a class <code>c</code> cannot be found.
  122. */
  123. public static Container getAncestorOfClass(Class c, Component comp) {
  124. if(comp == null || c == null)
  125. return null;
  126. Container parent = comp.getParent();
  127. while(parent != null && !(c.isInstance(parent)))
  128. parent = parent.getParent();
  129. return parent;
  130. }
  131. /**
  132. * Convenience method for searching above <code>comp</code> in the
  133. * component hierarchy and returns the first object of <code>name</code> it
  134. * finds. Can return null, if <code>name</code> cannot be found.
  135. */
  136. public static Container getAncestorNamed(String name, Component comp) {
  137. if(comp == null || name == null)
  138. return null;
  139. Container parent = comp.getParent();
  140. while(parent != null && !(name.equals(parent.getName())))
  141. parent = parent.getParent();
  142. return parent;
  143. }
  144. /**
  145. * Returns the deepest visible descendent Component of <code>parent</code>
  146. * that contains the location <code>x</code>, <code>y</code>.
  147. * If <code>parent</code> does not contain the specified location,
  148. * then <code>null</code> is returned. If <code>parent</code> is not a
  149. * container, or none of <code>parent</code>'s visible descendents
  150. * contain the specified location, <code>parent</code> is returned.
  151. *
  152. * @param parent the root component to begin the search
  153. * @param x the x target location
  154. * @param y the y target location
  155. */
  156. public static Component getDeepestComponentAt(Component parent, int x, int y) {
  157. if (!parent.contains(x, y)) {
  158. return null;
  159. }
  160. if (parent instanceof Container) {
  161. Component components[] = ((Container)parent).getComponents();
  162. for (int i = 0 ; i < components.length ; i++) {
  163. Component comp = components[i];
  164. if (comp != null && comp.isVisible()) {
  165. Point loc = comp.getLocation();
  166. if (comp instanceof Container) {
  167. comp = getDeepestComponentAt(comp, x - loc.x, y - loc.y);
  168. } else {
  169. comp = comp.getComponentAt(x - loc.x, y - loc.y);
  170. }
  171. if (comp != null && comp.isVisible()) {
  172. return comp;
  173. }
  174. }
  175. }
  176. }
  177. return parent;
  178. }
  179. /**
  180. * Returns a MouseEvent similar to <code>sourceEvent</code> except that its x
  181. * and y members have been converted to <code>destination</code>'s coordinate
  182. * system. If <code>source</code> is null, <code>sourceEvent</code> x and y members
  183. * are assumed to be into <code>destination</code>'s root component coordinate system.
  184. * If <code>destination</code> is <code>null</code>, the
  185. * returned MouseEvent will be in <code>source</code>'s coordinate system.
  186. * <code>sourceEvent</code> will not be changed. A new event is returned.
  187. * the <code>source</code> field of the returned event will be set
  188. * to <code>destination</code> if destination is non null
  189. * use the translateMouseEvent() method to translate a mouse event from
  190. * one component to another without changing the source.
  191. */
  192. public static MouseEvent convertMouseEvent(Component source,
  193. MouseEvent sourceEvent,
  194. Component destination) {
  195. Point p = convertPoint(source,new Point(sourceEvent.getX(),
  196. sourceEvent.getY()),
  197. destination);
  198. Component newSource;
  199. if(destination != null)
  200. newSource = destination;
  201. else
  202. newSource = source;
  203. return new MouseEvent(newSource,
  204. sourceEvent.getID(),
  205. sourceEvent.getWhen(),
  206. sourceEvent.getModifiers(),
  207. p.x,p.y,
  208. sourceEvent.getClickCount(),
  209. sourceEvent.isPopupTrigger());
  210. }
  211. /**
  212. * Convert a point from a component's coordinate system to
  213. * screen coordinates.
  214. *
  215. * @param p a Point object (converted to the new coordinate system)
  216. * @param c a Component object
  217. */
  218. public static void convertPointToScreen(Point p,Component c) {
  219. Rectangle b;
  220. int x,y;
  221. do {
  222. if(c instanceof JComponent) {
  223. x = ((JComponent)c).getX();
  224. y = ((JComponent)c).getY();
  225. } else if(c instanceof java.applet.Applet) {
  226. Point pp = c.getLocationOnScreen();
  227. x = pp.x;
  228. y = pp.y;
  229. } else {
  230. b = c.getBounds();
  231. x = b.x;
  232. y = b.y;
  233. }
  234. p.x += x;
  235. p.y += y;
  236. if(c instanceof java.awt.Window || c instanceof java.applet.Applet)
  237. break;
  238. c = c.getParent();
  239. } while(c != null);
  240. }
  241. /**
  242. * Convert a point from a screen coordinates to a component's
  243. * coordinate system
  244. *
  245. * @param p a Point object (converted to the new coordinate system)
  246. * @param c a Component object
  247. */
  248. public static void convertPointFromScreen(Point p,Component c) {
  249. Rectangle b;
  250. int x,y;
  251. do {
  252. if(c instanceof JComponent) {
  253. x = ((JComponent)c).getX();
  254. y = ((JComponent)c).getY();
  255. } else if(c instanceof java.applet.Applet) {
  256. Point pp = c.getLocationOnScreen();
  257. x = pp.x;
  258. y = pp.y;
  259. } else {
  260. b = c.getBounds();
  261. x = b.x;
  262. y = b.y;
  263. }
  264. p.x -= x;
  265. p.y -= y;
  266. if(c instanceof java.awt.Window || c instanceof java.applet.Applet)
  267. break;
  268. c = c.getParent();
  269. } while(c != null);
  270. }
  271. /** Return <code>aComponent</code>'s window **/
  272. public static Window windowForComponent(Component aComponent) {
  273. for (Container p = aComponent.getParent(); p != null; p = p.getParent()) {
  274. if (p instanceof Window) {
  275. return (Window)p;
  276. }
  277. }
  278. return null;
  279. }
  280. /**
  281. * Return <code>true</code> if a component <code>a</code> descends from a component <code>b</code>
  282. */
  283. public static boolean isDescendingFrom(Component a,Component b) {
  284. if(a == b)
  285. return true;
  286. for(Container p = a.getParent();p!=null;p=p.getParent())
  287. if(p == b)
  288. return true;
  289. return false;
  290. }
  291. /**
  292. * Convenience to calculate the intersection of two rectangles
  293. * without allocating a new rectangle.
  294. * If the two rectangles don't intersect,
  295. * then the returned rectangle begins at (0,0)
  296. * and has zero width and height.
  297. *
  298. * @param x the X coordinate of the first rectangle's top-left point
  299. * @param y the Y coordinate of the first rectangle's top-left point
  300. * @param width the width of the first rectangle
  301. * @param height the height of the first rectangle
  302. * @param dest the second rectangle
  303. *
  304. * @return <code>dest</code>, modified to specify the intersection
  305. */
  306. public static Rectangle computeIntersection(int x,int y,int width,int height,Rectangle dest) {
  307. int x1 = (x > dest.x) ? x : dest.x;
  308. int x2 = ((x+width) < (dest.x + dest.width)) ? (x+width) : (dest.x + dest.width);
  309. int y1 = (y > dest.y) ? y : dest.y;
  310. int y2 = ((y + height) < (dest.y + dest.height) ? (y+height) : (dest.y + dest.height));
  311. dest.x = x1;
  312. dest.y = y1;
  313. dest.width = x2 - x1;
  314. dest.height = y2 - y1;
  315. // If rectangles don't intersect, return zero'd intersection.
  316. if (dest.width < 0 || dest.height < 0) {
  317. dest.x = dest.y = dest.width = dest.height = 0;
  318. }
  319. return dest;
  320. }
  321. /**
  322. * Convenience to calculate the union of two rectangles without allocating a new rectangle
  323. * Return dest
  324. */
  325. public static Rectangle computeUnion(int x,int y,int width,int height,Rectangle dest) {
  326. int x1 = (x < dest.x) ? x : dest.x;
  327. int x2 = ((x+width) > (dest.x + dest.width)) ? (x+width) : (dest.x + dest.width);
  328. int y1 = (y < dest.y) ? y : dest.y;
  329. int y2 = ((y+height) > (dest.y + dest.height)) ? (y+height) : (dest.y + dest.height);
  330. dest.x = x1;
  331. dest.y = y1;
  332. dest.width = (x2 - x1);
  333. dest.height= (y2 - y1);
  334. return dest;
  335. }
  336. /**
  337. * Convenience returning an array of rect representing the regions within
  338. * <code>rectA</code> that do not overlap with <code>rectB</code>. If the
  339. * two Rects do not overlap, returns an empty array
  340. */
  341. public static Rectangle[] computeDifference(Rectangle rectA,Rectangle rectB) {
  342. if (rectB == null || !rectA.intersects(rectB) || isRectangleContainingRectangle(rectB,rectA)) {
  343. return new Rectangle[0];
  344. }
  345. Rectangle t = new Rectangle();
  346. Rectangle a=null,b=null,c=null,d=null;
  347. Rectangle result[];
  348. int rectCount = 0;
  349. /* rectA contains rectB */
  350. if (isRectangleContainingRectangle(rectA,rectB)) {
  351. t.x = rectA.x; t.y = rectA.y; t.width = rectB.x - rectA.x; t.height = rectA.height;
  352. if(t.width > 0 && t.height > 0) {
  353. a = new Rectangle(t);
  354. rectCount++;
  355. }
  356. t.x = rectB.x; t.y = rectA.y; t.width = rectB.width; t.height = rectB.y - rectA.y;
  357. if(t.width > 0 && t.height > 0) {
  358. b = new Rectangle(t);
  359. rectCount++;
  360. }
  361. t.x = rectB.x; t.y = rectB.y + rectB.height; t.width = rectB.width;
  362. t.height = rectA.y + rectA.height - (rectB.y + rectB.height);
  363. if(t.width > 0 && t.height > 0) {
  364. c = new Rectangle(t);
  365. rectCount++;
  366. }
  367. t.x = rectB.x + rectB.width; t.y = rectA.y; t.width = rectA.x + rectA.width - (rectB.x + rectB.width);
  368. t.height = rectA.height;
  369. if(t.width > 0 && t.height > 0) {
  370. d = new Rectangle(t);
  371. rectCount++;
  372. }
  373. } else {
  374. /* 1 */
  375. if (rectB.x <= rectA.x && rectB.y <= rectA.y) {
  376. if ((rectB.x + rectB.width) > (rectA.x + rectA.width)) {
  377. t.x = rectA.x; t.y = rectB.y + rectB.height;
  378. t.width = rectA.width; t.height = rectA.y + rectA.height - (rectB.y + rectB.height);
  379. if(t.width > 0 && t.height > 0) {
  380. a = t;
  381. rectCount++;
  382. }
  383. } else if ((rectB.y + rectB.height) > (rectA.y + rectA.height)) {
  384. t.setBounds((rectB.x + rectB.width), rectA.y,
  385. (rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
  386. if(t.width > 0 && t.height > 0) {
  387. a = t;
  388. rectCount++;
  389. }
  390. } else {
  391. t.setBounds((rectB.x + rectB.width), rectA.y,
  392. (rectA.x + rectA.width) - (rectB.x + rectB.width),
  393. (rectB.y + rectB.height) - rectA.y);
  394. if(t.width > 0 && t.height > 0) {
  395. a = new Rectangle(t);
  396. rectCount++;
  397. }
  398. t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
  399. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  400. if(t.width > 0 && t.height > 0) {
  401. b = new Rectangle(t);
  402. rectCount++;
  403. }
  404. }
  405. } else if (rectB.x <= rectA.x && (rectB.y + rectB.height) >= (rectA.y + rectA.height)) {
  406. if ((rectB.x + rectB.width) > (rectA.x + rectA.width)) {
  407. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  408. if(t.width > 0 && t.height > 0) {
  409. a = t;
  410. rectCount++;
  411. }
  412. } else {
  413. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  414. if(t.width > 0 && t.height > 0) {
  415. a = new Rectangle(t);
  416. rectCount++;
  417. }
  418. t.setBounds((rectB.x + rectB.width), rectB.y,
  419. (rectA.x + rectA.width) - (rectB.x + rectB.width),
  420. (rectA.y + rectA.height) - rectB.y);
  421. if(t.width > 0 && t.height > 0) {
  422. b = new Rectangle(t);
  423. rectCount++;
  424. }
  425. }
  426. } else if (rectB.x <= rectA.x) {
  427. if ((rectB.x + rectB.width) >= (rectA.x + rectA.width)) {
  428. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  429. if(t.width>0 && t.height > 0) {
  430. a = new Rectangle(t);
  431. rectCount++;
  432. }
  433. t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
  434. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  435. if(t.width > 0 && t.height > 0) {
  436. b = new Rectangle(t);
  437. rectCount++;
  438. }
  439. } else {
  440. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  441. if(t.width > 0 && t.height > 0) {
  442. a = new Rectangle(t);
  443. rectCount++;
  444. }
  445. t.setBounds((rectB.x + rectB.width), rectB.y,
  446. (rectA.x + rectA.width) - (rectB.x + rectB.width),
  447. rectB.height);
  448. if(t.width > 0 && t.height > 0) {
  449. b = new Rectangle(t);
  450. rectCount++;
  451. }
  452. t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
  453. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  454. if(t.width > 0 && t.height > 0) {
  455. c = new Rectangle(t);
  456. rectCount++;
  457. }
  458. }
  459. } else if (rectB.x <= (rectA.x + rectA.width) && (rectB.x + rectB.width) > (rectA.x + rectA.width)) {
  460. if (rectB.y <= rectA.y && (rectB.y + rectB.height) > (rectA.y + rectA.height)) {
  461. t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
  462. if(t.width > 0 && t.height > 0) {
  463. a = t;
  464. rectCount++;
  465. }
  466. } else if (rectB.y <= rectA.y) {
  467. t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x,
  468. (rectB.y + rectB.height) - rectA.y);
  469. if(t.width > 0 && t.height > 0) {
  470. a = new Rectangle(t);
  471. rectCount++;
  472. }
  473. t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
  474. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  475. if(t.width > 0 && t.height > 0) {
  476. b = new Rectangle(t);
  477. rectCount++;
  478. }
  479. } else if ((rectB.y + rectB.height) > (rectA.y + rectA.height)) {
  480. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  481. if(t.width > 0 && t.height > 0) {
  482. a = new Rectangle(t);
  483. rectCount++;
  484. }
  485. t.setBounds(rectA.x, rectB.y, rectB.x - rectA.x,
  486. (rectA.y + rectA.height) - rectB.y);
  487. if(t.width > 0 && t.height > 0) {
  488. b = new Rectangle(t);
  489. rectCount++;
  490. }
  491. } else {
  492. t.setBounds(rectA.x, rectA.y, rectA.width, rectB.y - rectA.y);
  493. if(t.width > 0 && t.height > 0) {
  494. a = new Rectangle(t);
  495. rectCount++;
  496. }
  497. t.setBounds(rectA.x, rectB.y, rectB.x - rectA.x,
  498. rectB.height);
  499. if(t.width > 0 && t.height > 0) {
  500. b = new Rectangle(t);
  501. rectCount++;
  502. }
  503. t.setBounds(rectA.x, (rectB.y + rectB.height), rectA.width,
  504. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  505. if(t.width > 0 && t.height > 0) {
  506. c = new Rectangle(t);
  507. rectCount++;
  508. }
  509. }
  510. } else if (rectB.x >= rectA.x && (rectB.x + rectB.width) <= (rectA.x + rectA.width)) {
  511. if (rectB.y <= rectA.y && (rectB.y + rectB.height) > (rectA.y + rectA.height)) {
  512. t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
  513. if(t.width > 0 && t.height > 0) {
  514. a = new Rectangle(t);
  515. rectCount++;
  516. }
  517. t.setBounds((rectB.x + rectB.width), rectA.y,
  518. (rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
  519. if(t.width > 0 && t.height > 0) {
  520. b = new Rectangle(t);
  521. rectCount++;
  522. }
  523. } else if (rectB.y <= rectA.y) {
  524. t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
  525. if(t.width > 0 && t.height > 0) {
  526. a = new Rectangle(t);
  527. rectCount++;
  528. }
  529. t.setBounds(rectB.x, (rectB.y + rectB.height),
  530. rectB.width,
  531. (rectA.y + rectA.height) - (rectB.y + rectB.height));
  532. if(t.width > 0 && t.height > 0) {
  533. b = new Rectangle(t);
  534. rectCount++;
  535. }
  536. t.setBounds((rectB.x + rectB.width), rectA.y,
  537. (rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
  538. if(t.width > 0 && t.height > 0) {
  539. c = new Rectangle(t);
  540. rectCount++;
  541. }
  542. } else {
  543. t.setBounds(rectA.x, rectA.y, rectB.x - rectA.x, rectA.height);
  544. if(t.width > 0 && t.height > 0) {
  545. a = new Rectangle(t);
  546. rectCount++;
  547. }
  548. t.setBounds(rectB.x, rectA.y, rectB.width,
  549. rectB.y - rectA.y);
  550. if(t.width > 0 && t.height > 0) {
  551. b = new Rectangle(t);
  552. rectCount++;
  553. }
  554. t.setBounds((rectB.x + rectB.width), rectA.y,
  555. (rectA.x + rectA.width) - (rectB.x + rectB.width), rectA.height);
  556. if(t.width > 0 && t.height > 0) {
  557. c = new Rectangle(t);
  558. rectCount++;
  559. }
  560. }
  561. }
  562. }
  563. result = new Rectangle[rectCount];
  564. rectCount = 0;
  565. if(a != null)
  566. result[rectCount++] = a;
  567. if(b != null)
  568. result[rectCount++] = b;
  569. if(c != null)
  570. result[rectCount++] = c;
  571. if(d != null)
  572. result[rectCount++] = d;
  573. return result;
  574. }
  575. /**
  576. * Returns true if the mouse event specifies the left mouse button.
  577. *
  578. * @param anEvent a MouseEvent object
  579. * @return true if the left mouse button was active
  580. */
  581. public static boolean isLeftMouseButton(MouseEvent anEvent) {
  582. return ((anEvent.getModifiers() & InputEvent.BUTTON1_MASK) != 0);
  583. }
  584. /**
  585. * Returns true if the mouse event specifies the middle mouse button.
  586. *
  587. * @param anEvent a MouseEvent object
  588. * @return true if the middle mouse button was active
  589. */
  590. public static boolean isMiddleMouseButton(MouseEvent anEvent) {
  591. return ((anEvent.getModifiers() & InputEvent.BUTTON2_MASK) == InputEvent.BUTTON2_MASK);
  592. }
  593. /**
  594. * Returns true if the mouse event specifies the right mouse button.
  595. *
  596. * @param anEvent a MouseEvent object
  597. * @return true if the right mouse button was active
  598. */
  599. public static boolean isRightMouseButton(MouseEvent anEvent) {
  600. return ((anEvent.getModifiers() & InputEvent.BUTTON3_MASK) == InputEvent.BUTTON3_MASK);
  601. }
  602. /**
  603. * Compute the width of the string using a font with the specified
  604. * "metrics" (sizes).
  605. *
  606. * @param fm a FontMetrics object to compute with
  607. * @param str the String to compute
  608. * @return an int containing the string width
  609. */
  610. public static int computeStringWidth(FontMetrics fm,String str) {
  611. // You can't assume that a string's width is the sum of its
  612. // characters' widths in Java2D -- it may be smaller due to
  613. // kerning, etc.
  614. return fm.stringWidth(str);
  615. }
  616. /**
  617. * Compute and return the location of the icons origin, the
  618. * location of origin of the text baseline, and a possibly clipped
  619. * version of the compound labels string. Locations are computed
  620. * relative to the viewR rectangle.
  621. * The JComponents orientation (LEADING/TRAILING) will also be taken
  622. * into account and translated into LEFT/RIGHT values accordingly.
  623. */
  624. public static String layoutCompoundLabel(JComponent c,
  625. FontMetrics fm,
  626. String text,
  627. Icon icon,
  628. int verticalAlignment,
  629. int horizontalAlignment,
  630. int verticalTextPosition,
  631. int horizontalTextPosition,
  632. Rectangle viewR,
  633. Rectangle iconR,
  634. Rectangle textR,
  635. int textIconGap)
  636. {
  637. boolean orientationIsLeftToRight = true;
  638. int hAlign = horizontalAlignment;
  639. int hTextPos = horizontalTextPosition;
  640. if (c != null) {
  641. if (!(c.getComponentOrientation().isLeftToRight())) {
  642. orientationIsLeftToRight = false;
  643. }
  644. }
  645. // Translate LEADING/TRAILING values in horizontalAlignment
  646. // to LEFT/RIGHT values depending on the components orientation
  647. switch (horizontalAlignment) {
  648. case LEADING:
  649. hAlign = (orientationIsLeftToRight) ? LEFT : RIGHT;
  650. break;
  651. case TRAILING:
  652. hAlign = (orientationIsLeftToRight) ? RIGHT : LEFT;
  653. break;
  654. }
  655. // Translate LEADING/TRAILING values in horizontalTextPosition
  656. // to LEFT/RIGHT values depending on the components orientation
  657. switch (horizontalTextPosition) {
  658. case LEADING:
  659. hTextPos = (orientationIsLeftToRight) ? LEFT : RIGHT;
  660. break;
  661. case TRAILING:
  662. hTextPos = (orientationIsLeftToRight) ? RIGHT : LEFT;
  663. break;
  664. }
  665. return layoutCompoundLabelImpl(c,
  666. fm,
  667. text,
  668. icon,
  669. verticalAlignment,
  670. hAlign,
  671. verticalTextPosition,
  672. hTextPos,
  673. viewR,
  674. iconR,
  675. textR,
  676. textIconGap);
  677. }
  678. /**
  679. * Compute and return the location of the icons origin, the
  680. * location of origin of the text baseline, and a possibly clipped
  681. * version of the compound labels string. Locations are computed
  682. * relative to the viewR rectangle.
  683. * This layoutCompoundLabel() does not know how to handle LEADING/TRAILING
  684. * values in horizontalTextPosition (they will default to RIGHT) and in
  685. * horizontalAlignment (they will default to CENTER).
  686. * Use the other version of layoutCompoundLabel() instead.
  687. */
  688. public static String layoutCompoundLabel(
  689. FontMetrics fm,
  690. String text,
  691. Icon icon,
  692. int verticalAlignment,
  693. int horizontalAlignment,
  694. int verticalTextPosition,
  695. int horizontalTextPosition,
  696. Rectangle viewR,
  697. Rectangle iconR,
  698. Rectangle textR,
  699. int textIconGap)
  700. {
  701. return layoutCompoundLabelImpl(null, fm, text, icon,
  702. verticalAlignment,
  703. horizontalAlignment,
  704. verticalTextPosition,
  705. horizontalTextPosition,
  706. viewR, iconR, textR, textIconGap);
  707. }
  708. /**
  709. * Compute and return the location of the icons origin, the
  710. * location of origin of the text baseline, and a possibly clipped
  711. * version of the compound labels string. Locations are computed
  712. * relative to the viewR rectangle.
  713. * This layoutCompoundLabel() does not know how to handle LEADING/TRAILING
  714. * values in horizontalTextPosition (they will default to RIGHT) and in
  715. * horizontalAlignment (they will default to CENTER).
  716. * Use the other version of layoutCompoundLabel() instead.
  717. */
  718. private static String layoutCompoundLabelImpl(
  719. JComponent c,
  720. FontMetrics fm,
  721. String text,
  722. Icon icon,
  723. int verticalAlignment,
  724. int horizontalAlignment,
  725. int verticalTextPosition,
  726. int horizontalTextPosition,
  727. Rectangle viewR,
  728. Rectangle iconR,
  729. Rectangle textR,
  730. int textIconGap)
  731. {
  732. /* Initialize the icon bounds rectangle iconR.
  733. */
  734. if (icon != null) {
  735. iconR.width = icon.getIconWidth();
  736. iconR.height = icon.getIconHeight();
  737. }
  738. else {
  739. iconR.width = iconR.height = 0;
  740. }
  741. /* Initialize the text bounds rectangle textR. If a null
  742. * or and empty String was specified we substitute "" here
  743. * and use 0,0,0,0 for textR.
  744. */
  745. boolean textIsEmpty = (text == null) || text.equals("");
  746. View v = null;
  747. if (textIsEmpty) {
  748. textR.width = textR.height = 0;
  749. text = "";
  750. }
  751. else {
  752. v = (c != null) ? (View) c.getClientProperty("html") : null;
  753. if (v != null) {
  754. textR.width = (int) v.getPreferredSpan(View.X_AXIS);
  755. textR.height = (int) v.getPreferredSpan(View.Y_AXIS);
  756. } else {
  757. textR.width = computeStringWidth(fm,text);
  758. textR.height = fm.getHeight();
  759. }
  760. }
  761. /* Unless both text and icon are non-null, we effectively ignore
  762. * the value of textIconGap. The code that follows uses the
  763. * value of gap instead of textIconGap.
  764. */
  765. int gap = (textIsEmpty || (icon == null)) ? 0 : textIconGap;
  766. if (!textIsEmpty) {
  767. /* If the label text string is too wide to fit within the available
  768. * space "..." and as many characters as will fit will be
  769. * displayed instead.
  770. */
  771. int availTextWidth;
  772. if (horizontalTextPosition == CENTER) {
  773. availTextWidth = viewR.width;
  774. }
  775. else {
  776. availTextWidth = viewR.width - (iconR.width + gap);
  777. }
  778. if (textR.width > availTextWidth) {
  779. if (v != null) {
  780. textR.width = availTextWidth;
  781. } else {
  782. String clipString = "...";
  783. int totalWidth = computeStringWidth(fm,clipString);
  784. int nChars;
  785. for(nChars = 0; nChars < text.length(); nChars++) {
  786. totalWidth += fm.charWidth(text.charAt(nChars));
  787. if (totalWidth > availTextWidth) {
  788. break;
  789. }
  790. }
  791. text = text.substring(0, nChars) + clipString;
  792. textR.width = computeStringWidth(fm,text);
  793. }
  794. }
  795. }
  796. /* Compute textR.x,y given the verticalTextPosition and
  797. * horizontalTextPosition properties
  798. */
  799. if (verticalTextPosition == TOP) {
  800. if (horizontalTextPosition != CENTER) {
  801. textR.y = 0;
  802. }
  803. else {
  804. textR.y = -(textR.height + gap);
  805. }
  806. }
  807. else if (verticalTextPosition == CENTER) {
  808. textR.y = (iconR.height / 2) - (textR.height / 2);
  809. }
  810. else { // (verticalTextPosition == BOTTOM)
  811. if (horizontalTextPosition != CENTER) {
  812. textR.y = iconR.height - textR.height;
  813. }
  814. else {
  815. textR.y = (iconR.height + gap);
  816. }
  817. }
  818. if (horizontalTextPosition == LEFT) {
  819. textR.x = -(textR.width + gap);
  820. }
  821. else if (horizontalTextPosition == CENTER) {
  822. textR.x = (iconR.width / 2) - (textR.width / 2);
  823. }
  824. else { // (horizontalTextPosition == RIGHT)
  825. textR.x = (iconR.width + gap);
  826. }
  827. /* labelR is the rectangle that contains iconR and textR.
  828. * Move it to its proper position given the labelAlignment
  829. * properties.
  830. *
  831. * To avoid actually allocating a Rectangle, Rectangle.union
  832. * has been inlined below.
  833. */
  834. int labelR_x = Math.min(iconR.x, textR.x);
  835. int labelR_width = Math.max(iconR.x + iconR.width,
  836. textR.x + textR.width) - labelR_x;
  837. int labelR_y = Math.min(iconR.y, textR.y);
  838. int labelR_height = Math.max(iconR.y + iconR.height,
  839. textR.y + textR.height) - labelR_y;
  840. int dx, dy;
  841. if (verticalAlignment == TOP) {
  842. dy = viewR.y - labelR_y;
  843. }
  844. else if (verticalAlignment == CENTER) {
  845. dy = (viewR.y + (viewR.height / 2)) - (labelR_y + (labelR_height / 2));
  846. }
  847. else { // (verticalAlignment == BOTTOM)
  848. dy = (viewR.y + viewR.height) - (labelR_y + labelR_height);
  849. }
  850. if (horizontalAlignment == LEFT) {
  851. dx = viewR.x - labelR_x;
  852. }
  853. else if (horizontalAlignment == RIGHT) {
  854. dx = (viewR.x + viewR.width) - (labelR_x + labelR_width);
  855. }
  856. else { // (horizontalAlignment == CENTER)
  857. dx = (viewR.x + (viewR.width / 2)) -
  858. (labelR_x + (labelR_width / 2));
  859. }
  860. /* Translate textR and glypyR by dx,dy.
  861. */
  862. textR.x += dx;
  863. textR.y += dy;
  864. iconR.x += dx;
  865. iconR.y += dy;
  866. return text;
  867. }
  868. /**
  869. * Paint a component c on an abitrary graphics g in the
  870. * specified rectangle, specifying the rectangle's upper left corner
  871. * and size. The component is reparented to a private
  872. * container (whose parent becomes p) which prevents c.validate() and
  873. * and c.repaint() calls from propogating up the tree. The intermediate
  874. * container has no other effect.
  875. *
  876. * @param g the Graphics object to draw on
  877. * @param c the Component to draw
  878. * @param p the intermedate Container
  879. * @param x an int specifying the left side of the area draw in, in pixels,
  880. * measured from the left edge of the graphics context
  881. * @param y an int specifying the top of the area to draw in, in pixels
  882. * measured down from the top edge of the graphics context
  883. * @param w an int specifying the width of the area draw in, in pixels
  884. * @param h an int specifying the height of the area draw in, in pixels
  885. */
  886. public static void paintComponent(Graphics g, Component c, Container p, int x, int y, int w, int h) {
  887. getCellRendererPane(c, p).paintComponent(g, c, p, x, y, w, h,false);
  888. }
  889. /**
  890. * Paint a component c on an abitrary graphics g in the
  891. * specified rectangle, specifying a Rectangle object. The component is reparented to a private
  892. * container (whose parent becomes p) which prevents c.validate() and
  893. * and c.repaint() calls from propogating up the tree. The intermediate
  894. * container has no other effect.
  895. *
  896. * @param g the Graphics object to draw on
  897. * @param c the Component to draw
  898. * @param p the intermedate Container
  899. * @param r the Rectangle to draw in
  900. */
  901. public static void paintComponent(Graphics g, Component c, Container p, Rectangle r) {
  902. paintComponent(g, c, p, r.x, r.y, r.width, r.height);
  903. }
  904. /*
  905. * Ensure that cell renderer c has a ComponentShell parent and that
  906. * the shells parent is p.
  907. */
  908. private static CellRendererPane getCellRendererPane(Component c, Container p) {
  909. Container shell = c.getParent();
  910. if (shell instanceof CellRendererPane) {
  911. if (shell.getParent() != p) {
  912. p.add(shell);
  913. }
  914. } else {
  915. shell = new CellRendererPane();
  916. shell.add(c);
  917. p.add(shell);
  918. }
  919. return (CellRendererPane)shell;
  920. }
  921. /**
  922. * A simple minded look and feel change: ask each node in the tree
  923. * to updateUI() -- that is, to initialize its UI property with the
  924. * current look and feel.
  925. */
  926. public static void updateComponentTreeUI(Component c) {
  927. updateComponentTreeUI0(c);
  928. c.invalidate();
  929. c.validate();
  930. c.repaint();
  931. }
  932. private static void updateComponentTreeUI0(Component c) {
  933. if (c instanceof JComponent) {
  934. ((JComponent) c).updateUI();
  935. }
  936. Component[] children = null;
  937. if (c instanceof JMenu) {
  938. children = ((JMenu)c).getMenuComponents();
  939. }
  940. else if (c instanceof Container) {
  941. children = ((Container)c).getComponents();
  942. }
  943. if (children != null) {
  944. for(int i = 0; i < children.length; i++) {
  945. updateComponentTreeUI0(children[i]);
  946. }
  947. }
  948. }
  949. /**
  950. * Causes <i>doRun.run()</i> to be executed asynchronously on the
  951. * AWT event dispatching thread. This will happen after all
  952. * pending AWT events have been processed. This method should
  953. * be used when an application thread needs to update the GUI.
  954. * In the following example the <code>invokeLater</code> call queues
  955. * the <code>Runnable</code> object <code>doHelloWorld</code>
  956. * on the event dispatching thread and
  957. * then prints a message.
  958. * <pre>
  959. * Runnable doHelloWorld = new Runnable() {
  960. * public void run() {
  961. * System.out.println("Hello World on " + Thread.currentThread());
  962. * }
  963. * };
  964. *
  965. * SwingUtilities.invokeLater(doHelloWorld);
  966. * System.out.println("This might well be displayed before the other message.");
  967. * </pre>
  968. * If invokeLater is called from the event dispatching thread --
  969. * for example, from a JButton's ActionListener -- the <i>doRun.run()</i> will
  970. * still be deferred until all pending events have been processed.
  971. * Note that if the <i>doRun.run()</i> throws an uncaught exception
  972. * the event dispatching thread will unwind (not the current thread).
  973. * <p>
  974. * Additional documentation and examples for this method can be
  975. * found in
  976. * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a>,
  977. * in <em>The Java Tutorial</em>.
  978. * <p>
  979. * As of 1.3 this method is just a cover for <code>java.awt.EventQueue.invokeLater()</code>.
  980. *
  981. * @see #invokeAndWait
  982. */
  983. public static void invokeLater(Runnable doRun) {
  984. EventQueue.invokeLater(doRun);
  985. }
  986. /**
  987. * Causes <i>doRun.run()</i> to be executed synchronously on the
  988. * AWT event dispatching thread. This call will block until
  989. * all pending AWT events have been processed and (then)
  990. * <i>doRun.run()</i> returns. This method should
  991. * be used when an application thread needs to update the GUI.
  992. * It should not be called from the EventDispatchThread.
  993. * Here's an example that creates a new application thread
  994. * that uses invokeAndWait() to print a string from the event
  995. * dispatching thread and then, when that's finished, print
  996. * a string from the application thread.
  997. * <pre>
  998. * final Runnable doHelloWorld = new Runnable() {
  999. * public void run() {
  1000. * System.out.println("Hello World on " + Thread.currentThread());
  1001. * }
  1002. * };
  1003. *
  1004. * Thread appThread = new Thread() {
  1005. * public void run() {
  1006. * try {
  1007. * SwingUtilities.invokeAndWait(doHelloWorld);
  1008. * }
  1009. * catch (Exception e) {
  1010. * e.printStackTrace();
  1011. * }
  1012. * System.out.println("Finished on " + Thread.currentThread());
  1013. * }
  1014. * };
  1015. * appThread.start();
  1016. * </pre>
  1017. * Note that if the Runnable.run() method throws an uncaught exception
  1018. * (on the event dispatching thread) it's caught and rethrown, as
  1019. * an InvocationTargetException, on the callers thread.
  1020. * <p>
  1021. * Additional documentation and examples for this method can be
  1022. * found in
  1023. * <A HREF="http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html">How to Use Threads</a>,
  1024. * in <em>The Java Tutorial</em>.
  1025. * <p>
  1026. * As of 1.3 this method is just a cover for <code>java.awt.EventQueue.invokeAndWait()</code>.
  1027. *
  1028. * @exception InterruptedException if we're interrupted while waiting for
  1029. * the event dispatching thread to finish excecuting <i>doRun.run()</i>
  1030. * @exception InvocationTargetException if <i>doRun.run()</i> throws
  1031. *
  1032. * @see #invokeLater
  1033. */
  1034. public static void invokeAndWait(final Runnable doRun)
  1035. throws InterruptedException, InvocationTargetException
  1036. {
  1037. EventQueue.invokeAndWait(doRun);
  1038. }
  1039. /**
  1040. * Returns true if the current thread is an AWT event dispatching thread.
  1041. * <p>
  1042. * As of 1.3 this method is just a cover for
  1043. * <code>java.awt.EventQueue.isEventDispatchThread()</code>.
  1044. *
  1045. * @return true if the current thread is an AWT event dispatching thread
  1046. */
  1047. public static boolean isEventDispatchThread()
  1048. {
  1049. return EventQueue.isDispatchThread();
  1050. }
  1051. /*
  1052. * --- Accessibility Support ---
  1053. *
  1054. */
  1055. /**
  1056. * Get the index of this object in its accessible parent.<p>
  1057. *
  1058. * Note: as of the Java 2 platform v1.3, it is recommended that developers call
  1059. * Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
  1060. * of using this method.
  1061. *
  1062. * @return -1 of this object does not have an accessible parent.
  1063. * Otherwise, the index of the child in its accessible parent.
  1064. */
  1065. public static int getAccessibleIndexInParent(Component c) {
  1066. return c.getAccessibleContext().getAccessibleIndexInParent();
  1067. }
  1068. /**
  1069. * Returns the Accessible child contained at the local coordinate
  1070. * Point, if one exists.
  1071. *
  1072. * @return the Accessible at the specified location, if it exists
  1073. */
  1074. public static Accessible getAccessibleAt(Component c, Point p) {
  1075. if (c instanceof Container) {
  1076. return c.getAccessibleContext().getAccessibleComponent().getAccessibleAt(p);
  1077. } else if (c instanceof Accessible) {
  1078. Accessible a = (Accessible) c;
  1079. if (a != null) {
  1080. AccessibleContext ac = a.getAccessibleContext();
  1081. if (ac != null) {
  1082. AccessibleComponent acmp;
  1083. Point location;
  1084. int nchildren = ac.getAccessibleChildrenCount();
  1085. for (int i=0; i < nchildren; i++) {
  1086. a = ac.getAccessibleChild(i);
  1087. if ((a != null)) {
  1088. ac = a.getAccessibleContext();
  1089. if (ac != null) {
  1090. acmp = ac.getAccessibleComponent();
  1091. if ((acmp != null) && (acmp.isShowing())) {
  1092. location = acmp.getLocation();
  1093. Point np = new Point(p.x-location.x,
  1094. p.y-location.y);
  1095. if (acmp.contains(np)){
  1096. return a;
  1097. }
  1098. }
  1099. }
  1100. }
  1101. }
  1102. }
  1103. }
  1104. return (Accessible) c;
  1105. }
  1106. return null;
  1107. }
  1108. /**
  1109. * Get the state of this object. <p>
  1110. *
  1111. * Note: as of the Java 2 platform v1.3, it is recommended that developers call
  1112. * Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
  1113. * of using this method.
  1114. *
  1115. * @return an instance of AccessibleStateSet containing the current state
  1116. * set of the object
  1117. * @see AccessibleState
  1118. */
  1119. public static AccessibleStateSet getAccessibleStateSet(Component c) {
  1120. return c.getAccessibleContext().getAccessibleStateSet();
  1121. }
  1122. /**
  1123. * Returns the number of accessible children in the object. If all
  1124. * of the children of this object implement Accessible, than this
  1125. * method should return the number of children of this object. <p>
  1126. *
  1127. * Note: as of the Java 2 platform v1.3, it is recommended that developers call
  1128. * Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
  1129. * of using this method.
  1130. *
  1131. * @return the number of accessible children in the object.
  1132. */
  1133. public static int getAccessibleChildrenCount(Component c) {
  1134. return c.getAccessibleContext().getAccessibleChildrenCount();
  1135. }
  1136. /**
  1137. * Return the nth Accessible child of the object. <p>
  1138. *
  1139. * Note: as of the Java 2 platform v1.3, it is recommended that developers call
  1140. * Component.AccessibleAWTComponent.getAccessibleIndexInParent() instead
  1141. * of using this method.
  1142. *
  1143. * @param i zero-based index of child
  1144. * @return the nth Accessible child of the object
  1145. */
  1146. public static Accessible getAccessibleChild(Component c, int i) {
  1147. return c.getAccessibleContext().getAccessibleChild(i);
  1148. }
  1149. /**
  1150. * Return the child component which has focus, if any. The HotJava
  1151. * SecurityManager forbids applet access to getFocusOwner(), so if the
  1152. * component is an applet, we check whether a JComponent has focus.
  1153. * Non-Swing components in an applet on HotJava are out-of-luck,
  1154. * unfortunately.
  1155. */
  1156. public static Component findFocusOwner(Component c) {
  1157. if (c instanceof Window) {
  1158. return ((Window)c).getFocusOwner();
  1159. }
  1160. if (c instanceof JComponent && ((JComponent)c).hasFocus()) {
  1161. return c;
  1162. }
  1163. if (c instanceof Container) {
  1164. int n = ((Container)c).getComponentCount();
  1165. for (int i = 0; i < n; i++) {
  1166. Component focusOwner =
  1167. findFocusOwner(((Container)c).getComponent(i));
  1168. if (focusOwner != null) {
  1169. return focusOwner;
  1170. }
  1171. }
  1172. return null;
  1173. } else {
  1174. return null; // Component doesn't have hasFocus().
  1175. }
  1176. }
  1177. /**
  1178. * If c is a JRootPane descendant return its JRootPane ancestor.
  1179. * If c is a RootPaneContainer then return its JRootPane.
  1180. * @return the JRootPane for Component c or null.
  1181. */
  1182. public static JRootPane getRootPane(Component c) {
  1183. if (c instanceof RootPaneContainer) {
  1184. return ((RootPaneContainer)c).getRootPane();
  1185. }
  1186. for( ; c != null; c = c.getParent()) {
  1187. if (c instanceof JRootPane) {
  1188. return (JRootPane)c;
  1189. }
  1190. }
  1191. return null;
  1192. }
  1193. /**
  1194. * Returns the root component for the current component tree.
  1195. * @return the first ancestor of c that's a Window or the last Applet ancestor
  1196. */
  1197. public static Component getRoot(Component c) {
  1198. Component applet = null;
  1199. for(Component p = c; p != null; p = p.getParent()) {
  1200. if (p instanceof Window) {
  1201. return p;
  1202. }
  1203. if (p instanceof Applet) {
  1204. applet = p;
  1205. }
  1206. }
  1207. return applet;
  1208. }
  1209. /**
  1210. * Invokes <code>actionPerformed</code> on <code>action</code> if
  1211. * <code>action</code> is enabled (and non null). The command for the
  1212. * ActionEvent is determined by:
  1213. * <ol>
  1214. * <li>If the action was registered via
  1215. * <code>registerKeyboardAction</code>, then the command string
  1216. * passed in (null will be used if null was passed in).
  1217. * <li>Action value with name Action.ACTION_COMMAND_KEY, unless null.
  1218. * <li>String value of the KeyEvent, unless <code>getKeyChar</code>
  1219. * returns KeyEvent.CHAR_UNDEFINED..
  1220. * </ol>
  1221. * This will return true if <code>action</code> is non-null and
  1222. * actionPerformed is invoked on it.
  1223. *
  1224. * @since 1.3
  1225. */
  1226. public static boolean notifyAction(Action action, KeyStroke ks,
  1227. KeyEvent event, Object sender,
  1228. int modifiers) {
  1229. if (action == null || !action.isEnabled()) {
  1230. return false;
  1231. }
  1232. Object commandO;
  1233. boolean stayNull;
  1234. // Get the command object.
  1235. commandO = action.getValue(Action.ACTION_COMMAND_KEY);
  1236. if (commandO == null && (action instanceof JComponent.ActionStandin)) {
  1237. // ActionStandin is used for historical reasons to support
  1238. // registerKeyboardAction with a null value.
  1239. stayNull = true;
  1240. }
  1241. else {
  1242. stayNull = false;
  1243. }
  1244. // Convert it to a string.
  1245. String command;
  1246. if (commandO != null) {
  1247. command = commandO.toString();
  1248. }
  1249. else if (!stayNull && event.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
  1250. command = String.valueOf(event.getKeyChar());
  1251. }
  1252. else {
  1253. // Do null for undefined chars, or if registerKeyboardAction
  1254. // was called with a null.
  1255. command = null;
  1256. }
  1257. action.actionPerformed(new ActionEvent(sender,
  1258. ActionEvent.ACTION_PERFORMED, command, modifiers));
  1259. return true;
  1260. }
  1261. /**
  1262. * Convenience method to change the UI InputMap for <code>component</code>
  1263. * to <code>uiInputMap</code>. If <code>uiInputMap</code> is null,
  1264. * this removes any previously installed UI InputMap.
  1265. *
  1266. * @since 1.3
  1267. */
  1268. public static void replaceUIInputMap(JComponent component, int type,
  1269. InputMap uiInputMap) {
  1270. InputMap map = component.getInputMap(type);
  1271. while (map != null) {
  1272. InputMap parent = map.getParent();
  1273. if (parent == null || (parent instanceof UIResource)) {
  1274. map.setParent(uiInputMap);
  1275. return;
  1276. }
  1277. map = parent;
  1278. }
  1279. }
  1280. /**
  1281. * Convenience method to change the UI ActionMap for <code>component</code>
  1282. * to <code>uiActionMap</code>. If <code>uiActionMap</code> is null,
  1283. * this removes any previously installed UI ActionMap.
  1284. *
  1285. * @since 1.3
  1286. */
  1287. public static void replaceUIActionMap(JComponent component,
  1288. ActionMap uiActionMap) {
  1289. ActionMap map = component.getActionMap();
  1290. while (map != null) {
  1291. ActionMap parent = map.getParent();
  1292. if (parent == null || (parent instanceof UIResource)) {
  1293. map.setParent(uiActionMap);
  1294. return;
  1295. }
  1296. map = parent;
  1297. }
  1298. }
  1299. /**
  1300. * Returns the InputMap provided by the UI for condition
  1301. * <code>condition</code> in component <code>component</code>.
  1302. * <p>This will return null if the UI has not installed a InputMap
  1303. * of the specified type.
  1304. *
  1305. * @since 1.3
  1306. */
  1307. public static InputMap getUIInputMap(JComponent component, int condition) {
  1308. InputMap map = component.getInputMap(condition, false);
  1309. while (map != null) {
  1310. InputMap parent = map.getParent();
  1311. if (parent instanceof UIResource) {
  1312. return parent;
  1313. }
  1314. map = parent;
  1315. }
  1316. return null;
  1317. }
  1318. /**
  1319. * Returns the ActionMap provided by the UI
  1320. * in component <code>component</code>.
  1321. * <p>This will return null if the UI has not installed an ActionMap.
  1322. *
  1323. * @since 1.3
  1324. */
  1325. public static ActionMap getUIActionMap(JComponent component) {
  1326. ActionMap map = component.getActionMap(false);
  1327. while (map != null) {
  1328. ActionMap parent = map.getParent();
  1329. if (parent instanceof UIResource) {
  1330. return parent;
  1331. }
  1332. map = parent;
  1333. }
  1334. return null;
  1335. }
  1336. // Don't use String, as it's not guaranteed to be unique in a Hashtable.
  1337. private static final Object sharedOwnerFrameKey =
  1338. new StringBuffer("SwingUtilities.sharedOwnerFrame");
  1339. /**
  1340. * Returns a toolkit-private, shared, invisible Frame
  1341. * to be the owner for JDialogs and JWindows created with
  1342. * null owners.
  1343. */
  1344. static Frame getSharedOwnerFrame() {
  1345. Frame sharedOwnerFrame =
  1346. (Frame)SwingUtilities.appContextGet(sharedOwnerFrameKey);
  1347. if (sharedOwnerFrame == null) {
  1348. sharedOwnerFrame = new Frame() {
  1349. public void show() {
  1350. // This frame can never be shown
  1351. }
  1352. public synchronized void dispose() {
  1353. try {
  1354. getToolkit().getSystemEventQueue();
  1355. super.dispose();
  1356. } catch (Exception e) {
  1357. // untrusted code not allowed to dispose
  1358. }
  1359. }
  1360. };
  1361. SwingUtilities.appContextPut(sharedOwnerFrameKey,
  1362. sharedOwnerFrame);
  1363. }
  1364. return sharedOwnerFrame;
  1365. }
  1366. /* Don't make these AppContext accessors public or protected --
  1367. * since AppContext is in sun.awt in 1.2, we shouldn't expose it
  1368. * even indirectly with a public API.
  1369. */
  1370. static Object appContextGet(Object key) {
  1371. return sun.awt.AppContext.getAppContext().get(key);
  1372. }
  1373. static void appContextPut(Object key, Object value) {
  1374. sun.awt.AppContext.getAppContext().put(key, value);
  1375. }
  1376. static void appContextRemove(Object key) {
  1377. sun.awt.AppContext.getAppContext().remove(key);
  1378. }
  1379. static Class loadSystemClass(String className) throws ClassNotFoundException {
  1380. return Class.forName(className, true, ClassLoader.getSystemClassLoader());
  1381. }
  1382. final static void doPrivileged(final Runnable doRun) {
  1383. java.security.AccessController.doPrivileged(
  1384. new java.security.PrivilegedAction() {
  1385. public Object run() {
  1386. doRun.run();
  1387. return null;
  1388. }
  1389. }
  1390. );
  1391. }
  1392. /*
  1393. * Convenience function for determining ComponentOrientation. Helps us
  1394. * avoid having Munge directives throughout the code.
  1395. */
  1396. static boolean isLeftToRight( Component c ) {
  1397. return c.getComponentOrientation().isLeftToRight();
  1398. }
  1399. private SwingUtilities() {
  1400. throw new Error("SwingUtilities is just a container for static methods");
  1401. }
  1402. /**
  1403. * Returns true if the Icon <code>icon</code> is an instance of
  1404. * ImageIcon, and the image it contains is the same as <code>image</code>.
  1405. */
  1406. static boolean doesIconReferenceImage(Icon icon, Image image) {
  1407. Image iconImage = (icon != null && (icon instanceof ImageIcon)) ?
  1408. ((ImageIcon)icon).getImage() : null;
  1409. return (iconImage == image);
  1410. }
  1411. }