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