Source for javax.swing.SwingUtilities

   1: /* SwingUtilities.java --
   2:    Copyright (C) 2002, 2004, 2005, 2006,  Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: 
  39: package javax.swing;
  40: 
  41: import java.applet.Applet;
  42: import java.awt.Component;
  43: import java.awt.ComponentOrientation;
  44: import java.awt.Container;
  45: import java.awt.FontMetrics;
  46: import java.awt.Frame;
  47: import java.awt.Graphics;
  48: import java.awt.Insets;
  49: import java.awt.KeyboardFocusManager;
  50: import java.awt.Point;
  51: import java.awt.Rectangle;
  52: import java.awt.Shape;
  53: import java.awt.Window;
  54: import java.awt.event.ActionEvent;
  55: import java.awt.event.InputEvent;
  56: import java.awt.event.KeyEvent;
  57: import java.awt.event.MouseEvent;
  58: import java.lang.reflect.InvocationTargetException;
  59: 
  60: import javax.accessibility.Accessible;
  61: import javax.accessibility.AccessibleStateSet;
  62: import javax.swing.plaf.ActionMapUIResource;
  63: import javax.swing.plaf.InputMapUIResource;
  64: 
  65: /**
  66:  * A number of static utility functions which are
  67:  * useful when drawing swing components, dispatching events, or calculating
  68:  * regions which need painting.
  69:  *
  70:  * @author Graydon Hoare (graydon@redhat.com)
  71:  * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  72:  */
  73: public class SwingUtilities
  74:   implements SwingConstants
  75: {
  76:   /** 
  77:    * This frame should be used as parent for JWindow or JDialog 
  78:    * that doesn't an owner
  79:    */
  80:   private static OwnerFrame ownerFrame;
  81: 
  82:   private SwingUtilities()
  83:   {
  84:     // Do nothing.
  85:   }
  86: 
  87:   /**
  88:    * Calculates the portion of the component's bounds which is inside the
  89:    * component's border insets. This area is usually the area a component
  90:    * should confine its painting to. The coordinates are returned in terms
  91:    * of the <em>component's</em> coordinate system, where (0,0) is the
  92:    * upper left corner of the component's bounds.
  93:    *
  94:    * @param c  the component to measure the bounds of (if <code>null</code>, 
  95:    *     this method returns <code>null</code>).
  96:    * @param r  a carrier to store the return value in (if <code>null</code>, a
  97:    *     new <code>Rectangle</code> instance is created).
  98:    *
  99:    * @return The calculated area inside the component and its border insets.
 100:    */
 101:   public static Rectangle calculateInnerArea(JComponent c, Rectangle r)
 102:   {
 103:     if (c == null)
 104:       return null;
 105:     r = c.getBounds(r);
 106:     Insets i = c.getInsets();
 107:     r.x = i.left;
 108:     r.width = r.width - i.left - i.right;
 109:     r.y = i.top;
 110:     r.height = r.height - i.top - i.bottom;
 111:     return r;
 112:   }
 113: 
 114:   /**
 115:    * Returns the focus owner or <code>null</code> if <code>comp</code> is not
 116:    * the focus owner or a parent of it.
 117:    * 
 118:    * @param comp the focus owner or a parent of it
 119:    * 
 120:    * @return the focus owner, or <code>null</code>
 121:    * 
 122:    * @deprecated 1.4 Replaced by
 123:    * <code>KeyboardFocusManager.getFocusOwner()</code>.
 124:    */
 125:   public static Component findFocusOwner(Component comp)
 126:   {
 127:     // Get real focus owner.
 128:     Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager()
 129:                            .getFocusOwner();
 130: 
 131:     // Check if comp is the focus owner or a parent of it.
 132:     Component tmp = focusOwner;
 133:     
 134:     while (tmp != null)
 135:       {
 136:     if (tmp == comp)
 137:       return focusOwner;
 138: 
 139:     tmp = tmp.getParent();
 140:       }
 141:     
 142:     return null;
 143:   }
 144:   
 145:   /**
 146:    * Returns the <code>Accessible</code> child of the specified component
 147:    * which appears at the supplied <code>Point</code>.  If there is no
 148:    * child located at that particular pair of co-ordinates, null is returned
 149:    * instead.
 150:    *
 151:    * @param c the component whose children may be found at the specified
 152:    *          point.
 153:    * @param p the point at which to look for the existence of children
 154:    *          of the specified component.
 155:    * @return the <code>Accessible</code> child at the point, <code>p</code>,
 156:    *         or null if there is no child at this point.
 157:    * @see javax.accessibility.AccessibleComponent#getAccessibleAt
 158:    */
 159:   public static Accessible getAccessibleAt(Component c, Point p)
 160:   {
 161:     return c.getAccessibleContext().getAccessibleComponent().getAccessibleAt(p);
 162:   }
 163: 
 164:   /**
 165:    * <p>
 166:    * Returns the <code>Accessible</code> child of the specified component
 167:    * that has the supplied index within the parent component.  The indexing
 168:    * of the children is zero-based, making the first child have an index of
 169:    * 0.
 170:    * </p>
 171:    * <p>
 172:    * Caution is advised when using this method, as its operation relies
 173:    * on the behaviour of varying implementations of an abstract method.
 174:    * For greater surety, direct use of the AWT component implementation
 175:    * of this method is advised.
 176:    * </p>
 177:    *
 178:    * @param c the component whose child should be returned.
 179:    * @param i the index of the child within the parent component.
 180:    * @return the <code>Accessible</code> child at index <code>i</code>
 181:    *         in the component, <code>c</code>.
 182:    * @see javax.accessibility.AccessibleContext#getAccessibleChild
 183:    * @see java.awt.Component.AccessibleAWTComponent#getAccessibleChild
 184:    */
 185:   public static Accessible getAccessibleChild(Component c, int i)
 186:   {
 187:     return c.getAccessibleContext().getAccessibleChild(i);
 188:   }
 189: 
 190:   /**
 191:    * <p>
 192:    * Returns the number of <code>Accessible</code> children within
 193:    * the supplied component.
 194:    * </p>
 195:    * <p>
 196:    * Caution is advised when using this method, as its operation relies
 197:    * on the behaviour of varying implementations of an abstract method.
 198:    * For greater surety, direct use of the AWT component implementation
 199:    * of this method is advised.
 200:    * </p>
 201:    *
 202:    * @param c the component whose children should be counted.
 203:    * @return the number of children belonging to the component,
 204:    *         <code>c</code>.
 205:    * @see javax.accessibility.AccessibleContext#getAccessibleChildrenCount
 206:    * @see java.awt.Component.AccessibleAWTComponent#getAccessibleChildrenCount
 207:    */
 208:   public static int getAccessibleChildrenCount(Component c)
 209:   {
 210:     return c.getAccessibleContext().getAccessibleChildrenCount();
 211:   }
 212: 
 213:   /**
 214:    * <p>
 215:    * Returns the zero-based index of the specified component
 216:    * within its parent.  If the component doesn't have a parent,
 217:    * -1 is returned.
 218:    * </p>
 219:    * <p>
 220:    * Caution is advised when using this method, as its operation relies
 221:    * on the behaviour of varying implementations of an abstract method.
 222:    * For greater surety, direct use of the AWT component implementation
 223:    * of this method is advised.
 224:    * </p>
 225:    *
 226:    * @param c the component whose parental index should be found.
 227:    * @return the index of the component within its parent, or -1
 228:    *         if the component doesn't have a parent.
 229:    * @see javax.accessibility.AccessibleContext#getAccessibleIndexInParent
 230:    * @see java.awt.Component.AccessibleAWTComponent#getAccessibleIndexInParent
 231:    */
 232:   public static int getAccessibleIndexInParent(Component c)
 233:   {
 234:     return c.getAccessibleContext().getAccessibleIndexInParent();
 235:   }
 236: 
 237:   /**
 238:    * <p>
 239:    * Returns a set of <code>AccessibleState</code>s, which represent
 240:    * the state of the supplied component.
 241:    * </p>
 242:    * <p>
 243:    * Caution is advised when using this method, as its operation relies
 244:    * on the behaviour of varying implementations of an abstract method.
 245:    * For greater surety, direct use of the AWT component implementation
 246:    * of this method is advised.
 247:    * </p>
 248:    *
 249:    * @param c the component whose accessible state should be retrieved.
 250:    * @return a set of <code>AccessibleState</code> objects, which represent
 251:    *         the state of the supplied component.
 252:    * @see javax.accessibility.AccessibleContext#getAccessibleStateSet
 253:    * @see java.awt.Component.AccessibleAWTComponent#getAccessibleStateSet
 254:    */
 255:   public static AccessibleStateSet getAccessibleStateSet(Component c)
 256:   {
 257:     return c.getAccessibleContext().getAccessibleStateSet();
 258:   }
 259: 
 260:   /**
 261:    * Calculates the bounds of a component in the component's own coordinate
 262:    * space. The result has the same height and width as the component's
 263:    * bounds, but its location is set to (0,0).
 264:    *
 265:    * @param aComponent The component to measure
 266:    *
 267:    * @return The component's bounds in its local coordinate space
 268:    */
 269:   public static Rectangle getLocalBounds(Component aComponent)
 270:   {
 271:     Rectangle bounds = aComponent.getBounds();
 272:     return new Rectangle(0, 0, bounds.width, bounds.height);
 273:   }
 274: 
 275:   /**
 276:    * If <code>comp</code> is a RootPaneContainer, return its JRootPane.
 277:    * Otherwise call <code>getAncestorOfClass(JRootPane.class, a)</code>.
 278:    *
 279:    * @param comp The component to get the JRootPane of
 280:    *
 281:    * @return a suitable JRootPane for <code>comp</code>, or <code>null</code>
 282:    * 
 283:    * @see javax.swing.RootPaneContainer#getRootPane
 284:    * @see #getAncestorOfClass
 285:    */
 286:   public static JRootPane getRootPane(Component comp)
 287:   {
 288:     if (comp instanceof RootPaneContainer)
 289:       return ((RootPaneContainer)comp).getRootPane();
 290:     else
 291:       return (JRootPane) getAncestorOfClass(JRootPane.class, comp);
 292:   }
 293: 
 294:   /**
 295:    * Returns the least ancestor of <code>comp</code> which has the
 296:    * specified name.
 297:    *
 298:    * @param name The name to search for
 299:    * @param comp The component to search the ancestors of
 300:    *
 301:    * @return The nearest ancestor of <code>comp</code> with the given
 302:    * name, or <code>null</code> if no such ancestor exists
 303:    *
 304:    * @see java.awt.Component#getName
 305:    * @see #getAncestorOfClass
 306:    */
 307:   public static Container getAncestorNamed(String name, Component comp)
 308:   {
 309:     while (comp != null && (comp.getName() != name))
 310:       comp = comp.getParent();
 311:     return (Container) comp;
 312:   }
 313: 
 314:   /**
 315:    * Returns the least ancestor of <code>comp</code> which is an instance
 316:    * of the specified class.
 317:    *
 318:    * @param c The class to search for
 319:    * @param comp The component to search the ancestors of
 320:    *
 321:    * @return The nearest ancestor of <code>comp</code> which is an instance
 322:    * of the given class, or <code>null</code> if no such ancestor exists
 323:    *
 324:    * @see #getAncestorOfClass
 325:    * @see #windowForComponent
 326:    */
 327:   public static Container getAncestorOfClass(Class c, Component comp)
 328:   {
 329:     while (comp != null && (! c.isInstance(comp)))
 330:       comp = comp.getParent();
 331:     return (Container) comp;
 332:   }
 333: 
 334:   /**
 335:    * Returns the first ancestor of <code>comp</code> that is a {@link Window}
 336:    * or <code>null</code> if <code>comp</code> is not contained in a
 337:    * {@link Window}.
 338:    *
 339:    * This is equivalent to calling
 340:    * <code>getAncestorOfClass(Window, comp)</code> or
 341:    * <code>windowForComponent(comp)</code>.
 342:    *
 343:    * @param comp the component for which we are searching the ancestor Window
 344:    *
 345:    * @return the first ancestor Window of <code>comp</code> or
 346:    *     <code>null</code> if <code>comp</code> is not contained in a Window
 347:    */
 348:   public static Window getWindowAncestor(Component comp)
 349:   {
 350:     return (Window) getAncestorOfClass(Window.class, comp);
 351:   }
 352: 
 353:   /**
 354:    * Equivalent to calling <code>getAncestorOfClass(Window, comp)</code>.
 355:    *
 356:    * @param comp The component to search for an ancestor window 
 357:    *
 358:    * @return An ancestral window, or <code>null</code> if none exists
 359:    */
 360:   public static Window windowForComponent(Component comp)
 361:   {
 362:     return (Window) getAncestorOfClass(Window.class, comp);
 363:   }
 364: 
 365:   /**
 366:    * Returns the "root" of the component tree containint <code>comp</code>
 367:    * The root is defined as either the <em>least</em> ancestor of
 368:    * <code>comp</code> which is a {@link Window}, or the <em>greatest</em>
 369:    * ancestor of <code>comp</code> which is a {@link Applet} if no {@link
 370:    * Window} ancestors are found.
 371:    *
 372:    * @param comp The component to search for a root
 373:    *
 374:    * @return The root of the component's tree, or <code>null</code>
 375:    */
 376:   public static Component getRoot(Component comp)
 377:   {
 378:     Applet app = null;
 379:     Window win = null;
 380: 
 381:     while (comp != null)
 382:       {
 383:         if (win == null && comp instanceof Window)
 384:           win = (Window) comp;
 385:         else if (comp instanceof Applet)
 386:           app = (Applet) comp;
 387:         comp = comp.getParent();
 388:       }
 389:     
 390:     if (win != null)
 391:       return win;
 392:     return app;
 393:   }
 394: 
 395:   /**
 396:    * Return true if a descends from b, in other words if b is an ancestor of a.
 397:    * 
 398:    * @param a The child to search the ancestry of
 399:    * @param b The potential ancestor to search for
 400:    * @return true if a is a descendent of b, false otherwise
 401:    */
 402:   public static boolean isDescendingFrom(Component a, Component b)
 403:   {
 404:     while (true)
 405:       {
 406:         if (a == null || b == null)
 407:           return false;
 408:         if (a == b)
 409:           return true;
 410:         a = a.getParent();
 411:       }
 412:   }
 413: 
 414:   /**
 415:    * Returns the deepest descendent of parent which is both visible and
 416:    * contains the point <code>(x,y)</code>. Returns parent when either
 417:    * parent is not a container, or has no children which contain
 418:    * <code>(x,y)</code>. Returns <code>null</code> when either
 419:    * <code>(x,y)</code> is outside the bounds of parent, or parent is
 420:    * <code>null</code>.
 421:    * 
 422:    * @param parent The component to search the descendents of
 423:    * @param x Horizontal coordinate to search for
 424:    * @param y Vertical coordinate to search for
 425:    *
 426:    * @return A component containing <code>(x,y)</code>, or
 427:    * <code>null</code>
 428:    *
 429:    * @see java.awt.Container#findComponentAt(int, int)
 430:    */
 431:   public static Component getDeepestComponentAt(Component parent, int x, int y)
 432:   {
 433:     if (parent == null || (! parent.contains(x, y)))
 434:       return null;
 435: 
 436:     if (! (parent instanceof Container))
 437:       return parent;
 438: 
 439:     Container c = (Container) parent;
 440:     return c.findComponentAt(x, y);
 441:   }
 442: 
 443:   /**
 444:    * Converts a point from a component's local coordinate space to "screen"
 445:    * coordinates (such as the coordinate space mouse events are delivered
 446:    * in). This operation is equivalent to translating the point by the
 447:    * location of the component (which is the origin of its coordinate
 448:    * space).
 449:    *
 450:    * @param p The point to convert
 451:    * @param c The component which the point is expressed in terms of
 452:    *
 453:    * @see #convertPointFromScreen
 454:    */
 455:   public static void convertPointToScreen(Point p, Component c)
 456:   {
 457:     Point c0 = c.getLocationOnScreen();
 458:     p.translate(c0.x, c0.y);
 459:   }
 460: 
 461:   /**
 462:    * Converts a point from "screen" coordinates (such as the coordinate
 463:    * space mouse events are delivered in) to a component's local coordinate
 464:    * space. This operation is equivalent to translating the point by the
 465:    * negation of the component's location (which is the origin of its
 466:    * coordinate space).
 467:    *
 468:    * @param p The point to convert
 469:    * @param c The component which the point should be expressed in terms of
 470:    */
 471:   public static void convertPointFromScreen(Point p, Component c)
 472:   {
 473:     Point c0 = c.getLocationOnScreen();
 474:     p.translate(-c0.x, -c0.y);
 475:   }
 476: 
 477:   /**
 478:    * Converts a point <code>(x,y)</code> from the coordinate space of one
 479:    * component to another. This is equivalent to converting the point from
 480:    * <code>source</code> space to screen space, then back from screen space
 481:    * to <code>destination</code> space. If exactly one of the two
 482:    * Components is <code>null</code>, it is taken to refer to the root
 483:    * ancestor of the other component. If both are <code>null</code>, no
 484:    * transformation is done.
 485:    *
 486:    * @param source The component which the point is expressed in terms of
 487:    * @param x Horizontal coordinate of point to transform
 488:    * @param y Vertical coordinate of point to transform
 489:    * @param destination The component which the return value will be
 490:    * expressed in terms of
 491:    *
 492:    * @return The point <code>(x,y)</code> converted from the coordinate space of the
 493:    * source component to the coordinate space of the destination component
 494:    *
 495:    * @see #convertPointToScreen
 496:    * @see #convertPointFromScreen
 497:    * @see #convertRectangle
 498:    * @see #getRoot
 499:    */
 500:   public static Point convertPoint(Component source, int x, int y,
 501:                                    Component destination)
 502:   {
 503:     Point pt = new Point(x, y);
 504: 
 505:     if (source == null && destination == null)
 506:       return pt;
 507: 
 508:     if (source == null)
 509:       source = getRoot(destination);
 510: 
 511:     if (destination == null)
 512:       destination = getRoot(source);
 513: 
 514:     if (source.isShowing() && destination.isShowing())
 515:       {
 516:         convertPointToScreen(pt, source);
 517:         convertPointFromScreen(pt, destination);
 518:       }
 519: 
 520:     return pt;
 521:   }
 522:   
 523:   public static Point convertPoint(Component source, Point aPoint, Component destination)
 524:   {
 525:     return convertPoint(source, aPoint.x, aPoint.y, destination);
 526:   }
 527: 
 528:   /**
 529:    * Converts a rectangle from the coordinate space of one component to
 530:    * another. This is equivalent to converting the rectangle from
 531:    * <code>source</code> space to screen space, then back from screen space
 532:    * to <code>destination</code> space. If exactly one of the two
 533:    * Components is <code>null</code>, it is taken to refer to the root
 534:    * ancestor of the other component. If both are <code>null</code>, no
 535:    * transformation is done.
 536:    *
 537:    * @param source The component which the rectangle is expressed in terms of
 538:    * @param rect The rectangle to convert
 539:    * @param destination The component which the return value will be
 540:    * expressed in terms of
 541:    *
 542:    * @return A new rectangle, equal in size to the input rectangle, but
 543:    * with its position converted from the coordinate space of the source
 544:    * component to the coordinate space of the destination component
 545:    *
 546:    * @see #convertPointToScreen
 547:    * @see #convertPointFromScreen
 548:    * @see #convertPoint(Component, int, int, Component)
 549:    * @see #getRoot
 550:    */
 551:   public static Rectangle convertRectangle(Component source,
 552:                                            Rectangle rect,
 553:                                            Component destination)
 554:   {
 555:     Point pt = convertPoint(source, rect.x, rect.y, destination);
 556:     return new Rectangle(pt.x, pt.y, rect.width, rect.height);
 557:   }
 558: 
 559:   /**
 560:    * Convert a mouse event which refrers to one component to another.  This
 561:    * includes changing the mouse event's coordinate space, as well as the
 562:    * source property of the event. If <code>source</code> is
 563:    * <code>null</code>, it is taken to refer to <code>destination</code>'s
 564:    * root component. If <code>destination</code> is <code>null</code>, the
 565:    * new event will remain expressed in <code>source</code>'s coordinate
 566:    * system.
 567:    *
 568:    * @param source The component the mouse event currently refers to
 569:    * @param sourceEvent The mouse event to convert
 570:    * @param destination The component the new mouse event should refer to
 571:    *
 572:    * @return A new mouse event expressed in terms of the destination
 573:    * component's coordinate space, and with the destination component as
 574:    * its source
 575:    *
 576:    * @see #convertPoint(Component, int, int, Component)
 577:    */
 578:   public static MouseEvent convertMouseEvent(Component source,
 579:                                              MouseEvent sourceEvent,
 580:                                              Component destination)
 581:   {
 582:     Point newpt = convertPoint(source, sourceEvent.getX(), sourceEvent.getY(),
 583:                                destination);
 584: 
 585:     return new MouseEvent(destination, sourceEvent.getID(),
 586:                           sourceEvent.getWhen(), sourceEvent.getModifiersEx(),
 587:                           newpt.x, newpt.y, sourceEvent.getClickCount(),
 588:                           sourceEvent.isPopupTrigger(), sourceEvent.getButton());
 589:   }
 590: 
 591:   /**
 592:    * Recursively walk the component tree under <code>comp</code> calling
 593:    * <code>updateUI</code> on each {@link JComponent} found. This causes
 594:    * the entire tree to re-initialize its UI delegates.
 595:    *
 596:    * @param comp The component to walk the children of, calling <code>updateUI</code>
 597:    */
 598:   public static void updateComponentTreeUI(Component comp)
 599:   {
 600:     updateComponentTreeUIImpl(comp);
 601:     if (comp instanceof JComponent)
 602:       {
 603:         JComponent jc = (JComponent) comp;
 604:         jc.revalidate();
 605:       }
 606:     else
 607:       {
 608:         comp.invalidate();
 609:         comp.validate();
 610:       }
 611:     comp.repaint();
 612:   }
 613: 
 614:   /**
 615:    * Performs the actual work for {@link #updateComponentTreeUI(Component)}.
 616:    * This calls updateUI() on c if it is a JComponent, and then walks down
 617:    * the component tree and calls this method on each child component.
 618:    *
 619:    * @param c the component to update the UI
 620:    */
 621:   private static void updateComponentTreeUIImpl(Component c)
 622:   {
 623:     if (c instanceof JComponent)
 624:       {
 625:         JComponent jc = (JComponent) c;
 626:         jc.updateUI();
 627:       }
 628: 
 629:     Component[] components = null;
 630:     if (c instanceof JMenu)
 631:       components = ((JMenu) c).getMenuComponents();
 632:     else if (c instanceof Container)
 633:       components = ((Container) c).getComponents();
 634:     if (components != null)
 635:       {
 636:         for (int i = 0; i < components.length; ++i)
 637:           updateComponentTreeUIImpl(components[i]);
 638:       }
 639:   }
 640: 
 641:   /**
 642:    * <p>Layout a "compound label" consisting of a text string and an icon
 643:    * which is to be placed near the rendered text. Once the text and icon
 644:    * are laid out, the text rectangle and icon rectangle parameters are
 645:    * altered to store the calculated positions.</p>
 646:    *
 647:    * <p>The size of the text is calculated from the provided font metrics
 648:    * object.  This object should be the metrics of the font you intend to
 649:    * paint the label with.</p>
 650:    *
 651:    * <p>The position values control where the text is placed relative to
 652:    * the icon. The horizontal position value should be one of the constants
 653:    * <code>LEADING</code>, <code>TRAILING</code>, <code>LEFT</code>,
 654:    * <code>RIGHT</code> or <code>CENTER</code>. The vertical position value
 655:    * should be one fo the constants <code>TOP</code>, <code>BOTTOM</code>
 656:    * or <code>CENTER</code>.</p>
 657:    *
 658:    * <p>The text-icon gap value controls the number of pixels between the
 659:    * icon and the text.</p>
 660:    *
 661:    * <p>The alignment values control where the text and icon are placed, as
 662:    * a combined unit, within the view rectangle. The horizontal alignment
 663:    * value should be one of the constants <code>LEADING</code>,
 664:    * <code>TRAILING</code>, <code>LEFT</code>, <code>RIGHT</code> or
 665:    * <code>CENTER</code>. The vertical alignment valus should be one of the
 666:    * constants <code>TOP</code>, <code>BOTTOM</code> or
 667:    * <code>CENTER</code>.</p>
 668:    *
 669:    * <p>If the <code>LEADING</code> or <code>TRAILING</code> constants are
 670:    * given for horizontal alignment or horizontal text position, they are
 671:    * interpreted relative to the provided component's orientation property,
 672:    * a constant in the {@link java.awt.ComponentOrientation} class. For
 673:    * example, if the component's orientation is <code>LEFT_TO_RIGHT</code>,
 674:    * then the <code>LEADING</code> value is a synonym for <code>LEFT</code>
 675:    * and the <code>TRAILING</code> value is a synonym for
 676:    * <code>RIGHT</code></p>
 677:    *
 678:    * <p>If the text and icon are equal to or larger than the view
 679:    * rectangle, the horizontal and vertical alignment values have no
 680:    * affect.</p>
 681:    *
 682:    * @param c A component used for its orientation value
 683:    * @param fm The font metrics used to measure the text
 684:    * @param text The text to place in the compound label
 685:    * @param icon The icon to place next to the text
 686:    * @param verticalAlignment The vertical alignment of the label relative
 687:    * to its component
 688:    * @param horizontalAlignment The horizontal alignment of the label
 689:    * relative to its component
 690:    * @param verticalTextPosition The vertical position of the label's text
 691:    * relative to its icon
 692:    * @param horizontalTextPosition The horizontal position of the label's
 693:    * text relative to its icon
 694:    * @param viewR The view rectangle, specifying the area which layout is
 695:    * constrained to
 696:    * @param iconR A rectangle which is modified to hold the laid-out
 697:    * position of the icon
 698:    * @param textR A rectangle which is modified to hold the laid-out
 699:    * position of the text
 700:    * @param textIconGap The distance between text and icon
 701:    *
 702:    * @return The string of characters, possibly truncated with an elipsis,
 703:    * which is laid out in this label
 704:    */
 705: 
 706:   public static String layoutCompoundLabel(JComponent c, 
 707:                                            FontMetrics fm,
 708:                                            String text, 
 709:                                            Icon icon, 
 710:                                            int verticalAlignment,
 711:                                            int horizontalAlignment, 
 712:                                            int verticalTextPosition,
 713:                                            int horizontalTextPosition, 
 714:                                            Rectangle viewR,
 715:                                            Rectangle iconR, 
 716:                                            Rectangle textR, 
 717:                                            int textIconGap)
 718:   {
 719: 
 720:     // Fix up the orientation-based horizontal positions.
 721: 
 722:     if (horizontalTextPosition == LEADING)
 723:       {
 724:         if (c.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT)
 725:           horizontalTextPosition = RIGHT;
 726:         else
 727:           horizontalTextPosition = LEFT;
 728:       }
 729:     else if (horizontalTextPosition == TRAILING)
 730:       {
 731:         if (c.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT)
 732:           horizontalTextPosition = LEFT;
 733:         else
 734:           horizontalTextPosition = RIGHT;
 735:       }
 736: 
 737:     // Fix up the orientation-based alignments.
 738: 
 739:     if (horizontalAlignment == LEADING)
 740:       {
 741:         if (c.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT)
 742:           horizontalAlignment = RIGHT;
 743:         else
 744:           horizontalAlignment = LEFT;
 745:       }
 746:     else if (horizontalAlignment == TRAILING)
 747:       {
 748:         if (c.getComponentOrientation() == ComponentOrientation.RIGHT_TO_LEFT)
 749:           horizontalAlignment = LEFT;
 750:         else
 751:           horizontalAlignment = RIGHT;
 752:       }
 753:     
 754:     return layoutCompoundLabel(fm, text, icon,
 755:                                verticalAlignment,
 756:                                horizontalAlignment,
 757:                                verticalTextPosition,
 758:                                horizontalTextPosition,
 759:                                viewR, iconR, textR, textIconGap);
 760:   }
 761: 
 762:   /**
 763:    * <p>Layout a "compound label" consisting of a text string and an icon
 764:    * which is to be placed near the rendered text. Once the text and icon
 765:    * are laid out, the text rectangle and icon rectangle parameters are
 766:    * altered to store the calculated positions.</p>
 767:    *
 768:    * <p>The size of the text is calculated from the provided font metrics
 769:    * object.  This object should be the metrics of the font you intend to
 770:    * paint the label with.</p>
 771:    *
 772:    * <p>The position values control where the text is placed relative to
 773:    * the icon. The horizontal position value should be one of the constants
 774:    * <code>LEFT</code>, <code>RIGHT</code> or <code>CENTER</code>. The
 775:    * vertical position value should be one fo the constants
 776:    * <code>TOP</code>, <code>BOTTOM</code> or <code>CENTER</code>.</p>
 777:    *
 778:    * <p>The text-icon gap value controls the number of pixels between the
 779:    * icon and the text.</p>
 780:    *
 781:    * <p>The alignment values control where the text and icon are placed, as
 782:    * a combined unit, within the view rectangle. The horizontal alignment
 783:    * value should be one of the constants <code>LEFT</code>, <code>RIGHT</code> or
 784:    * <code>CENTER</code>. The vertical alignment valus should be one of the
 785:    * constants <code>TOP</code>, <code>BOTTOM</code> or
 786:    * <code>CENTER</code>.</p>
 787:    *
 788:    * <p>If the text and icon are equal to or larger than the view
 789:    * rectangle, the horizontal and vertical alignment values have no
 790:    * affect.</p>
 791:    *
 792:    * <p>Note that this method does <em>not</em> know how to deal with
 793:    * horizontal alignments or positions given as <code>LEADING</code> or
 794:    * <code>TRAILING</code> values. Use the other overloaded variant of this
 795:    * method if you wish to use such values.
 796:    *
 797:    * @param fm The font metrics used to measure the text
 798:    * @param text The text to place in the compound label
 799:    * @param icon The icon to place next to the text
 800:    * @param verticalAlignment The vertical alignment of the label relative
 801:    * to its component
 802:    * @param horizontalAlignment The horizontal alignment of the label
 803:    * relative to its component
 804:    * @param verticalTextPosition The vertical position of the label's text
 805:    * relative to its icon
 806:    * @param horizontalTextPosition The horizontal position of the label's
 807:    * text relative to its icon
 808:    * @param viewR The view rectangle, specifying the area which layout is
 809:    * constrained to
 810:    * @param iconR A rectangle which is modified to hold the laid-out
 811:    * position of the icon
 812:    * @param textR A rectangle which is modified to hold the laid-out
 813:    * position of the text
 814:    * @param textIconGap The distance between text and icon
 815:    *
 816:    * @return The string of characters, possibly truncated with an elipsis,
 817:    * which is laid out in this label
 818:    */
 819: 
 820:   public static String layoutCompoundLabel(FontMetrics fm,
 821:                                            String text,
 822:                                            Icon icon,
 823:                                            int verticalAlignment,
 824:                                            int horizontalAlignment,
 825:                                            int verticalTextPosition,
 826:                                            int horizontalTextPosition,
 827:                                            Rectangle viewR,
 828:                                            Rectangle iconR,
 829:                                            Rectangle textR,
 830:                                            int textIconGap)
 831:   {
 832: 
 833:     // Work out basic height and width.
 834: 
 835:     if (icon == null)
 836:       {
 837:         textIconGap = 0;
 838:         iconR.width = 0;
 839:         iconR.height = 0;
 840:       }
 841:     else
 842:       {
 843:         iconR.width = icon.getIconWidth();
 844:         iconR.height = icon.getIconHeight();
 845:       }
 846:     if (text == null || text.equals(""))
 847:       {
 848:         textIconGap = 0;
 849:     textR.width = 0;
 850:     textR.height = 0;
 851:       }
 852:     else
 853:       {
 854:         int fromIndex = 0;
 855:         textR.width = fm.stringWidth(text);
 856:         textR.height = fm.getHeight(); 
 857:         while (text.indexOf('\n', fromIndex) != -1)
 858:           {
 859:             textR.height += fm.getHeight();
 860:             fromIndex = text.indexOf('\n', fromIndex) + 1;
 861:           }
 862:       }
 863: 
 864:     // Work out the position of text and icon, assuming the top-left coord
 865:     // starts at (0,0). We will fix that up momentarily, after these
 866:     // "position" decisions are made and we look at alignment.
 867: 
 868:     switch (horizontalTextPosition)
 869:       {
 870:       case LEFT:
 871:         textR.x = 0;
 872:         iconR.x = textR.width + textIconGap;
 873:         break;
 874:       case RIGHT:
 875:         iconR.x = 0;
 876:         textR.x = iconR.width + textIconGap;
 877:         break;
 878:       case CENTER:
 879:         int centerLine = Math.max(textR.width, iconR.width) / 2;
 880:         textR.x = centerLine - textR.width/2;
 881:         iconR.x = centerLine - iconR.width/2;
 882:         break;
 883:       }
 884: 
 885:     switch (verticalTextPosition)
 886:       {
 887:       case TOP:
 888:         textR.y = 0;
 889:         iconR.y = (horizontalTextPosition == CENTER 
 890:                    ? textR.height + textIconGap : 0);
 891:         break;
 892:       case BOTTOM:
 893:         iconR.y = 0;
 894:         textR.y = (horizontalTextPosition == CENTER
 895:                    ? iconR.height + textIconGap 
 896:                    : Math.max(iconR.height - textR.height, 0));
 897:         break;
 898:       case CENTER:
 899:         int centerLine = Math.max(textR.height, iconR.height) / 2;
 900:         textR.y = centerLine - textR.height/2;
 901:         iconR.y = centerLine - iconR.height/2;
 902:         break;
 903:       }
 904:     // The two rectangles are laid out correctly now, but only assuming
 905:     // that their upper left corner is at (0,0). If we have any alignment other
 906:     // than TOP and LEFT, we need to adjust them.
 907: 
 908:     Rectangle u = textR.union(iconR);
 909:     int horizontalAdjustment = viewR.x;
 910:     int verticalAdjustment = viewR.y;
 911:     switch (verticalAlignment)
 912:       {
 913:       case TOP:
 914:         break;
 915:       case BOTTOM:
 916:         verticalAdjustment += (viewR.height - u.height);
 917:         break;
 918:       case CENTER:
 919:         verticalAdjustment += ((viewR.height/2) - (u.height/2));
 920:         break;
 921:       }
 922:     switch (horizontalAlignment)
 923:       {
 924:       case LEFT:
 925:         break;
 926:       case RIGHT:
 927:         horizontalAdjustment += (viewR.width - u.width);
 928:         break;
 929:       case CENTER:
 930:         horizontalAdjustment += ((viewR.width/2) - (u.width/2));
 931:         break;
 932:       }
 933: 
 934:     iconR.x += horizontalAdjustment;
 935:     iconR.y += verticalAdjustment;
 936: 
 937:     textR.x += horizontalAdjustment;
 938:     textR.y += verticalAdjustment;
 939: 
 940:     return text;
 941:   }
 942: 
 943:   /** 
 944:    * Calls {@link java.awt.EventQueue#invokeLater} with the
 945:    * specified {@link Runnable}. 
 946:    */
 947:   public static void invokeLater(Runnable doRun)
 948:   {
 949:     java.awt.EventQueue.invokeLater(doRun);
 950:   }
 951: 
 952:   /** 
 953:    * Calls {@link java.awt.EventQueue#invokeAndWait} with the
 954:    * specified {@link Runnable}. 
 955:    */
 956:   public static void invokeAndWait(Runnable doRun)
 957:     throws InterruptedException,
 958:     InvocationTargetException
 959:   {
 960:     java.awt.EventQueue.invokeAndWait(doRun);
 961:   }
 962: 
 963:   /** 
 964:    * Calls {@link java.awt.EventQueue#isDispatchThread()}.
 965:    * 
 966:    * @return <code>true</code> if the current thread is the current AWT event 
 967:    * dispatch thread.
 968:    */
 969:   public static boolean isEventDispatchThread()
 970:   {
 971:     return java.awt.EventQueue.isDispatchThread();
 972:   }
 973:   
 974:   /**
 975:    * This method paints the given component at the given position and size.
 976:    * The component will be reparented to the container given.
 977:    * 
 978:    * @param g The Graphics object to draw with.
 979:    * @param c The Component to draw
 980:    * @param p The Container to reparent to.
 981:    * @param x The x coordinate to draw at.
 982:    * @param y The y coordinate to draw at.
 983:    * @param w The width of the drawing area.
 984:    * @param h The height of the drawing area.
 985:    */
 986:   public static void paintComponent(Graphics g, Component c, Container p, 
 987:                                     int x, int y, int w, int h)
 988:   {       
 989:     Container parent = c.getParent();
 990:     if (parent != null)
 991:       parent.remove(c);
 992:     if (p != null)
 993:       p.add(c);
 994:     
 995:     Shape savedClip = g.getClip();
 996:     
 997:     g.setClip(x, y, w, h);
 998:     g.translate(x, y);
 999: 
1000:     c.paint(g);
1001:     
1002:     g.translate(-x, -y);
1003:     g.setClip(savedClip);
1004:   }
1005: 
1006:   /**
1007:    * This method paints the given component in the given rectangle.
1008:    * The component will be reparented to the container given.
1009:    * 
1010:    * @param g The Graphics object to draw with.
1011:    * @param c The Component to draw
1012:    * @param p The Container to reparent to.
1013:    * @param r The rectangle that describes the drawing area.
1014:    */  
1015:   public static void paintComponent(Graphics g, Component c, 
1016:                                     Container p, Rectangle r)
1017:   {
1018:     paintComponent(g, c, p, r.x, r.y, r.width, r.height);
1019:   }
1020:   
1021:   /**
1022:    * This method returns the common Frame owner used in JDialogs or
1023:    * JWindow when no owner is provided.
1024:    *
1025:    * @return The common Frame 
1026:    */
1027:   static Window getOwnerFrame(Window owner)
1028:   {
1029:     Window result = owner;
1030:     if (result == null)
1031:       {
1032:         if (ownerFrame == null)
1033:           ownerFrame = new OwnerFrame();
1034:         result = ownerFrame;
1035:       }
1036:     return result;
1037:   }
1038: 
1039:   /**
1040:    * Checks if left mouse button was clicked.
1041:    *
1042:    * @param event the event to check
1043:    *
1044:    * @return true if left mouse was clicked, false otherwise.
1045:    */
1046:   public static boolean isLeftMouseButton(MouseEvent event)
1047:   {
1048:     return ((event.getModifiers() & InputEvent.BUTTON1_MASK) != 0);
1049:   }
1050: 
1051:   /**
1052:    * Checks if middle mouse button was clicked.
1053:    *
1054:    * @param event the event to check
1055:    *
1056:    * @return true if middle mouse was clicked, false otherwise.
1057:    */
1058:   public static boolean isMiddleMouseButton(MouseEvent event)
1059:   {
1060:     return ((event.getModifiersEx() & InputEvent.BUTTON2_DOWN_MASK)
1061:          == InputEvent.BUTTON2_DOWN_MASK);
1062:   }
1063: 
1064:   /**
1065:    * Checks if right mouse button was clicked.
1066:    *
1067:    * @param event the event to check
1068:    *
1069:    * @return true if right mouse was clicked, false otherwise.
1070:    */
1071:   public static boolean isRightMouseButton(MouseEvent event)
1072:   {
1073:     return ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK)
1074:          == InputEvent.BUTTON3_DOWN_MASK);
1075:   }
1076:   
1077:   /**
1078:    * This frame should be used when constructing a Window/JDialog without
1079:    * a parent. In this case, we are forced to use this frame as a window's
1080:    * parent, because we simply cannot pass null instead of parent to Window
1081:    * constructor, since doing it will result in NullPointerException.
1082:    */
1083:   private static class OwnerFrame extends Frame
1084:   {
1085:     public void setVisible(boolean b)
1086:     {
1087:       // Do nothing here. 
1088:     }
1089:     
1090:     public boolean isShowing()
1091:     {
1092:       return true;
1093:     }
1094:   }
1095: 
1096:   public static boolean notifyAction(Action action,
1097:                                      KeyStroke ks,
1098:                                      KeyEvent event,
1099:                                      Object sender,
1100:                                      int modifiers)
1101:   {
1102:     if (action != null && action.isEnabled())
1103:       {
1104:         String name = (String) action.getValue(Action.ACTION_COMMAND_KEY);
1105:         if (name == null
1106:             && event.getKeyChar() != KeyEvent.CHAR_UNDEFINED)
1107:           name = new String(new char[] {event.getKeyChar()});
1108:         action.actionPerformed(new ActionEvent(sender,
1109:                                                ActionEvent.ACTION_PERFORMED,
1110:                                                name, modifiers));
1111:         return true;
1112:       }
1113:     return false;
1114:   }
1115: 
1116:   /**
1117:    * <p>Change the shared, UI-managed {@link ActionMap} for a given
1118:    * component. ActionMaps are arranged in a hierarchy, in order to
1119:    * encourage sharing of common actions between components. The hierarchy
1120:    * unfortunately places UI-managed ActionMaps at the <em>end</em> of the
1121:    * parent-pointer chain, as illustrated:</p>
1122:    *
1123:    * <pre>
1124:    *  [{@link javax.swing.JComponent#getActionMap()}] 
1125:    *          --&gt; [{@link javax.swing.ActionMap}] 
1126:    *     parent --&gt; [{@link javax.swing.text.JTextComponent.KeymapActionMap}] 
1127:    *       parent --&gt; [{@link javax.swing.plaf.ActionMapUIResource}]
1128:    * </pre>
1129:    *
1130:    * <p>Our goal with this method is to replace the first ActionMap along
1131:    * this chain which is an instance of {@link ActionMapUIResource}, since
1132:    * these are the ActionMaps which are supposed to be shared between
1133:    * components.</p>
1134:    *
1135:    * <p>If the provided ActionMap is <code>null</code>, we interpret the
1136:    * call as a request to remove the UI-managed ActionMap from the
1137:    * component's ActionMap parent chain.</p>
1138:    */
1139:   public static void replaceUIActionMap(JComponent component, 
1140:                                         ActionMap uiActionMap)
1141:   {
1142:     ActionMap child = component.getActionMap();
1143:     if (child == null)
1144:       component.setActionMap(uiActionMap);
1145:     else
1146:       {
1147:         ActionMap parent = child.getParent();
1148:         while (parent != null && !(parent instanceof ActionMapUIResource))
1149:           {
1150:             child = parent;
1151:             parent = child.getParent();
1152:           }
1153:         // Sanity check to avoid loops.
1154:         if (child != uiActionMap)
1155:           child.setParent(uiActionMap);
1156:       }
1157:   }
1158: 
1159:   /**
1160:    * <p>Change the shared, UI-managed {@link InputMap} for a given
1161:    * component. InputMaps are arranged in a hierarchy, in order to
1162:    * encourage sharing of common input mappings between components. The
1163:    * hierarchy unfortunately places UI-managed InputMaps at the
1164:    * <em>end</em> of the parent-pointer chain, as illustrated:</p>
1165:    *
1166:    * <pre>
1167:    *  [{@link javax.swing.JComponent#getInputMap()}] 
1168:    *          --&gt; [{@link javax.swing.InputMap}] 
1169:    *     parent --&gt; [{@link javax.swing.text.JTextComponent.KeymapWrapper}] 
1170:    *       parent --&gt; [{@link javax.swing.plaf.InputMapUIResource}]
1171:    * </pre>
1172:    *
1173:    * <p>Our goal with this method is to replace the first InputMap along
1174:    * this chain which is an instance of {@link InputMapUIResource}, since
1175:    * these are the InputMaps which are supposed to be shared between
1176:    * components.</p>
1177:    *
1178:    * <p>If the provided InputMap is <code>null</code>, we interpret the
1179:    * call as a request to remove the UI-managed InputMap from the
1180:    * component's InputMap parent chain.</p>
1181:    */
1182:   public static void replaceUIInputMap(JComponent component, 
1183:                                        int condition, 
1184:                                        InputMap uiInputMap)
1185:   {
1186:     InputMap child = component.getInputMap(condition);
1187:     if (child == null)
1188:       component.setInputMap(condition, uiInputMap);
1189:     else
1190:       {
1191:         InputMap parent = child.getParent();
1192:         while (parent != null && !(parent instanceof InputMapUIResource))
1193:           {
1194:             child = parent;
1195:             parent = parent.getParent();
1196:           }
1197:         // Sanity check to avoid loops.
1198:         if (child != uiInputMap)
1199:           child.setParent(uiInputMap);
1200:       }
1201:   }
1202: 
1203:   /**
1204:    * Subtracts a rectangle from another and return the area as an array
1205:    * of rectangles.
1206:    * Returns the areas of rectA which are not covered by rectB.
1207:    * If the rectangles do not overlap, or if either parameter is
1208:    * <code>null</code>, a zero-size array is returned.
1209:    * @param rectA The first rectangle
1210:    * @param rectB The rectangle to subtract from the first
1211:    * @return An array of rectangles representing the area in rectA
1212:    * not overlapped by rectB
1213:    */
1214:   public static Rectangle[] computeDifference(Rectangle rectA, Rectangle rectB)
1215:   {
1216:     if (rectA == null || rectB == null)
1217:       return new Rectangle[0];
1218: 
1219:     Rectangle[] r = new Rectangle[4];
1220:     int x1 = rectA.x;
1221:     int y1 = rectA.y;
1222:     int w1 = rectA.width;
1223:     int h1 = rectA.height;
1224:     int x2 = rectB.x;
1225:     int y2 = rectB.y;
1226:     int w2 = rectB.width;
1227:     int h2 = rectB.height;
1228: 
1229:     // (outer box = rectA)
1230:     // ------------- 
1231:     // |_____0_____|
1232:     // |  |rectB|  |
1233:     // |_1|_____|_2|
1234:     // |     3     |
1235:     // -------------
1236:     int H0 = (y2 > y1) ? y2 - y1 : 0; // height of box 0
1237:     int H3 = (y2 + h2 < y1 + h1) ? y1 + h1 - y2 - h2 : 0; // height box 3
1238:     int W1 = (x2 > x1) ? x2 - x1 : 0; // width box 1
1239:     int W2 = (x1 + w1 > x2 + w2) ? x1 + w1 - x2 - w2 : 0; // w. box 2
1240:     int H12 = (H0 + H3 < h1) ? h1 - H0 - H3 : 0; // height box 1 & 2
1241: 
1242:     if (H0 > 0)
1243:       r[0] = new Rectangle(x1, y1, w1, H0);
1244:     else
1245:       r[0] = null;
1246: 
1247:     if (W1 > 0 && H12 > 0)
1248:       r[1] = new Rectangle(x1, y1 + H0, W1, H12);
1249:     else
1250:       r[1] = null;
1251: 
1252:     if (W2 > 0 && H12 > 0)
1253:       r[2] = new Rectangle(x2 + w2, y1 + H0, W2, H12);
1254:     else
1255:       r[2] = null;
1256: 
1257:     if (H3 > 0)
1258:       r[3] = new Rectangle(x1, y1 + H0 + H12, w1, H3);
1259:     else
1260:       r[3] = null;
1261: 
1262:     // sort out null objects
1263:     int n = 0;
1264:     for (int i = 0; i < 4; i++)
1265:       if (r[i] != null)
1266:     n++;
1267:     Rectangle[] out = new Rectangle[n];
1268:     for (int i = 3; i >= 0; i--)
1269:       if (r[i] != null)
1270:     out[--n] = r[i];
1271: 
1272:     return out;
1273:   }
1274: 
1275:   /**
1276:    * Calculates the intersection of two rectangles. The result is stored
1277:    * in <code>rect</code>. This is basically the same
1278:    * like {@link Rectangle#intersection(Rectangle)}, only that it does not
1279:    * create new Rectangle instances. The tradeoff is that you loose any data in
1280:    * <code>rect</code>.
1281:    *
1282:    * @param x upper-left x coodinate of first rectangle
1283:    * @param y upper-left y coodinate of first rectangle
1284:    * @param w width of first rectangle
1285:    * @param h height of first rectangle
1286:    * @param rect a Rectangle object of the second rectangle
1287:    *
1288:    * @throws NullPointerException if rect is null
1289:    *
1290:    * @return a rectangle corresponding to the intersection of the
1291:    *         two rectangles. An empty rectangle is returned if the rectangles
1292:    *         do not overlap
1293:    */
1294:   public static Rectangle computeIntersection(int x, int y, int w, int h,
1295:                                               Rectangle rect)
1296:   {
1297:     int x2 = (int) rect.x;
1298:     int y2 = (int) rect.y;
1299:     int w2 = (int) rect.width;
1300:     int h2 = (int) rect.height;
1301: 
1302:     int dx = (x > x2) ? x : x2;
1303:     int dy = (y > y2) ? y : y2;
1304:     int dw = (x + w < x2 + w2) ? (x + w - dx) : (x2 + w2 - dx);
1305:     int dh = (y + h < y2 + h2) ? (y + h - dy) : (y2 + h2 - dy);
1306: 
1307:     if (dw >= 0 && dh >= 0)
1308:       rect.setBounds(dx, dy, dw, dh);
1309:     else
1310:       rect.setBounds(0, 0, 0, 0);
1311: 
1312:     return rect;
1313:   }
1314:   
1315:   /**
1316:    * Calculates the width of a given string.
1317:    *
1318:    * @param fm the <code>FontMetrics</code> object to use
1319:    * @param str the string
1320:    * 
1321:    * @return the width of the the string.
1322:    */
1323:   public static int computeStringWidth(FontMetrics fm, String str)
1324:   {
1325:     return fm.stringWidth(str);
1326:   }
1327: 
1328:   /**
1329:    * Calculates the union of two rectangles. The result is stored in
1330:    * <code>rect</code>. This is basically the same as
1331:    * {@link Rectangle#union(Rectangle)} except that it avoids creation of new
1332:    * Rectangle objects. The tradeoff is that you loose any data in
1333:    * <code>rect</code>.
1334:    *
1335:    * @param x upper-left x coodinate of first rectangle
1336:    * @param y upper-left y coodinate of first rectangle
1337:    * @param w width of first rectangle
1338:    * @param h height of first rectangle
1339:    * @param rect a Rectangle object of the second rectangle
1340:    *
1341:    * @throws NullPointerException if rect is null
1342:    *
1343:    * @return a rectangle corresponding to the union of the
1344:    *         two rectangles; a rectangle encompassing both is returned if the
1345:    *         rectangles do not overlap
1346:    */
1347:   public static Rectangle computeUnion(int x, int y, int w, int h,
1348:                                        Rectangle rect)
1349:   {
1350:     int x2 = (int) rect.x;
1351:     int y2 = (int) rect.y;
1352:     int w2 = (int) rect.width;
1353:     int h2 = (int) rect.height;
1354: 
1355:     int dx = (x < x2) ? x : x2;
1356:     int dy = (y < y2) ? y : y2;
1357:     int dw = (x + w > x2 + w2) ? (x + w - dx) : (x2 + w2 - dx);
1358:     int dh = (y + h > y2 + h2) ? (y + h - dy) : (y2 + h2 - dy);
1359: 
1360:     if (dw >= 0 && dh >= 0)
1361:       rect.setBounds(dx, dy, dw, dh);
1362:     else
1363:       rect.setBounds(0, 0, 0, 0);
1364:     return rect;
1365:   }
1366: 
1367:   /**
1368:    * Tests if a rectangle contains another.
1369:    * @param a first rectangle
1370:    * @param b second rectangle
1371:    * @return true if a contains b, false otherwise
1372:    * @throws NullPointerException
1373:    */
1374:   public static boolean isRectangleContainingRectangle(Rectangle a, Rectangle b)
1375:   {
1376:     // Note: zero-size rects inclusive, differs from Rectangle.contains()
1377:     return b.width >= 0 && b.height >= 0 && b.width >= 0 && b.height >= 0
1378:            && b.x >= a.x && b.x + b.width <= a.x + a.width && b.y >= a.y
1379:            && b.y + b.height <= a.y + a.height;
1380:   }
1381: 
1382:   /**
1383:    * Returns the InputMap that is provided by the ComponentUI of
1384:    * <code>component</code> for the specified condition.
1385:    *
1386:    * @param component the component for which the InputMap is returned
1387:    * @param cond the condition that specifies which of the three input
1388:    *     maps should be returned, may be
1389:    *     {@link JComponent#WHEN_IN_FOCUSED_WINDOW},
1390:    *     {@link JComponent#WHEN_FOCUSED} or
1391:    *     {@link JComponent#WHEN_ANCESTOR_OF_FOCUSED_COMPONENT}
1392:    *
1393:    * @return The input map.
1394:    */
1395:   public static InputMap getUIInputMap(JComponent component, int cond)
1396:   {
1397:     if (UIManager.getUI(component) != null)
1398:       // we assume here that the UI class sets the parent of the component's
1399:       // InputMap, which is the correct behaviour. If it's not, then
1400:       // this can be considered a bug
1401:       return component.getInputMap(cond).getParent();
1402:     else
1403:       return null;
1404:   }
1405: 
1406:   /**
1407:    * Returns the ActionMap that is provided by the ComponentUI of
1408:    * <code>component</code>.
1409:    *
1410:    * @param component the component for which the ActionMap is returned
1411:    */
1412:   public static ActionMap getUIActionMap(JComponent component)
1413:   {
1414:     if (UIManager.getUI(component) != null)
1415:       // we assume here that the UI class sets the parent of the component's
1416:       // ActionMap, which is the correct behaviour. If it's not, then
1417:       // this can be considered a bug
1418:       return component.getActionMap().getParent();
1419:     else
1420:       return null;
1421:   }
1422: 
1423:   /**
1424:    * Processes key bindings for the component that is associated with the 
1425:    * key event. Note that this method does not make sense for
1426:    * JComponent-derived components, except when
1427:    * {@link JComponent#processKeyEvent(KeyEvent)} is overridden and super is
1428:    * not called.
1429:    *
1430:    * This method searches through the component hierarchy of the component's
1431:    * top-level container to find a <code>JComponent</code> that has a binding
1432:    * for the key event in the WHEN_IN_FOCUSED_WINDOW scope.
1433:    *
1434:    * @param ev the key event
1435:    *
1436:    * @return <code>true</code> if a binding has been found and processed,
1437:    *         <code>false</code> otherwise
1438:    *
1439:    * @since 1.4
1440:    */
1441:   public static boolean processKeyBindings(KeyEvent ev)
1442:   {
1443:     Component c = ev.getComponent();
1444:     KeyStroke s = KeyStroke.getKeyStrokeForEvent(ev);
1445:     KeyboardManager km = KeyboardManager.getManager();
1446:     return km.processKeyStroke(c, s, ev);
1447:   }
1448:   
1449:   /**
1450:    * Returns a string representing one of the horizontal alignment codes
1451:    * defined in the {@link SwingConstants} interface.  The following table
1452:    * lists the constants and return values:
1453:    * <p>
1454:    * <table border="0">
1455:    * <tr>
1456:    *   <th>Code:</th><th>Returned String:</th>
1457:    * </tr>
1458:    * <tr>
1459:    *   <td>{@link SwingConstants#CENTER}</td>
1460:    *   <td><code>"CENTER"</code></td>
1461:    * </tr>
1462:    * <tr>
1463:    *   <td>{@link SwingConstants#LEFT}</td>
1464:    *   <td><code>"LEFT"</code></td>
1465:    * </tr>
1466:    * <tr>
1467:    *   <td>{@link SwingConstants#RIGHT}</td>
1468:    *   <td><code>"RIGHT"</code></td>
1469:    * </tr>
1470:    * <tr>
1471:    *   <td>{@link SwingConstants#LEADING}</td>
1472:    *   <td><code>"LEADING"</code></td>
1473:    * </tr>
1474:    * <tr>
1475:    *   <td>{@link SwingConstants#TRAILING}</td>
1476:    *   <td><code>"TRAILING"</code></td>
1477:    * </tr>
1478:    * </table>
1479:    * </p>
1480:    * If the supplied code is not one of those listed, this methods will throw
1481:    * an {@link IllegalArgumentException}.
1482:    * 
1483:    * @param code  the code.
1484:    * 
1485:    * @return A string representing the given code.
1486:    */
1487:   static String convertHorizontalAlignmentCodeToString(int code)
1488:   {
1489:     switch (code) 
1490:     {
1491:       case SwingConstants.CENTER: 
1492:         return "CENTER";
1493:       case SwingConstants.LEFT:
1494:         return "LEFT";
1495:       case SwingConstants.RIGHT:
1496:         return "RIGHT";
1497:       case SwingConstants.LEADING:
1498:         return "LEADING";
1499:       case SwingConstants.TRAILING:
1500:         return "TRAILING";
1501:       default:
1502:         throw new IllegalArgumentException("Unrecognised code: " + code);
1503:     }
1504:   }
1505:   
1506:   /**
1507:    * Returns a string representing one of the vertical alignment codes
1508:    * defined in the {@link SwingConstants} interface.  The following table
1509:    * lists the constants and return values:
1510:    * <p>
1511:    * <table border="0">
1512:    * <tr>
1513:    *   <th>Code:</th><th>Returned String:</th>
1514:    * </tr>
1515:    * <tr>
1516:    *   <td>{@link SwingConstants#CENTER}</td>
1517:    *   <td><code>"CENTER"</code></td>
1518:    * </tr>
1519:    * <tr>
1520:    *   <td>{@link SwingConstants#TOP}</td>
1521:    *   <td><code>"TOP"</code></td>
1522:    * </tr>
1523:    * <tr>
1524:    *   <td>{@link SwingConstants#BOTTOM}</td>
1525:    *   <td><code>"BOTTOM"</code></td>
1526:    * </tr>
1527:    * </table>
1528:    * </p>
1529:    * If the supplied code is not one of those listed, this methods will throw
1530:    * an {@link IllegalArgumentException}.
1531:    * 
1532:    * @param code  the code.
1533:    * 
1534:    * @return A string representing the given code.
1535:    */
1536:   static String convertVerticalAlignmentCodeToString(int code)
1537:   {
1538:     switch (code)
1539:     {
1540:       case SwingConstants.CENTER:
1541:         return "CENTER";
1542:       case SwingConstants.TOP:
1543:         return "TOP";
1544:       case SwingConstants.BOTTOM:
1545:         return "BOTTOM";
1546:       default:
1547:         throw new IllegalArgumentException("Unrecognised code: " + code);
1548:     }
1549:   }
1550:   
1551:   /**
1552:    * Returns a string representing one of the default operation codes
1553:    * defined in the {@link WindowConstants} interface.  The following table
1554:    * lists the constants and return values:
1555:    * <p>
1556:    * <table border="0">
1557:    * <tr>
1558:    *   <th>Code:</th><th>Returned String:</th>
1559:    * </tr>
1560:    * <tr>
1561:    *   <td>{@link WindowConstants#DO_NOTHING_ON_CLOSE}</td>
1562:    *   <td><code>"DO_NOTHING_ON_CLOSE"</code></td>
1563:    * </tr>
1564:    * <tr>
1565:    *   <td>{@link WindowConstants#HIDE_ON_CLOSE}</td>
1566:    *   <td><code>"HIDE_ON_CLOSE"</code></td>
1567:    * </tr>
1568:    * <tr>
1569:    *   <td>{@link WindowConstants#DISPOSE_ON_CLOSE}</td>
1570:    *   <td><code>"DISPOSE_ON_CLOSE"</code></td>
1571:    * </tr>
1572:    * <tr>
1573:    *   <td>{@link WindowConstants#EXIT_ON_CLOSE}</td>
1574:    *   <td><code>"EXIT_ON_CLOSE"</code></td>
1575:    * </tr>
1576:    * </table>
1577:    * </p>
1578:    * If the supplied code is not one of those listed, this method will throw
1579:    * an {@link IllegalArgumentException}.
1580:    * 
1581:    * @param code  the code.
1582:    * 
1583:    * @return A string representing the given code.
1584:    */
1585:   static String convertWindowConstantToString(int code) 
1586:   {
1587:     switch (code)
1588:     {
1589:       case WindowConstants.DO_NOTHING_ON_CLOSE:
1590:         return "DO_NOTHING_ON_CLOSE";
1591:       case WindowConstants.HIDE_ON_CLOSE:
1592:         return "HIDE_ON_CLOSE";
1593:       case WindowConstants.DISPOSE_ON_CLOSE:
1594:         return "DISPOSE_ON_CLOSE";
1595:       case WindowConstants.EXIT_ON_CLOSE:
1596:         return "EXIT_ON_CLOSE";
1597:       default:
1598:         throw new IllegalArgumentException("Unrecognised code: " + code);
1599:     }
1600:   }
1601: 
1602:   /**
1603:    * Converts a rectangle in the coordinate system of a child component into
1604:    * a rectangle of one of it's Ancestors. The result is stored in the input
1605:    * rectangle.
1606:    *
1607:    * @param comp the child component
1608:    * @param r the rectangle to convert
1609:    * @param ancestor the ancestor component
1610:    */
1611:   static void convertRectangleToAncestor(Component comp, Rectangle r,
1612:                                          Component ancestor)
1613:   {
1614:     if (comp == ancestor)
1615:       return;
1616: 
1617:     r.x += comp.getX();
1618:     r.y += comp.getY();
1619: 
1620:     Component parent = comp.getParent();
1621:     if (parent != null && parent != ancestor)
1622:       convertRectangleToAncestor(parent, r, ancestor);
1623:   }
1624: }