JComponent.java 115 KB
Newer Older
Tom Tromey committed
1
/* JComponent.java -- Every component in swing inherits from this class.
2
   Copyright (C) 2002, 2004, 2005, 2006,  Free Software Foundation, Inc.
Tom Tromey committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package javax.swing;

41 42
import gnu.java.lang.CPStringBuilder;

Tom Tromey committed
43
import java.applet.Applet;
Tom Tromey committed
44 45 46 47 48
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
49
import java.awt.EventQueue;
Tom Tromey committed
50
import java.awt.FocusTraversalPolicy;
Tom Tromey committed
51 52 53 54 55 56
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
Tom Tromey committed
57
import java.awt.Window;
Tom Tromey committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71
import java.awt.dnd.DropTarget;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.peer.LightweightPeer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
72
import java.beans.VetoableChangeSupport;
Tom Tromey committed
73
import java.io.Serializable;
74
import java.util.ArrayList;
Tom Tromey committed
75 76 77
import java.util.EventListener;
import java.util.Hashtable;
import java.util.Locale;
Tom Tromey committed
78
import java.util.Set;
Tom Tromey committed
79 80 81 82 83 84

import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleExtendedComponent;
import javax.accessibility.AccessibleKeyBinding;
import javax.accessibility.AccessibleRole;
85
import javax.accessibility.AccessibleState;
Tom Tromey committed
86 87
import javax.accessibility.AccessibleStateSet;
import javax.swing.border.Border;
88 89
import javax.swing.border.CompoundBorder;
import javax.swing.border.TitledBorder;
Tom Tromey committed
90 91 92 93 94 95
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.event.EventListenerList;
import javax.swing.plaf.ComponentUI;

/**
Tom Tromey committed
96
 * The base class of all Swing components.
Tom Tromey committed
97 98 99 100 101 102 103 104 105 106 107 108
 * It contains generic methods to manage events, properties and sizes. Actual
 * drawing of the component is channeled to a look-and-feel class that is
 * implemented elsewhere.
 *
 * @author Ronald Veldema (rveldema&064;cs.vu.nl)
 * @author Graydon Hoare (graydon&064;redhat.com)
 */
public abstract class JComponent extends Container implements Serializable
{
  private static final long serialVersionUID = -7908749299918704233L;

  /** 
109
   * The accessible context of this <code>JComponent</code>.
Tom Tromey committed
110 111 112
   */
  protected AccessibleContext accessibleContext;

Tom Tromey committed
113 114 115 116
  /**
   * Basic accessibility support for <code>JComponent</code> derived
   * widgets.
   */
Tom Tromey committed
117 118 119 120
  public abstract class AccessibleJComponent 
    extends AccessibleAWTContainer
    implements AccessibleExtendedComponent
  {
Tom Tromey committed
121
    /**
122 123 124
     * Receives notification if the focus on the JComponent changes and
     * fires appropriate PropertyChangeEvents to listeners registered with
     * the AccessibleJComponent.
Tom Tromey committed
125
     */
Tom Tromey committed
126 127 128
    protected class AccessibleFocusHandler 
      implements FocusListener
    {
129 130 131
      /**
       * Creates a new AccessibleFocusHandler.
       */
132 133
      protected AccessibleFocusHandler()
      {
134
        // Nothing to do here.
135
      }
136 137 138 139 140 141 142 143

      /**
       * Receives notification when the JComponent gained focus and fires
       * a PropertyChangeEvent to listeners registered on the
       * AccessibleJComponent with a property name of
       * {@link AccessibleContext#ACCESSIBLE_STATE_PROPERTY} and a new value
       * of {@link AccessibleState#FOCUSED}.
       */
144 145
      public void focusGained(FocusEvent event)
      {
146 147 148
        AccessibleJComponent.this.firePropertyChange
          (AccessibleContext.ACCESSIBLE_STATE_PROPERTY, null,
           AccessibleState.FOCUSED);
149
      }
150 151 152 153 154 155 156 157

      /**
       * Receives notification when the JComponent lost focus and fires
       * a PropertyChangeEvent to listeners registered on the
       * AccessibleJComponent with a property name of
       * {@link AccessibleContext#ACCESSIBLE_STATE_PROPERTY} and an old value
       * of {@link AccessibleState#FOCUSED}.
       */
158 159
      public void focusLost(FocusEvent valevent)
      {
160 161 162
        AccessibleJComponent.this.firePropertyChange
          (AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
           AccessibleState.FOCUSED, null);
163
      }
Tom Tromey committed
164 165
    }

Tom Tromey committed
166
    /**
167 168 169
     * Receives notification if there are child components are added or removed
     * from the JComponent and fires appropriate PropertyChangeEvents to
     * interested listeners on the AccessibleJComponent.
Tom Tromey committed
170
     */
Tom Tromey committed
171 172 173
    protected class AccessibleContainerHandler 
      implements ContainerListener
    {
174 175 176
      /**
       * Creates a new AccessibleContainerHandler.
       */
177 178
      protected AccessibleContainerHandler()
      {
179
        // Nothing to do here.
180
      }
181 182 183 184 185 186 187 188 189

      /**
       * Receives notification when a child component is added to the
       * JComponent and fires a PropertyChangeEvent on listeners registered
       * with the AccessibleJComponent with a property name of
       * {@link AccessibleContext#ACCESSIBLE_CHILD_PROPERTY}.
       *
       * @param event the container event
       */
190 191
      public void componentAdded(ContainerEvent event)
      {
192 193 194 195 196 197 198
        Component c = event.getChild();
        if (c != null && c instanceof Accessible)
          {
            AccessibleContext childCtx = c.getAccessibleContext();
            AccessibleJComponent.this.firePropertyChange
              (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, null, childCtx);
          }
199
      }
200 201 202 203 204 205 206 207 208 209

      /**
       * Receives notification when a child component is removed from the
       * JComponent and fires a PropertyChangeEvent on listeners registered
       * with the AccessibleJComponent with a property name of
       * {@link AccessibleContext#ACCESSIBLE_CHILD_PROPERTY}.
       *
       * @param event the container event
       */
      public void componentRemoved(ContainerEvent event)
210
      {
211 212 213 214 215 216 217
        Component c = event.getChild();
        if (c != null && c instanceof Accessible)
          {
            AccessibleContext childCtx = c.getAccessibleContext();
            AccessibleJComponent.this.firePropertyChange
              (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY, childCtx, null);
          }
218
      }
Tom Tromey committed
219 220 221
    }

    private static final long serialVersionUID = -7047089700479897799L;
222 223 224 225 226 227 228 229 230

    /**
     * Receives notification when a child component is added to the
     * JComponent and fires a PropertyChangeEvent on listeners registered
     * with the AccessibleJComponent.
     *
     * @specnote AccessibleAWTContainer has a protected field with the same
     *           name. Looks like a bug or nasty misdesign to me.
     */
Tom Tromey committed
231 232
    protected ContainerListener accessibleContainerHandler;

233
    /**
234 235 236 237 238 239 240
     * Receives notification if the focus on the JComponent changes and
     * fires appropriate PropertyChangeEvents to listeners registered with
     * the AccessibleJComponent.
     *
     * @specnote AccessibleAWTComponent has a protected field
     *           accessibleAWTFocusHandler. Looks like a bug or nasty misdesign
     *           to me.
241
     */
242
    protected FocusListener accessibleFocusHandler;
243

244 245 246
    /**
     * Creates a new AccessibleJComponent.
     */
247 248
    protected AccessibleJComponent()
    {
249
      // Nothing to do here.
250 251 252 253 254
    }

    /**
     * Adds a property change listener to the list of registered listeners.
     *
255 256 257 258
     * This sets up the {@link #accessibleContainerHandler} and
     * {@link #accessibleFocusHandler} fields and calls
     * <code>super.addPropertyChangeListener(listener)</code>.
     *
259 260 261 262
     * @param listener the listener to add
     */
    public void addPropertyChangeListener(PropertyChangeListener listener)
    {
263 264 265 266 267 268 269 270 271 272 273 274 275
      // Tests seem to indicate that this method also sets up the other two
      // handlers.
      if (accessibleContainerHandler == null)
        {
          accessibleContainerHandler = new AccessibleContainerHandler();
          addContainerListener(accessibleContainerHandler);
        }
      if (accessibleFocusHandler == null)
        {
          accessibleFocusHandler = new AccessibleFocusHandler();
          addFocusListener(accessibleFocusHandler);
        }
      super.addPropertyChangeListener(listener);
276 277 278
    }

    /**
279 280 281 282 283
     * Removes a property change listener from the list of registered listeners.
     *
     * This uninstalls the {@link #accessibleContainerHandler} and
     * {@link #accessibleFocusHandler} fields and calls
     * <code>super.removePropertyChangeListener(listener)</code>.
284 285 286 287 288
     *
     * @param listener the listener to remove
     */
    public void removePropertyChangeListener(PropertyChangeListener listener)
    {
289 290 291 292 293 294 295 296 297 298 299 300 301
      // Tests seem to indicate that this method also resets the other two
      // handlers.
      if (accessibleContainerHandler != null)
        {
          removeContainerListener(accessibleContainerHandler);
          accessibleContainerHandler = null;
        }
      if (accessibleFocusHandler != null)
        {
          removeFocusListener(accessibleFocusHandler);
          accessibleFocusHandler = null;
        }
      super.removePropertyChangeListener(listener);
302 303 304 305 306 307 308 309 310
    }

    /**
     * Returns the number of accessible children of this object.
     *
     * @return  the number of accessible children of this object
     */
    public int getAccessibleChildrenCount()
    {
311 312 313 314 315
      // TODO: The functionality should be performed in the superclass.
      // Find out why this is overridden. However, it is very well possible
      // that this is left over from times when there was no such superclass
      // method.
      return super.getAccessibleChildrenCount();
316 317 318 319 320 321 322 323 324 325 326
    }

    /**
     * Returns the accessible child component at index <code>i</code>.
     *
     * @param i the index of the accessible child to return
     *
     * @return the accessible child component at index <code>i</code>
     */
    public Accessible getAccessibleChild(int i)
    {
327 328 329 330 331
      // TODO: The functionality should be performed in the superclass.
      // Find out why this is overridden. However, it is very well possible
      // that this is left over from times when there was no such superclass
      // method.
      return super.getAccessibleChild(i);
332 333 334 335 336 337 338 339 340
    }

    /**
     * Returns the accessible state set of this component.
     *
     * @return the accessible state set of this component
     */
    public AccessibleStateSet getAccessibleStateSet()
    {
341 342 343 344 345 346 347 348
      // Note: While the java.awt.Component has an 'opaque' property, it
      // seems that it is not added to the accessible state set there, even
      // if this property is true. However, it is handled for JComponent, so
      // we add it here.
      AccessibleStateSet state = super.getAccessibleStateSet();
      if (isOpaque())
        state.add(AccessibleState.OPAQUE);
      return state;
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    }

    /**
     * Returns the localized name for this object. Generally this should
     * almost never return {@link Component#getName()} since that is not
     * a localized name. If the object is some kind of text component (like
     * a menu item), then the value of the object may be returned. Also, if
     * the object has a tooltip, the value of the tooltip may also be
     * appropriate.
     *
     * @return the localized name for this object or <code>null</code> if this
     *         object has no name
     */
    public String getAccessibleName()
    {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
      String name = super.getAccessibleName();

      // There are two fallbacks provided by the JComponent in the case the
      // superclass returns null:
      // - If the component is inside a titled border, then it inherits the
      //   name from the border title.
      // - If the component is not inside a titled border but has a label
      //   (via JLabel.setLabelFor()), then it gets the name from the label's
      //   accessible context.

      if (name == null)
        {
          name = getTitledBorderText();
        }

      if (name == null)
        {
          Object l = getClientProperty(JLabel.LABEL_PROPERTY);
          if (l instanceof Accessible)
            {
              AccessibleContext labelCtx =
                ((Accessible) l).getAccessibleContext();
              name = labelCtx.getAccessibleName();
            }
        }

      return name;
391 392 393 394 395 396 397 398 399 400
    }

    /**
     * Returns the localized description of this object.
     *
     * @return the localized description of this object or <code>null</code>
     *         if this object has no description
     */
    public String getAccessibleDescription()
    {
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
      // There are two fallbacks provided by the JComponent in the case the
      // superclass returns null:
      // - If the component has a tooltip, then inherit the description from
      //   the tooltip.
      // - If the component is not inside a titled border but has a label
      //   (via JLabel.setLabelFor()), then it gets the name from the label's
      //   accessible context.
      String descr = super.getAccessibleDescription();

      if (descr == null)
        {
          descr = getToolTipText();
        }

      if (descr == null)
        {
          Object l = getClientProperty(JLabel.LABEL_PROPERTY);
          if (l instanceof Accessible)
            {
              AccessibleContext labelCtx =
                ((Accessible) l).getAccessibleContext();
              descr = labelCtx.getAccessibleName();
            }
        }

      return descr;
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    }

    /**
     * Returns the accessible role of this component.
     *
     * @return the accessible role of this component
     *
     * @see AccessibleRole
     */
    public AccessibleRole getAccessibleRole()
    {
      return AccessibleRole.SWING_COMPONENT;
    }

    /**
     * Recursivly searches a border hierarchy (starting at <code>border) for
     * a titled border and returns the title if one is found, <code>null</code>
     * otherwise.
     *
     * @param border the border to start search from
     *
     * @return the border title of a possibly found titled border
     */
    protected String getBorderTitle(Border border)
    {
      String title = null;
      if (border instanceof CompoundBorder)
        {
          CompoundBorder compound = (CompoundBorder) border;
          Border inner = compound.getInsideBorder();
          title = getBorderTitle(inner);
          if (title == null)
            {
              Border outer = compound.getOutsideBorder();
              title = getBorderTitle(outer);
            }
        }
      else if (border instanceof TitledBorder)
        {
          TitledBorder titled = (TitledBorder) border;
          title = titled.getTitle(); 
        }
      return title;
    }

    /**
     * Returns the tooltip text for this accessible component.
     *
     * @return the tooltip text for this accessible component
     */
    public String getToolTipText()
    {
      return JComponent.this.getToolTipText();
    }

    /**
     * Returns the title of the border of this accessible component if
     * this component has a titled border, otherwise returns <code>null</code>.
     *
     * @return the title of the border of this accessible component if
     *         this component has a titled border, otherwise returns
     *         <code>null</code>
     */
    public String getTitledBorderText()
    {
      return getBorderTitle(getBorder()); 
    }

    /**
     * Returns the keybindings associated with this accessible component or
     * <code>null</code> if the component does not support key bindings.
     *
     * @return the keybindings associated with this accessible component
     */
    public AccessibleKeyBinding getAccessibleKeyBinding()
    {
503 504
      // The reference implementation seems to always return null here,
      // independent of the key bindings of the JComponent. So do we.
505 506
      return null;
    }
Tom Tromey committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
  }

  /**
   * A value between 0.0 and 1.0 indicating the preferred horizontal
   * alignment of the component, relative to its siblings. The values
   * {@link #LEFT_ALIGNMENT}, {@link #CENTER_ALIGNMENT}, and {@link
   * #RIGHT_ALIGNMENT} can also be used, as synonyms for <code>0.0</code>,
   * <code>0.5</code>, and <code>1.0</code>, respectively. Not all layout
   * managers use this property.
   *
   * @see #getAlignmentX
   * @see #setAlignmentX
   * @see javax.swing.OverlayLayout
   * @see javax.swing.BoxLayout
   */
522
  float alignmentX = -1.0F;
Tom Tromey committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536

  /**
   * A value between 0.0 and 1.0 indicating the preferred vertical
   * alignment of the component, relative to its siblings. The values
   * {@link #TOP_ALIGNMENT}, {@link #CENTER_ALIGNMENT}, and {@link
   * #BOTTOM_ALIGNMENT} can also be used, as synonyms for <code>0.0</code>,
   * <code>0.5</code>, and <code>1.0</code>, respectively. Not all layout
   * managers use this property.
   *
   * @see #getAlignmentY
   * @see #setAlignmentY
   * @see javax.swing.OverlayLayout
   * @see javax.swing.BoxLayout
   */
537
  float alignmentY = -1.0F;
Tom Tromey committed
538 539 540 541 542 543 544 545

  /** 
   * The border painted around this component.
   * 
   * @see #paintBorder
   */
  Border border;

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
  /**
   * The popup menu for the component.
   * 
   * @see #getComponentPopupMenu()
   * @see #setComponentPopupMenu(JPopupMenu)
   */
  JPopupMenu componentPopupMenu;
   
  /**
   * A flag that controls whether the {@link #getComponentPopupMenu()} method
   * looks to the component's parent when the <code>componentPopupMenu</code>
   * field is <code>null</code>.
   */
  boolean inheritsPopupMenu;
  
Tom Tromey committed
561 562
  /** 
   * <p>Whether to double buffer this component when painting. This flag
563 564
   * should generally be <code>true</code>, to ensure good painting
   * performance.</p>
Tom Tromey committed
565 566 567 568 569 570 571 572 573
   *
   * <p>All children of a double buffered component are painted into the
   * double buffer automatically, so only the top widget in a window needs
   * to be double buffered.</p>
   *
   * @see #setDoubleBuffered
   * @see #isDoubleBuffered
   * @see #paint
   */
574
  boolean doubleBuffered = true;
Tom Tromey committed
575 576 577 578

  /**
   * A set of flags indicating which debugging graphics facilities should
   * be enabled on this component. The values should be a combination of
579 580 581
   * {@link DebugGraphics#NONE_OPTION}, {@link DebugGraphics#LOG_OPTION},
   * {@link DebugGraphics#FLASH_OPTION}, or {@link
   * DebugGraphics#BUFFERED_OPTION}.
Tom Tromey committed
582
   *
583 584
   * @see #setDebugGraphicsOptions
   * @see #getDebugGraphicsOptions
Tom Tromey committed
585
   * @see DebugGraphics
586
   * @see #getComponentGraphics
Tom Tromey committed
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
   */
  int debugGraphicsOptions;

  /** 
   * <p>This property controls two independent behaviors simultaneously.</p>
   *
   * <p>First, it controls whether to fill the background of this widget
   * when painting its body. This affects calls to {@link
   * JComponent#paintComponent}, which in turn calls {@link
   * ComponentUI#update} on the component's {@link #ui} property. If the
   * component is opaque during this call, the background will be filled
   * before calling {@link ComponentUI#paint}. This happens merely as a
   * convenience; you may fill the component's background yourself too,
   * but there is no need to do so if you will be filling with the same
   * color.</p>
   *
   * <p>Second, it the opaque property informs swing's repaint system
   * whether it will be necessary to paint the components "underneath" this
   * component, in Z-order. If the component is opaque, it is considered to
   * completely occlude components "underneath" it, so they will not be
   * repainted along with the opaque component.</p>
   *
   * <p>The default value for this property is <code>false</code>, but most
   * components will want to set it to <code>true</code> when installing UI
   * defaults in {@link ComponentUI#installUI}.</p>
   *
   * @see #setOpaque
   * @see #isOpaque
   * @see #paintComponent
   */
  boolean opaque = false;

  /** 
   * The user interface delegate for this component. Event delivery and
   * repainting of the component are usually delegated to this object. 
   *
   * @see #setUI
Tom Tromey committed
624
   * @see #getUIClassID
Tom Tromey committed
625 626 627 628 629 630 631 632 633 634 635
   * @see #updateUI
   */
  protected ComponentUI ui;

  /**
   * A hint to the focus system that this component should or should not
   * get focus. If this is <code>false</code>, swing will not try to
   * request focus on this component; if <code>true</code>, swing might
   * try to request focus, but the request might fail. Thus it is only 
   * a hint guiding swing's behavior.
   *
636
   * @see #requestFocus()
Tom Tromey committed
637 638 639 640 641 642 643 644 645 646 647 648
   * @see #isRequestFocusEnabled
   * @see #setRequestFocusEnabled
   */
  boolean requestFocusEnabled;

  /**
   * Flag indicating behavior of this component when the mouse is dragged
   * outside the component and the mouse <em>stops moving</em>. If
   * <code>true</code>, synthetic mouse events will be delivered on regular
   * timed intervals, continuing off in the direction the mouse exited the
   * component, until the mouse is released or re-enters the component.
   *
649 650
   * @see #setAutoscrolls
   * @see #getAutoscrolls
Tom Tromey committed
651 652 653 654
   */
  boolean autoscrolls = false;

  /**
655 656 657
   * Indicates whether the current paint call is already double buffered or
   * not. 
   */
658 659 660 661 662 663
  static boolean paintingDoubleBuffered = false;

  /**
   * Indicates whether we are calling paintDoubleBuffered() from
   * paintImmadiately (RepaintManager) or from paint() (AWT refresh).
   */
664
  static boolean isRepainting = false;
665 666

  /**
Tom Tromey committed
667 668 669 670 671 672
   * Listeners for events other than {@link PropertyChangeEvent} are
   * handled by this listener list. PropertyChangeEvents are handled in
   * {@link #changeSupport}.
   */
  protected EventListenerList listenerList = new EventListenerList();

673 674 675 676 677
  /**
   * Handles VetoableChangeEvents.
   */
  private VetoableChangeSupport vetoableChangeSupport;

Tom Tromey committed
678 679 680 681 682 683 684 685 686 687
  /** 
   * Storage for "client properties", which are key/value pairs associated
   * with this component by a "client", such as a user application or a
   * layout manager. This is lazily constructed when the component gets its
   * first client property.
   */
  private Hashtable clientProperties;
  
  private InputMap inputMap_whenFocused;
  private InputMap inputMap_whenAncestorOfFocused;
688
  private ComponentInputMap inputMap_whenInFocusedWindow;
Tom Tromey committed
689 690
  private ActionMap actionMap;
  /** @since 1.3 */
691
  private boolean verifyInputWhenFocusTarget = true;
Tom Tromey committed
692 693 694 695
  private InputVerifier inputVerifier;

  private TransferHandler transferHandler;

696 697 698 699 700 701
  /**
   * Indicates if this component is currently painting a tile or not.
   */
  private boolean paintingTile;

  /**
702 703 704 705 706 707 708 709 710 711
   * A temporary buffer used for fast dragging of components.
   */
  private Image dragBuffer;

  /**
   * Indicates if the dragBuffer is already initialized.
   */
  private boolean dragBufferInitialized;

  /**
712 713 714
   * A cached Rectangle object to be reused. Be careful when you use that,
   * so that it doesn't get modified in another context within the same
   * method call chain.
Tom Tromey committed
715
   */
716
  private static transient Rectangle rectCache;
Tom Tromey committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731

  /**
   * The default locale of the component.
   * 
   * @see #getDefaultLocale
   * @see #setDefaultLocale
   */
  private static Locale defaultLocale;
  
  public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";

  /**
   * Constant used to indicate that no condition has been assigned to a
   * particular action.
   *
Tom Tromey committed
732
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
Tom Tromey committed
733 734 735 736 737 738 739
   */
  public static final int UNDEFINED_CONDITION = -1;

  /**
   * Constant used to indicate that an action should be performed only when 
   * the component has focus.
   *
Tom Tromey committed
740
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
Tom Tromey committed
741 742 743 744 745 746 747
   */
  public static final int WHEN_FOCUSED = 0;

  /**
   * Constant used to indicate that an action should be performed only when 
   * the component is an ancestor of the component which has focus.
   *
Tom Tromey committed
748
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
Tom Tromey committed
749 750 751 752 753 754 755
   */
  public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;

  /**
   * Constant used to indicate that an action should be performed only when 
   * the component is in the window which has focus.
   *
Tom Tromey committed
756
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
Tom Tromey committed
757 758 759
   */
  public static final int WHEN_IN_FOCUSED_WINDOW = 2;

760 761 762 763 764 765 766

  /**
   * Used to optimize painting. This is set in paintImmediately2() to specify
   * the exact component path to be painted by paintChildren.
   */
  Component paintChild;

Tom Tromey committed
767
  /**
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
   * Indicates if the opaque property has been set by a client program or by
   * the UI.
   *
   * @see #setUIProperty(String, Object)
   * @see LookAndFeel#installProperty(JComponent, String, Object)
   */
  private boolean clientOpaqueSet = false;

  /**
   * Indicates if the autoscrolls property has been set by a client program or
   * by the UI.
   *
   * @see #setUIProperty(String, Object)
   * @see LookAndFeel#installProperty(JComponent, String, Object)
   */
  private boolean clientAutoscrollsSet = false;

  /**
Tom Tromey committed
786 787 788 789 790 791
   * Creates a new <code>JComponent</code> instance.
   */
  public JComponent()
  {
    super();
    setDropTarget(new DropTarget());
792
    setLocale(getDefaultLocale());
Tom Tromey committed
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    debugGraphicsOptions = DebugGraphics.NONE_OPTION;
    setRequestFocusEnabled(true);
  }

  /**
   * Helper to lazily construct and return the client properties table.
   * 
   * @return The current client properties table
   *
   * @see #clientProperties
   * @see #getClientProperty
   * @see #putClientProperty
   */
  private Hashtable getClientProperties()
  {
    if (clientProperties == null)
      clientProperties = new Hashtable();
    return clientProperties;
  }

  /**
   * Get a client property associated with this component and a particular
   * key.
   *
   * @param key The key with which to look up the client property
   *
   * @return A client property associated with this object and key
   *
   * @see #clientProperties
   * @see #getClientProperties
   * @see #putClientProperty
   */
  public final Object getClientProperty(Object key)
  {
    return getClientProperties().get(key);
  }

  /**
   * Add a client property <code>value</code> to this component, associated
   * with <code>key</code>. If there is an existing client property
833 834 835
   * associated with <code>key</code>, it will be replaced.  A
   * {@link PropertyChangeEvent} is sent to registered listeners (with the
   * name of the property being <code>key.toString()</code>).
Tom Tromey committed
836 837 838 839 840 841 842 843 844 845
   *
   * @param key The key of the client property association to add
   * @param value The value of the client property association to add
   *
   * @see #clientProperties
   * @see #getClientProperties
   * @see #getClientProperty
   */
  public final void putClientProperty(Object key, Object value)
  {
846 847
    Hashtable t = getClientProperties();
    Object old = t.get(key);
Tom Tromey committed
848
    if (value != null)
849
      t.put(key, value);
Tom Tromey committed
850
    else
851
      t.remove(key);
852 853 854 855 856 857

    // When both old and new value are null, no event is fired. This is
    // different from what firePropertyChange() normally does, so we add this
    // check here.
    if (old != null || value != null)
      firePropertyChange(key.toString(), old, value);
Tom Tromey committed
858 859 860 861 862 863 864
  }

  /**
   * Unregister an <code>AncestorListener</code>.
   *
   * @param listener The listener to unregister
   * 
Tom Tromey committed
865
   * @see #addAncestorListener
Tom Tromey committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
   */
  public void removeAncestorListener(AncestorListener listener)
  {
    listenerList.remove(AncestorListener.class, listener);
  }

  /**
   * Unregister a <code>VetoableChangeChangeListener</code>.
   *
   * @param listener The listener to unregister
   *
   * @see #addVetoableChangeListener
   */
  public void removeVetoableChangeListener(VetoableChangeListener listener)
  {
881 882
    if (vetoableChangeSupport != null)
      vetoableChangeSupport.removeVetoableChangeListener(listener);
Tom Tromey committed
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
  }

  /**
   * Register an <code>AncestorListener</code>.
   *
   * @param listener The listener to register
   *
   * @see #removeVetoableChangeListener
   */
  public void addAncestorListener(AncestorListener listener)
  {
    listenerList.add(AncestorListener.class, listener);
  }

  /**
   * Register a <code>VetoableChangeListener</code>.
   *
   * @param listener The listener to register
   *
   * @see #removeVetoableChangeListener
   * @see #listenerList
   */
  public void addVetoableChangeListener(VetoableChangeListener listener)
  {
907 908 909 910
    // Lazily instantiate this, it's rarely needed.
    if (vetoableChangeSupport == null)
      vetoableChangeSupport = new VetoableChangeSupport(this);
    vetoableChangeSupport.addVetoableChangeListener(listener);
Tom Tromey committed
911 912 913
  }

  /**
914 915
   * Returns all registered {@link EventListener}s of the given 
   * <code>listenerType</code>.
Tom Tromey committed
916
   *
917 918 919 920 921 922 923 924 925 926 927
   * @param listenerType the class of listeners to filter (<code>null</code> 
   *                     not permitted).
   *                     
   * @return An array of registered listeners.
   * 
   * @throws ClassCastException if <code>listenerType</code> does not implement
   *                            the {@link EventListener} interface.
   * @throws NullPointerException if <code>listenerType</code> is 
   *                              <code>null</code>.
   *                            
   * @see #getAncestorListeners()
Tom Tromey committed
928
   * @see #listenerList
929 930
   * 
   * @since 1.3
Tom Tromey committed
931
   */
932
  public <T extends EventListener> T[] getListeners(Class<T> listenerType)
Tom Tromey committed
933
  {
934
    if (listenerType == PropertyChangeListener.class)
935
      return (T[]) getPropertyChangeListeners();
936
    else if (listenerType == VetoableChangeListener.class)
937
      return (T[]) getVetoableChangeListeners();
938 939
    else
      return listenerList.getListeners(listenerType);
Tom Tromey committed
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
  }

  /**
   * Return all registered <code>AncestorListener</code> objects.
   *
   * @return The set of <code>AncestorListener</code> objects in {@link
   * #listenerList}
   */
  public AncestorListener[] getAncestorListeners()
  {
    return (AncestorListener[]) getListeners(AncestorListener.class);
  }

  /**
   * Return all registered <code>VetoableChangeListener</code> objects.
   *
956 957 958 959 960
   * @return An array of the <code>VetoableChangeListener</code> objects 
   *     registered with this component (possibly empty but never 
   *     <code>null</code>).
   * 
   * @since 1.4
Tom Tromey committed
961 962
   */
  public VetoableChangeListener[] getVetoableChangeListeners()
963 964 965
  {    
    return vetoableChangeSupport == null ? new VetoableChangeListener[0]
        : vetoableChangeSupport.getVetoableChangeListeners();
Tom Tromey committed
966 967 968
  }

  /**
969 970 971 972 973 974 975 976 977
   * Call {@link VetoableChangeListener#vetoableChange} on all listeners
   * registered to listen to a given property. Any method which changes
   * the specified property of this component should call this method.
   *
   * @param propertyName The property which changed
   * @param oldValue The old value of the property
   * @param newValue The new value of the property
   *
   * @throws PropertyVetoException if the change was vetoed by a listener
978
   *
979 980
   * @see #addVetoableChangeListener
   * @see #removeVetoableChangeListener
Tom Tromey committed
981
   */
982 983 984
  protected void fireVetoableChange(String propertyName, Object oldValue,
                                    Object newValue)
    throws PropertyVetoException
Tom Tromey committed
985
  {
986 987
    if (vetoableChangeSupport != null)
      vetoableChangeSupport.fireVetoableChange(propertyName, oldValue, newValue);
Tom Tromey committed
988 989
  }

990

Tom Tromey committed
991
  /**
992 993 994 995 996
   * Fires a property change for a primitive integer property.
   *
   * @param property the name of the property
   * @param oldValue the old value of the property
   * @param newValue the new value of the property
997
   *
998 999 1000 1001
   * @specnote This method is implemented in
   *           {@link Component#firePropertyChange(String, int, int)}. It is
   *           only here because it is specified to be public, whereas the
   *           Component method is protected.
Tom Tromey committed
1002
   */
1003
  public void firePropertyChange(String property, int oldValue, int newValue)
Tom Tromey committed
1004
  {
1005
    super.firePropertyChange(property, oldValue, newValue);
Tom Tromey committed
1006
  }
1007
  
Tom Tromey committed
1008
  /**
1009 1010 1011 1012 1013
   * Fires a property change for a primitive boolean property.
   *
   * @param property the name of the property
   * @param oldValue the old value of the property
   * @param newValue the new value of the property
1014
   *
1015 1016 1017 1018
   * @specnote This method is implemented in
   *           {@link Component#firePropertyChange(String, boolean, boolean)}.
   *           It is only here because it is specified to be public, whereas
   *           the Component method is protected.
Tom Tromey committed
1019
   */
1020 1021
  public void firePropertyChange(String property, boolean oldValue,
                                 boolean newValue)
Tom Tromey committed
1022
  {
1023
    super.firePropertyChange(property, oldValue, newValue);
Tom Tromey committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
  }

  /**
   * Get the value of the accessibleContext property for this component.
   *
   * @return the current value of the property
   */
  public AccessibleContext getAccessibleContext()
  {
    return null;
  }

  /**
   * Get the value of the {@link #alignmentX} property.
   *
   * @return The current value of the property.
   *
   * @see #setAlignmentX
   * @see #alignmentY
   */
  public float getAlignmentX()
  {
1046 1047 1048 1049 1050 1051
    float ret = alignmentX;
    if (alignmentX < 0)
      // alignment has not been set explicitly.
      ret = super.getAlignmentX();

    return ret;
Tom Tromey committed
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
  }

  /**
   * Get the value of the {@link #alignmentY} property.
   *
   * @return The current value of the property.
   *
   * @see #setAlignmentY
   * @see #alignmentX
   */
  public float getAlignmentY()
  {
1064 1065 1066 1067 1068 1069
    float ret = alignmentY;
    if (alignmentY < 0)
      // alignment has not been set explicitly.
      ret = super.getAlignmentY();

    return ret;
Tom Tromey committed
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  }

  /**
   * Get the current value of the {@link #autoscrolls} property.
   *
   * @return The current value of the property
   */
  public boolean getAutoscrolls()
  {
    return autoscrolls;
  }

  /**
   * Set the value of the {@link #border} property.
   *   
   * @param newBorder The new value of the property
   *
   * @see #getBorder
   */
  public void setBorder(Border newBorder)
  {
1091 1092 1093 1094
    Border oldBorder = getBorder();
    if (oldBorder == newBorder)
      return;

Tom Tromey committed
1095 1096
    border = newBorder;
    firePropertyChange("border", oldBorder, newBorder);
1097
    repaint();
Tom Tromey committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  }

  /**
   * Get the value of the {@link #border} property.
   *
   * @return The property's current value
   *
   * @see #setBorder
   */
  public Border getBorder()
  {
    return border;
  }

  /**
   * Get the component's current bounding box. If a rectangle is provided,
   * use this as the return value (adjusting its fields in place);
   * otherwise (of <code>null</code> is provided) return a new {@link
   * Rectangle}.
   *
   * @param rv Optional return value to use
   *
   * @return A rectangle bounding the component
   */
  public Rectangle getBounds(Rectangle rv)
  {
    if (rv == null)
      return new Rectangle(getX(), getY(), getWidth(), getHeight());
    else
      {
        rv.setBounds(getX(), getY(), getWidth(), getHeight());
        return rv;
      }
  }

  /**
   * Prepares a graphics context for painting this object. If {@link
   * #debugGraphicsOptions} is not equal to {@link
   * DebugGraphics#NONE_OPTION}, produce a new {@link DebugGraphics} object
   * wrapping the parameter. Otherwise configure the parameter with this
   * component's foreground color and font.
   *
   * @param g The graphics context to wrap or configure
   *
   * @return A graphics context to paint this object with
   *
   * @see #debugGraphicsOptions
   * @see #paint
   */
  protected Graphics getComponentGraphics(Graphics g)
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  {
    Graphics g2 = g;
    int options = getDebugGraphicsOptions();
    if (options != DebugGraphics.NONE_OPTION)
      {
        if (!(g2 instanceof DebugGraphics))
          g2 = new DebugGraphics(g);
        DebugGraphics dg = (DebugGraphics) g2;
        dg.setDebugOptions(dg.getDebugOptions() | options);
      }
    g2.setFont(this.getFont());
    g2.setColor(this.getForeground());
    return g2;
Tom Tromey committed
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
  }

  /**
   * Get the value of the {@link #debugGraphicsOptions} property.
   *
   * @return The current value of the property.
   *
   * @see #setDebugGraphicsOptions
   * @see #debugGraphicsOptions
   */
  public int getDebugGraphicsOptions()
  {
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
    String option = System.getProperty("gnu.javax.swing.DebugGraphics");
    int options = debugGraphicsOptions;
    if (option != null && option.length() != 0)
      {
        if (options < 0)
          options = 0;

        if (option.equals("LOG"))
          options |= DebugGraphics.LOG_OPTION;
        else if (option.equals("FLASH"))
          options |= DebugGraphics.FLASH_OPTION;
      }
    return options;
Tom Tromey committed
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  }

  /**
   * Get the component's insets, which are calculated from
   * the {@link #border} property. If the border is <code>null</code>,
   * calls {@link Container#getInsets}.
   *
   * @return The component's current insets
   */
  public Insets getInsets()
  {
    if (border == null)
      return super.getInsets();
    return getBorder().getBorderInsets(this);
  }

  /**
   * Get the component's insets, which are calculated from the {@link
   * #border} property. If the border is <code>null</code>, calls {@link
   * Container#getInsets}. The passed-in {@link Insets} value will be
   * used as the return value, if possible.
   *
   * @param insets Return value object to reuse, if possible
   *
   * @return The component's current insets
   */
  public Insets getInsets(Insets insets)
  {
    Insets t = getInsets();

    if (insets == null)
      return t;

    insets.left = t.left;
    insets.right = t.right;
    insets.top = t.top;
    insets.bottom = t.bottom;
    return insets;
  }

  /**
   * Get the component's location. The passed-in {@link Point} value
   * will be used as the return value, if possible.
   *
   * @param rv Return value object to reuse, if possible
   *
   * @return The component's current location
   */
  public Point getLocation(Point rv)
  {
    if (rv == null)
      return new Point(getX(), getY());

    rv.setLocation(getX(), getY());
    return rv;
  }

  /**
1244 1245
   * Get the component's maximum size. If the <code>maximumSize</code> property
   * has been explicitly set, it is returned. If the <code>maximumSize</code>
Tom Tromey committed
1246
   * property has not been set but the {@link #ui} property has been, the
Tom Tromey committed
1247 1248 1249 1250
   * result of {@link ComponentUI#getMaximumSize} is returned. If neither
   * property has been set, the result of {@link Container#getMaximumSize}
   * is returned.
   *
1251
   * @return the maximum size of the component
Tom Tromey committed
1252
   *
1253 1254 1255 1256
   * @see Component#setMaximumSize
   * @see Component#getMaximumSize()
   * @see Component#isMaximumSizeSet()
   * @see ComponentUI#getMaximumSize(JComponent)
Tom Tromey committed
1257 1258 1259
   */
  public Dimension getMaximumSize()
  {
1260 1261 1262 1263
    Dimension size = null; 
    if (isMaximumSizeSet())
      size = super.getMaximumSize();
    else
Tom Tromey committed
1264
      {
1265 1266 1267 1268
        if (ui != null)
          size = ui.getMaximumSize(this);
        if (size == null)
          size = super.getMaximumSize();
Tom Tromey committed
1269
      }
1270
    return size;
Tom Tromey committed
1271 1272 1273
  }

  /**
1274 1275
   * Get the component's minimum size. If the <code>minimumSize</code> property
   * has been explicitly set, it is returned. If the <code>minimumSize</code>
Tom Tromey committed
1276
   * property has not been set but the {@link #ui} property has been, the
Tom Tromey committed
1277 1278 1279 1280 1281 1282
   * result of {@link ComponentUI#getMinimumSize} is returned. If neither
   * property has been set, the result of {@link Container#getMinimumSize}
   * is returned.
   *
   * @return The minimum size of the component
   *
1283 1284 1285 1286
   * @see Component#setMinimumSize
   * @see Component#getMinimumSize()
   * @see Component#isMinimumSizeSet()
   * @see ComponentUI#getMinimumSize(JComponent)
Tom Tromey committed
1287 1288 1289
   */
  public Dimension getMinimumSize()
  {
1290 1291 1292 1293
    Dimension size = null; 
    if (isMinimumSizeSet())
      size = super.getMinimumSize();
    else
Tom Tromey committed
1294
      {
1295 1296 1297 1298
        if (ui != null)
          size = ui.getMinimumSize(this);
        if (size == null)
          size = super.getMinimumSize();
Tom Tromey committed
1299
      }
1300
    return size;
Tom Tromey committed
1301 1302 1303
  }

  /**
1304 1305 1306 1307
   * Get the component's preferred size. If the <code>preferredSize</code>
   * property has been explicitly set, it is returned. If the
   * <code>preferredSize</code> property has not been set but the {@link #ui}
   * property has been, the result of {@link ComponentUI#getPreferredSize} is
Tom Tromey committed
1308 1309 1310 1311 1312
   * returned. If neither property has been set, the result of {@link
   * Container#getPreferredSize} is returned.
   *
   * @return The preferred size of the component
   *
1313 1314 1315 1316
   * @see Component#setPreferredSize
   * @see Component#getPreferredSize()
   * @see Component#isPreferredSizeSet()
   * @see ComponentUI#getPreferredSize(JComponent)
Tom Tromey committed
1317 1318 1319
   */
  public Dimension getPreferredSize()
  {
1320 1321 1322 1323
    Dimension size = null; 
    if (isPreferredSizeSet())
      size = super.getPreferredSize();
    else
Tom Tromey committed
1324
      {
1325 1326 1327 1328
        if (ui != null)
          size = ui.getPreferredSize(this);
        if (size == null)
          size = super.getPreferredSize();
Tom Tromey committed
1329
      }
1330
    return size;
Tom Tromey committed
1331 1332 1333
  }

  /**
Tom Tromey committed
1334
   * Return the value of the <code>nextFocusableComponent</code> property.
Tom Tromey committed
1335 1336 1337 1338 1339 1340 1341 1342
   *
   * @return The current value of the property, or <code>null</code>
   * if none has been set.
   * 
   * @deprecated See {@link java.awt.FocusTraversalPolicy}
   */
  public Component getNextFocusableComponent()
  {
1343 1344 1345 1346 1347 1348
    Container focusRoot = this;
    if (! this.isFocusCycleRoot())
      focusRoot = getFocusCycleRootAncestor();

    FocusTraversalPolicy policy  = focusRoot.getFocusTraversalPolicy();
    return policy.getComponentAfter(focusRoot, this);
Tom Tromey committed
1349 1350 1351 1352 1353 1354
  }

  /**
   * Return the set of {@link KeyStroke} objects which are registered
   * to initiate actions on this component.
   *
1355 1356
   * @return An array of the registered keystrokes (possibly empty but never
   *     <code>null</code>).
Tom Tromey committed
1357 1358 1359
   */
  public KeyStroke[] getRegisteredKeyStrokes()
  {
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    KeyStroke[] ks0;
    KeyStroke[] ks1;
    KeyStroke[] ks2;
    if (inputMap_whenFocused != null)
      ks0 = inputMap_whenFocused.keys();
    else 
      ks0 = new KeyStroke[0];
    if (inputMap_whenAncestorOfFocused != null)
      ks1 = inputMap_whenAncestorOfFocused.keys();
    else 
      ks1 = new KeyStroke[0];
    if (inputMap_whenInFocusedWindow != null)
      ks2 = inputMap_whenInFocusedWindow.keys();
    else
      ks2 = new KeyStroke[0];
    int count = ks0.length + ks1.length + ks2.length;
    KeyStroke[] result = new KeyStroke[count];
    System.arraycopy(ks0, 0, result, 0, ks0.length);
    System.arraycopy(ks1, 0, result, ks0.length, ks1.length);
    System.arraycopy(ks2, 0, result, ks0.length + ks1.length, ks2.length);
    return result;
Tom Tromey committed
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  }

  /**
   * Returns the first ancestor of this component which is a {@link JRootPane}.
   * Equivalent to calling <code>SwingUtilities.getRootPane(this);</code>.
   *
   * @return An ancestral JRootPane, or <code>null</code> if none exists.
   */
  public JRootPane getRootPane()
  {
    JRootPane p = SwingUtilities.getRootPane(this);
    return p;
  }

  /**
   * Get the component's size. The passed-in {@link Dimension} value
   * will be used as the return value, if possible.
   *
   * @param rv Return value object to reuse, if possible
   *
   * @return The component's current size
   */
  public Dimension getSize(Dimension rv)
  {
    if (rv == null)
      return new Dimension(getWidth(), getHeight());
    else
      {
        rv.setSize(getWidth(), getHeight());
        return rv;
      }
  }

  /**
Tom Tromey committed
1415
   * Return the <code>toolTip</code> property of this component, creating it and
Tom Tromey committed
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
   * setting it if it is currently <code>null</code>. This method can be
   * overridden in subclasses which wish to control the exact form of
   * tooltip created.
   *
   * @return The current toolTip
   */
  public JToolTip createToolTip()
  {
    JToolTip toolTip = new JToolTip();
    toolTip.setComponent(this);
    return toolTip;
  }

  /**
1430 1431
   * Return the location at which the <code>toolTipText</code> property should
   * be displayed, when triggered by a particular mouse event. 
Tom Tromey committed
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443
   *
   * @param event The event the tooltip is being presented in response to
   *
   * @return The point at which to display a tooltip, or <code>null</code>
   *     if swing is to choose a default location.
   */
  public Point getToolTipLocation(MouseEvent event)
  {
    return null;
  }

  /**
1444 1445 1446 1447 1448
   * Set the tooltip text for this component. If a non-<code>null</code>
   * value is set, this component is registered in the
   * <code>ToolTipManager</code> in order to turn on tooltips for this
   * component. If a <code>null</code> value is set, tooltips are turne off
   * for this component.
Tom Tromey committed
1449
   *
1450
   * @param text the tooltip text for this component
Tom Tromey committed
1451
   *
Tom Tromey committed
1452
   * @see #getToolTipText()
1453
   * @see #getToolTipText(MouseEvent)
Tom Tromey committed
1454 1455 1456
   */
  public void setToolTipText(String text)
  {
1457 1458 1459
    String old = getToolTipText();
    putClientProperty(TOOL_TIP_TEXT_KEY, text);
    ToolTipManager ttm = ToolTipManager.sharedInstance();
Tom Tromey committed
1460
    if (text == null)
1461 1462 1463
      ttm.unregisterComponent(this);
    else if (old == null)
      ttm.registerComponent(this);
Tom Tromey committed
1464 1465 1466
  }

  /**
1467 1468
   * Returns the current tooltip text for this component, or <code>null</code>
   * if none has been set.
Tom Tromey committed
1469
   *
1470 1471
   * @return the current tooltip text for this component, or <code>null</code>
   *         if none has been set
Tom Tromey committed
1472 1473
   *
   * @see #setToolTipText
1474
   * @see #getToolTipText(MouseEvent)
Tom Tromey committed
1475 1476 1477
   */
  public String getToolTipText()
  {
1478
    return (String) getClientProperty(TOOL_TIP_TEXT_KEY);
Tom Tromey committed
1479 1480 1481
  }

  /**
1482 1483 1484 1485
   * Returns the tooltip text for this component for a particular mouse
   * event. This can be used to support context sensitive tooltips that can
   * change with the mouse location. By default this returns the static
   * tooltip text returned by {@link #getToolTipText()}.
Tom Tromey committed
1486
   *
1487
   * @param event the mouse event which triggered the tooltip
Tom Tromey committed
1488
   *
1489 1490
   * @return the tooltip text for this component for a particular mouse
   *         event
Tom Tromey committed
1491 1492
   *
   * @see #setToolTipText
1493
   * @see #getToolTipText()
Tom Tromey committed
1494 1495 1496 1497 1498
   */
  public String getToolTipText(MouseEvent event)
  {
    return getToolTipText();
  }
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  
  /**
   * Returns the flag that controls whether or not the component inherits its
   * parent's popup menu when no popup menu is specified for this component.
   * 
   * @return A boolean.
   * 
   * @since 1.5
   * 
   * @see #setInheritsPopupMenu(boolean)
   */
  public boolean getInheritsPopupMenu()
  {
    return inheritsPopupMenu; 
  }
  
  /**
   * Sets the flag that controls whether or not the component inherits its
   * parent's popup menu when no popup menu is specified for this component.
   * This is a bound property with the property name 'inheritsPopupMenu'.
   * 
   * @param inherit  the new flag value.
   * 
   * @since 1.5
   * 
   * @see #getInheritsPopupMenu()
   */
  public void setInheritsPopupMenu(boolean inherit)
  {
    if (inheritsPopupMenu != inherit)
      {
        inheritsPopupMenu = inherit;
        this.firePropertyChange("inheritsPopupMenu", ! inherit, inherit);
      }
  }
  
  /**
   * Returns the popup menu for this component.  If the popup menu is 
   * <code>null</code> AND the {@link #getInheritsPopupMenu()} method returns
   * <code>true</code>, this method will return the parent's popup menu (if it
   * has one).
   * 
   * @return The popup menu (possibly <code>null</code>.
   * 
   * @since 1.5
   * 
   * @see #setComponentPopupMenu(JPopupMenu)
   * @see #getInheritsPopupMenu()
   */
  public JPopupMenu getComponentPopupMenu()
  {
    if (componentPopupMenu == null && getInheritsPopupMenu())
      {
        Container parent = getParent(); 
        if (parent instanceof JComponent)
          return ((JComponent) parent).getComponentPopupMenu();
        else
          return null;
      }
    else
      return componentPopupMenu;
  }
Tom Tromey committed
1561 1562

  /**
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
   * Sets the popup menu for this component (this is a bound property with 
   * the property name 'componentPopupMenu').
   * 
   * @param popup  the popup menu (<code>null</code> permitted).
   *
   * @since 1.5
   * 
   * @see #getComponentPopupMenu()
   */
  public void setComponentPopupMenu(JPopupMenu popup)
  {
    if (componentPopupMenu != popup)
      {
        JPopupMenu old = componentPopupMenu;
        componentPopupMenu = popup;
        firePropertyChange("componentPopupMenu", old, popup);
      }
  }
  
  /**
Tom Tromey committed
1583
   * Return the top level ancestral container (usually a {@link
Tom Tromey committed
1584
   * java.awt.Window} or {@link java.applet.Applet}) which this component is
Tom Tromey committed
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
   * contained within, or <code>null</code> if no ancestors exist.
   *
   * @return The top level container, if it exists
   */
  public Container getTopLevelAncestor()
  {
    Container c = getParent();
    for (Container peek = c; peek != null; peek = peek.getParent())
      c = peek;
    return c;
  }

  /**
   * Compute the component's visible rectangle, which is defined
   * recursively as either the component's bounds, if it has no parent, or
   * the intersection of the component's bounds with the visible rectangle
   * of its parent.
   *
   * @param rect The return value slot to place the visible rectangle in
   */
  public void computeVisibleRect(Rectangle rect)
  {
    Component c = getParent();
    if (c != null && c instanceof JComponent)
      {
        ((JComponent) c).computeVisibleRect(rect);
        rect.translate(-getX(), -getY());
1612 1613
        rect = SwingUtilities.computeIntersection(0, 0, getWidth(),
                                                  getHeight(), rect);
Tom Tromey committed
1614 1615 1616 1617 1618 1619 1620 1621 1622
      }
    else
      rect.setRect(0, 0, getWidth(), getHeight());
  }

  /**
   * Return the component's visible rectangle in a new {@link Rectangle},
   * rather than via a return slot.
   *
1623
   * @return the component's visible rectangle
Tom Tromey committed
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
   *
   * @see #computeVisibleRect(Rectangle)
   */
  public Rectangle getVisibleRect()
  {
    Rectangle r = new Rectangle();
    computeVisibleRect(r);
    return r;
  }

  /**
   * <p>Requests that this component receive input focus, giving window
   * focus to the top level ancestor of this component. Only works on
   * displayable, focusable, visible components.</p>
   *
   * <p>This method should not be called by clients; it is intended for
Tom Tromey committed
1640
   * focus implementations. Use {@link Component#requestFocus()} instead.</p>
Tom Tromey committed
1641
   *
Tom Tromey committed
1642
   * @see Component#requestFocus()
Tom Tromey committed
1643 1644 1645
   */
  public void grabFocus()
  {
1646
    requestFocus();
Tom Tromey committed
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
  }

  /**
   * Get the value of the {@link #doubleBuffered} property.
   *
   * @return The property's current value
   */
  public boolean isDoubleBuffered()
  {
    return doubleBuffered;
  }

  /**
   * Return <code>true</code> if the provided component has no native peer;
   * in other words, if it is a "lightweight component".
   *
   * @param c The component to test for lightweight-ness
   *
   * @return Whether or not the component is lightweight
   */
  public static boolean isLightweightComponent(Component c)
  {
    return c.getPeer() instanceof LightweightPeer;
  }

  /**
   * Return <code>true</code> if you wish this component to manage its own
   * focus. In particular: if you want this component to be sent
   * <code>TAB</code> and <code>SHIFT+TAB</code> key events, and to not
   * have its children considered as focus transfer targets. If
   * <code>true</code>, focus traversal around this component changes to
   * <code>CTRL+TAB</code> and <code>CTRL+SHIFT+TAB</code>.
   *
   * @return <code>true</code> if you want this component to manage its own
   *     focus, otherwise (by default) <code>false</code>
   *
Tom Tromey committed
1683 1684
   * @deprecated 1.4 Use {@link Component#setFocusTraversalKeys(int, Set)} and
   *     {@link Container#setFocusCycleRoot(boolean)} instead
Tom Tromey committed
1685 1686 1687 1688 1689 1690 1691
   */
  public boolean isManagingFocus()
  {
    return false;
  }

  /**
Tom Tromey committed
1692
   * Return the current value of the {@link #opaque} property. 
Tom Tromey committed
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
   *
   * @return The current property value
   */
  public boolean isOpaque()
  {
    return opaque;
  }

  /**
   * Return <code>true</code> if the component can guarantee that none of its
   * children will overlap in Z-order. This is a hint to the painting system.
   * The default is to return <code>true</code>, but some components such as
   * {@link JLayeredPane} should override this to return <code>false</code>.
   *
   * @return Whether the component tiles its children
   */
  public boolean isOptimizedDrawingEnabled()
  {
    return true;
  }

  /**
1715 1716 1717 1718
   * Return <code>true</code> if this component is currently painting a tile,
   * this means that paint() is called again on another child component. This
   * method returns <code>false</code> if this component does not paint a tile
   * or if the last tile is currently painted.
Tom Tromey committed
1719
   *
1720
   * @return whether the component is painting a tile
Tom Tromey committed
1721 1722 1723
   */
  public boolean isPaintingTile()
  {
1724
    return paintingTile;
Tom Tromey committed
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
  }

  /**
   * Get the value of the {@link #requestFocusEnabled} property.
   *
   * @return The current value of the property
   */
  public boolean isRequestFocusEnabled()
  {
    return requestFocusEnabled;
  }

  /**
   * Return <code>true</code> if this component is a validation root; this
Tom Tromey committed
1739
   * will cause calls to {@link #invalidate()} in this component's children
Tom Tromey committed
1740 1741
   * to be "captured" at this component, and not propagate to its parents.
   * For most components this should return <code>false</code>, but some
Tom Tromey committed
1742
   * components such as {@link JViewport} will want to return
Tom Tromey committed
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
   * <code>true</code>.
   *
   * @return Whether this component is a validation root
   */
  public boolean isValidateRoot()
  {
    return false;
  }

  /**
   * <p>Paint the component. This is a delicate process, and should only be
   * called from the repaint thread, under control of the {@link
Tom Tromey committed
1755
   * RepaintManager}. Client code should usually call {@link #repaint()} to
Tom Tromey committed
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
   * trigger painting.</p>
   *
   * <p>The body of the <code>paint</code> call involves calling {@link
   * #paintComponent}, {@link #paintBorder}, and {@link #paintChildren} in
   * order. If you want to customize painting behavior, you should override
   * one of these methods rather than <code>paint</code>.</p>
   *
   * <p>For more details on the painting sequence, see <a
   * href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">
   * this article</a>.</p>
   *
   * @param g The graphics context to paint with
   *
Tom Tromey committed
1769
   * @see #paintImmediately(Rectangle)
Tom Tromey committed
1770 1771 1772 1773
   */
  public void paint(Graphics g)
  {
    RepaintManager rm = RepaintManager.currentManager(this);
1774 1775 1776 1777 1778 1779 1780 1781
    // We do a little stunt act here to switch on double buffering if it's
    // not already on. If we are not already doublebuffered, then we jump
    // into the method paintDoubleBuffered, which turns on the double buffer
    // and then calls paint(g) again. In the second call we go into the else
    // branch of this if statement and actually paint things to the double
    // buffer. When this method completes, the call stack unwinds back to
    // paintDoubleBuffered, where the buffer contents is finally drawn to the
    // screen.
1782
    if (!paintingDoubleBuffered && isDoubleBuffered()
1783
        && rm.isDoubleBufferingEnabled())
1784 1785
      {
        Rectangle clip = g.getClipBounds();
1786
        paintDoubleBuffered(clip.x, clip.y, clip.width, clip.height);
1787
      }
1788
    else
Tom Tromey committed
1789
      {
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
        if (getClientProperty("bufferedDragging") != null
            && dragBuffer == null)
          {
            initializeDragBuffer();
          }
        else if (getClientProperty("bufferedDragging") == null
            && dragBuffer != null)
          {
            dragBuffer = null;
          }

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
        Rectangle clip = g.getClipBounds();
        int clipX, clipY, clipW, clipH;
        if (clip == null)
          {
            clipX = 0;
            clipY = 0;
            clipW = getWidth();
            clipH = getHeight();
          }
        else
          {
            clipX = clip.x;
            clipY = clip.y;
            clipW = clip.width;
            clipH = clip.height;
          }
1817 1818 1819 1820 1821 1822 1823
        if (dragBuffer != null && dragBufferInitialized)
          {
            g.drawImage(dragBuffer, 0, 0, this);
          }
        else
          {
            Graphics g2 = getComponentGraphics(g);
1824 1825 1826 1827 1828
            if (! isOccupiedByChild(clipX, clipY, clipW, clipH))
              {
                paintComponent(g2);
                paintBorder(g2);
              }
1829 1830
            paintChildren(g2);
          }
Tom Tromey committed
1831 1832 1833 1834
      }
  }

  /**
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
   * Determines if a region of this component is completely occupied by
   * an opaque child component, in which case we don't need to bother
   * painting this component at all.
   *
   * @param x the area, x coordinate
   * @param y the area, y coordinate
   * @param w the area, width
   * @param h the area, height
   *
   * @return <code>true</code> if the specified area is completely covered
   *         by a child component, <code>false</code> otherwise
   */
  private boolean isOccupiedByChild(int x, int y, int w, int h)
  {
    boolean occupied = false;
    int count = getComponentCount();
    for (int i = 0; i < count; i++)
      {
        Component child = getComponent(i);
        int cx = child.getX();
        int cy = child.getY();
        int cw = child.getWidth();
        int ch = child.getHeight();
        if (child.isVisible() && x >= cx && x + w <= cx + cw && y >= cy
            && y + h <= cy + ch)
          {
            occupied = child.isOpaque();
            break;
          }
      }
    return occupied;
  }

  /**
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
   * Initializes the drag buffer by creating a new image and painting this
   * component into it.
   */
  private void initializeDragBuffer()
  {
    dragBufferInitialized = false;
    // Allocate new dragBuffer if the current one is too small.
    if (dragBuffer == null || dragBuffer.getWidth(this) < getWidth()
        || dragBuffer.getHeight(this) < getHeight())
      {
        dragBuffer = createImage(getWidth(), getHeight());
      }
    Graphics g = dragBuffer.getGraphics();
    paint(g);
    g.dispose();
    dragBufferInitialized = true;
  }

  /**
Tom Tromey committed
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
   * Paint the component's border. This usually means calling {@link
   * Border#paintBorder} on the {@link #border} property, if it is
   * non-<code>null</code>. You may override this if you wish to customize
   * border painting behavior. The border is painted after the component's
   * body, but before the component's children.
   *
   * @param g The graphics context with which to paint the border
   *
   * @see #paint
   * @see #paintChildren
   * @see #paintComponent
   */
  protected void paintBorder(Graphics g)
  {
    if (getBorder() != null)
      getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());
  }

  /**
   * Paint the component's children. This usually means calling {@link
   * Container#paint}, which recursively calls {@link #paint} on any of the
   * component's children, with appropriate changes to coordinate space and
   * clipping region. You may override this if you wish to customize
   * children painting behavior. The children are painted after the
   * component's body and border.
   *
   * @param g The graphics context with which to paint the children
   *
   * @see #paint
   * @see #paintBorder
   * @see #paintComponent
   */
  protected void paintChildren(Graphics g)
  {
1922 1923
    if (getComponentCount() > 0)
      {
1924 1925
        // Need to lock the tree to avoid problems with AWT and concurrency.
        synchronized (getTreeLock())
1926
          {
1927 1928 1929 1930 1931
            // Fast forward to the child to paint, if set by
            // paintImmediately2()
            int i = getComponentCount() - 1;
            if (paintChild != null && paintChild.isOpaque())
              {
1932 1933
                for (; i >= 0 && getComponent(i) != paintChild; i--)
                  ;
1934 1935
              }
            for (; i >= 0; i--)
1936
              {
1937 1938 1939
                Component child = getComponent(i);
                if (child != null && child.isLightweight()
                    && child.isVisible())
1940
                  {
1941 1942 1943 1944 1945
                    int cx = child.getX();
                    int cy = child.getY();
                    int cw = child.getWidth();
                    int ch = child.getHeight();
                    if (g.hitClip(cx, cy, cw, ch))
1946
                      {
1947 1948 1949 1950 1951 1952
                        if ((! isOptimizedDrawingEnabled()) && i > 0)
                          {
                            // Check if the child is completely obscured.
                            Rectangle clip = g.getClipBounds(); // A copy.
                            SwingUtilities.computeIntersection(cx, cy, cw, ch,
                                                               clip);
1953 1954
                            if (isCompletelyObscured(i, clip.x, clip.y,
                                                     clip.width, clip.height))
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
                              continue; // Continues the for-loop.
                          }
                        Graphics cg = g.create(cx, cy, cw, ch);
                        cg.setColor(child.getForeground());
                        cg.setFont(child.getFont());
                        try
                          {
                            child.paint(cg);
                          }
                        finally
                          {
                            cg.dispose();
                          }
1968 1969 1970 1971
                      }
                  }
              }
          }
1972
      }
1973 1974 1975
  }

  /**
1976 1977 1978 1979
   * Determines if a region of a child component is completely obscured by one
   * of its siblings.
   *
   * @param index the index of the child component
1980 1981 1982 1983
   * @param x the region to check, x coordinate
   * @param y the region to check, y coordinate
   * @param w the region to check, width
   * @param h the region to check, height
1984
   *
1985 1986
   * @return <code>true</code> if the region is completely obscured by a
   *         sibling, <code>false</code> otherwise
1987
   */
1988
  private boolean isCompletelyObscured(int index, int x, int y, int w, int h)
1989
  {
1990 1991
    boolean obscured = false;
    for (int i = index - 1; i >= 0 && obscured == false; i--)
1992
      {
1993 1994 1995 1996
        Component sib = getComponent(i);
        if (sib.isVisible())
          {
            Rectangle sibRect = sib.getBounds(rectCache);
1997 1998 1999 2000
            if (sib.isOpaque() && x >= sibRect.x
                && (x + w) <= (sibRect.x + sibRect.width)
                && y >= sibRect.y
                && (y + h) <= (sibRect.y + sibRect.height))
2001 2002 2003 2004
              {
                obscured = true;
              }
          }
2005
      }
2006
    return obscured;
Tom Tromey committed
2007 2008 2009
  }

  /**
2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
   * Checks if a component/rectangle is partially obscured by one of its
   * siblings.
   * Note that this doesn't check for completely obscured, this is
   * done by isCompletelyObscured() and should probably also be checked.
   *
   * @param i the component index from which to start searching
   * @param x the x coordinate of the rectangle to check
   * @param y the y coordinate of the rectangle to check
   * @param w the width of the rectangle to check
   * @param h the height of the rectangle to check
   *
   * @return <code>true</code> if the rectangle is partially obscured
   */
  private boolean isPartiallyObscured(int i, int x, int y, int w, int h)
  {
    boolean obscured = false;
    for (int j = i - 1; j >= 0 && ! obscured; j--)
      {
        Component sibl = getComponent(j);
        if (sibl.isVisible())
          {
            Rectangle rect = sibl.getBounds(rectCache);
            if (!(x + w <= rect.x)
                  || (y + h <= rect.y)
                  || (x >= rect.x + rect.width)
                  || (y >= rect.y + rect.height))
              obscured = true;
          }
      }
    return obscured;
  }

  /**
Tom Tromey committed
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058
   * Paint the component's body. This usually means calling {@link
   * ComponentUI#update} on the {@link #ui} property of the component, if
   * it is non-<code>null</code>. You may override this if you wish to
   * customize the component's body-painting behavior. The component's body
   * is painted first, before the border and children.
   *
   * @param g The graphics context with which to paint the body
   *
   * @see #paint
   * @see #paintBorder
   * @see #paintChildren
   */
  protected void paintComponent(Graphics g)
  {
    if (ui != null)
      {
2059 2060 2061 2062 2063 2064 2065 2066 2067
        Graphics g2 = g.create();
        try
          {
            ui.update(g2, this);
          }
        finally
          {
            g2.dispose();
          }
Tom Tromey committed
2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
      }
  }

  /**
   * A variant of {@link #paintImmediately(Rectangle)} which takes
   * integer parameters.
   *
   * @param x The left x coordinate of the dirty region
   * @param y The top y coordinate of the dirty region
   * @param w The width of the dirty region
   * @param h The height of the dirty region
   */
  public void paintImmediately(int x, int y, int w, int h)
  {
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    // Find opaque parent and call paintImmediately2() on it.
    if (isShowing())
      {
        Component c = this;
        Component p;
        while (c != null && ! c.isOpaque())
          {
            p = c.getParent();
            if (p != null)
              {
                x += c.getX();
                y += c.getY();
                c = p;
              }
          }
        if (c instanceof JComponent)
          ((JComponent) c).paintImmediately2(x, y, w, h);
        else
          c.repaint(x, y, w, h);
      }
Tom Tromey committed
2102 2103 2104 2105 2106 2107 2108 2109
  }

  /**
   * Transform the provided dirty rectangle for this component into the
   * appropriate ancestral {@link JRootPane} and call {@link #paint} on
   * that root pane. This method is called from the {@link RepaintManager}
   * and should always be called within the painting thread.
   *
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
   * <p>This method will acquire a double buffer from the {@link
   * RepaintManager} if the component's {@link #doubleBuffered} property is
   * <code>true</code> and the <code>paint</code> call is the
   * <em>first</em> recursive <code>paint</code> call inside swing.</p>
   *
   * <p>The method will also modify the provided {@link Graphics} context
   * via the {@link #getComponentGraphics} method. If you want to customize
   * the graphics object used for painting, you should override that method
   * rather than <code>paint</code>.</p>
   *
Tom Tromey committed
2120 2121 2122 2123
   * @param r The dirty rectangle to paint
   */
  public void paintImmediately(Rectangle r)
  {
2124
    paintImmediately(r.x, r.y, r.width, r.height);
2125 2126 2127 2128 2129
  }

  /**
   * Performs the actual work of paintImmediatly on the repaint root.
   *
2130 2131
   * @param x the area to be repainted, X coordinate
   * @param y the area to be repainted, Y coordinate
2132
   */
2133
  void paintImmediately2(int x, int y, int w, int h)
2134
  {
2135 2136 2137 2138
    // Optimization for components that are always painted on top.
    boolean onTop = onTop() && isOpaque();

    // Fetch the RepaintManager.
2139
    RepaintManager rm = RepaintManager.currentManager(this);
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193

    // The painting clip;
    int paintX = x;
    int paintY = y;
    int paintW = w;
    int paintH = h;

    // If we should paint buffered or not.
    boolean haveBuffer = false;

    // The component that is finally triggered for painting.
    JComponent paintRoot = this;
    
    // Stores the component and all its parents. This will be used to limit
    // the actually painted components in paintChildren by setting
    // the field paintChild.
    int pIndex = -1;
    int pCount = 0;
    ArrayList components = new ArrayList();

    // Offset to subtract from the paintRoot rectangle when painting.
    int offsX = 0;
    int offsY = 0;

    // The current component and its child.
    Component child;
    Container c;

    // Find appropriate paint root.
    for (c = this, child = null;
         c != null && ! (c instanceof Window) && ! (c instanceof Applet);
         child = c, c = c.getParent())
      {
        JComponent jc = c instanceof JComponent ? (JComponent) c : null;
        components.add(c);
        if (! onTop && jc != null  && ! jc.isOptimizedDrawingEnabled())
          {
            // Indicates whether we reset the paint root to be the current
            // component.
            boolean updatePaintRoot = false;

            // Check obscured state of the child.
            // Generally, we have 3 cases here:
            // 1. Not obscured. No need to paint from the parent.
            // 2. Partially obscured. Paint from the parent.
            // 3. Completely obscured. No need to paint anything.
            if (c != this)
              {
                if (jc.isPaintRoot())
                  updatePaintRoot = true;
                else
                  {
                    int count = c.getComponentCount();
                    int i = 0;
2194 2195
                    for (; i < count && c.getComponent(i) != child; i++)
                      ;
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287

                    if (jc.isCompletelyObscured(i, paintX, paintY, paintW,
                                                paintH))
                      return; // No need to paint anything.
                    else if (jc.isPartiallyObscured(i, paintX, paintY, paintW,
                                                    paintH))
                      updatePaintRoot = true;
                      
                  }
              }
            if (updatePaintRoot)
              {
                // Paint from parent.
                paintRoot = jc;
                pIndex = pCount;
                offsX = 0;
                offsY = 0;
                haveBuffer = false;
              }
          }
        pCount++;
        // Check if component is double buffered.
        if (rm.isDoubleBufferingEnabled() && jc != null
            && jc.isDoubleBuffered())
          {
            haveBuffer = true;
          }

        // Clip the paint region with the parent.
        if (! onTop)
          {
            paintX = Math.max(0, paintX);
            paintY = Math.max(0, paintY);
            paintW = Math.min(c.getWidth(), paintW + paintX) - paintX;
            paintH = Math.min(c.getHeight(), paintH + paintY) - paintY;
            int dx = c.getX();
            int dy = c.getY();
            paintX += dx;
            paintY += dy;
            offsX += dx;
            offsY += dy;
          }
      }
    if (c != null && c.getPeer() != null && paintW > 0 && paintH > 0)
      {
        isRepainting = true;
        paintX -= offsX;
        paintY -= offsY;

        // Set the painting path so that paintChildren paints only what we
        // want.
        if (paintRoot != this)
          {
            for (int i = pIndex; i > 0; i--)
              {
                Component paintParent = (Component) components.get(i);
                if (paintParent instanceof JComponent)
                  ((JComponent) paintParent).paintChild =
                    (Component) components.get(i - 1);
              }
          }

        // Actually trigger painting.
        if (haveBuffer)
          paintRoot.paintDoubleBuffered(paintX, paintY, paintW, paintH);
        else
          {
            Graphics g = paintRoot.getGraphics();
            try
              {
                g.setClip(paintX, paintY, paintW, paintH);
                paintRoot.paint(g);
              }
            finally
              {
                g.dispose();
              }
          }

        // Reset the painting path.
        if (paintRoot != this)
          {
            for (int i = pIndex; i > 0; i--)
              {
                Component paintParent = (Component) components.get(i);
                if (paintParent instanceof JComponent)
                  ((JComponent) paintParent).paintChild = null;
              }
          }

        isRepainting = false;
      }
Tom Tromey committed
2288 2289 2290
  }

  /**
2291 2292 2293 2294
   * Returns <code>true</code> if the component is guaranteed to be painted
   * on top of others. This returns false by default and is overridden by
   * components like JMenuItem, JPopupMenu and JToolTip to return true for
   * added efficiency.
2295
   *
2296 2297
   * @return <code>true</code> if the component is guaranteed to be painted
   *         on top of others
2298
   */
2299
  boolean onTop()
2300
  {
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
    return false;
  }

  /**
   * This returns true when a component needs to force itself as a paint
   * origin. This is used for example in JViewport to make sure that it
   * gets to update its backbuffer.
   *
   * @return true when a component needs to force itself as a paint
   *         origin
   */
  boolean isPaintRoot()
  {
    return false;
2315
  }
2316

2317
  /**
2318 2319
   * Performs double buffered repainting.
   */
2320
  private void paintDoubleBuffered(int x, int y, int w, int h)
2321 2322 2323 2324
  {
    RepaintManager rm = RepaintManager.currentManager(this);

    // Paint on the offscreen buffer.
2325
    Component root = SwingUtilities.getRoot(this);
2326 2327 2328 2329 2330 2331 2332 2333
    Image buffer = rm.getVolatileOffscreenBuffer(this, root.getWidth(),
                                                 root.getHeight());

    // The volatile offscreen buffer may be null when that's not supported
    // by the AWT backend. Fall back to normal backbuffer in this case.
    if (buffer == null)
      buffer = rm.getOffscreenBuffer(this, root.getWidth(), root.getHeight());

2334
    //Rectangle targetClip = SwingUtilities.convertRectangle(this, r, root);
2335
    Graphics g2 = buffer.getGraphics();
2336
    clipAndTranslateGraphics(root, this, g2);
2337
    g2.clipRect(x, y, w, h);
2338
    g2 = getComponentGraphics(g2);
2339
    paintingDoubleBuffered = true;
2340 2341
    try
      {
2342 2343 2344 2345 2346 2347 2348 2349
        if (isRepainting) // Called from paintImmediately, go through paint().
          paint(g2);
        else // Called from paint() (AWT refresh), don't call it again.
          {
            paintComponent(g2);
            paintBorder(g2);
            paintChildren(g2);
          }
2350 2351 2352
      }
    finally
      {
2353
        paintingDoubleBuffered = false;
2354 2355
        g2.dispose();
      }
2356

2357
    // Paint the buffer contents on screen.
2358
    rm.commitBuffer(this, x, y, w, h);
2359 2360 2361
  }

  /**
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
   * Clips and translates the Graphics instance for painting on the double
   * buffer. This has to be done, so that it reflects the component clip of the
   * target component.
   *
   * @param root the root component (top-level container usually)
   * @param target the component to be painted
   * @param g the Graphics instance
   */
  private void clipAndTranslateGraphics(Component root, Component target,
                                        Graphics g)
  {
2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
    Component parent = target;
    int deltaX = 0;
    int deltaY = 0;
    while (parent != root)
      {
        deltaX += parent.getX();
        deltaY += parent.getY();
        parent = parent.getParent();
      }
    g.translate(deltaX, deltaY);
2383 2384 2385 2386
    g.clipRect(0, 0, target.getWidth(), target.getHeight());
  }

  /**
2387 2388
   * Performs normal painting without double buffering.
   *
2389
   * @param r the area that should be repainted
2390
   */
2391
  void paintSimple(Rectangle r)
2392
  {
2393
    Graphics g = getGraphics();
2394
    Graphics g2 = getComponentGraphics(g);
2395
    g2.setClip(r);
2396
    paint(g2);
2397 2398 2399
    g2.dispose();
    if (g != g2)
      g.dispose();
2400 2401 2402
  }

  /**
Tom Tromey committed
2403 2404 2405 2406 2407 2408 2409
   * Return a string representation for this component, for use in
   * debugging.
   *
   * @return A string describing this component.
   */
  protected String paramString()
  {
2410
    CPStringBuilder sb = new CPStringBuilder();
Tom Tromey committed
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
    sb.append(super.paramString());
    sb.append(",alignmentX=").append(getAlignmentX());
    sb.append(",alignmentY=").append(getAlignmentY());
    sb.append(",border=");
    if (getBorder() != null)
      sb.append(getBorder());
    sb.append(",maximumSize=");
    if (getMaximumSize() != null)
      sb.append(getMaximumSize());
    sb.append(",minimumSize=");
    if (getMinimumSize() != null)
      sb.append(getMinimumSize());
    sb.append(",preferredSize=");
    if (getPreferredSize() != null)
      sb.append(getPreferredSize());
    return sb.toString();
  }

  /**
   * A variant of {@link
   * #registerKeyboardAction(ActionListener,String,KeyStroke,int)} which
2432 2433 2434 2435 2436 2437 2438
   * provides <code>null</code> for the command name.
   * 
   * @param act  the action listener to notify when the keystroke occurs.
   * @param stroke  the key stroke.
   * @param cond  the condition (one of {@link #WHEN_FOCUSED}, 
   *     {@link #WHEN_IN_FOCUSED_WINDOW} and 
   *     {@link #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT}).
Tom Tromey committed
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
   */
  public void registerKeyboardAction(ActionListener act,
                                     KeyStroke stroke, 
                                     int cond)
  {
    registerKeyboardAction(act, null, stroke, cond);
  }

  /* 
   * There is some charmingly undocumented behavior sun seems to be using
   * to simulate the old register/unregister keyboard binding API. It's not
   * clear to me why this matters, but we shall endeavour to follow suit.
   *
   * Two main thing seem to be happening when you do registerKeyboardAction():
   * 
   *  - no actionMap() entry gets created, just an entry in inputMap()
   *
   *  - the inputMap() entry is a proxy class which invokes the the
   *  binding's actionListener as a target, and which clobbers the command
   *  name sent in the ActionEvent, providing the binding command name
   *  instead.
   *
   * This much you can work out just by asking the input and action maps
   * what they contain after making bindings, and watching the event which
   * gets delivered to the recipient. Beyond that, it seems to be a
   * sun-private solution so I will only immitate it as much as it matters
   * to external observers.
   */
  private static class ActionListenerProxy
    extends AbstractAction
  {
    ActionListener target;
    String bindingCommandName;

    public ActionListenerProxy(ActionListener li, 
                               String cmd)
    {
      target = li;
      bindingCommandName = cmd;
    }

    public void actionPerformed(ActionEvent e)
    {
      ActionEvent derivedEvent = new ActionEvent(e.getSource(),
                                                 e.getID(),
                                                 bindingCommandName,
                                                 e.getModifiers());
      target.actionPerformed(derivedEvent);
    }
  }

  
  /**
   * An obsolete method to register a keyboard action on this component.
   * You should use <code>getInputMap</code> and <code>getActionMap</code>
   * to fetch mapping tables from keystrokes to commands, and commands to
   * actions, respectively, and modify those mappings directly.
   *
Tom Tromey committed
2497 2498 2499 2500 2501
   * @param act The action to be registered
   * @param cmd The command to deliver in the delivered {@link
   *     java.awt.event.ActionEvent}
   * @param stroke The keystroke to register on
   * @param cond One of the values {@link #UNDEFINED_CONDITION},
Tom Tromey committed
2502 2503 2504 2505 2506
   *     {@link #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT}, {@link #WHEN_FOCUSED}, or
   *     {@link #WHEN_IN_FOCUSED_WINDOW}, indicating the condition which must
   *     be met for the action to be fired
   *
   * @see #unregisterKeyboardAction
Tom Tromey committed
2507 2508
   * @see #getConditionForKeyStroke
   * @see #resetKeyboardActions
Tom Tromey committed
2509 2510 2511 2512 2513 2514
   */
  public void registerKeyboardAction(ActionListener act, 
                                     String cmd,
                                     KeyStroke stroke, 
                                     int cond)
  {
2515 2516 2517
    ActionListenerProxy proxy = new ActionListenerProxy(act, cmd);
    getInputMap(cond).put(stroke, proxy);
    getActionMap().put(proxy, proxy);
Tom Tromey committed
2518 2519
  }

2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530
  /**
   * Sets the input map for the given condition.
   * 
   * @param condition  the condition (one of {@link #WHEN_FOCUSED}, 
   *     {@link #WHEN_IN_FOCUSED_WINDOW} and 
   *     {@link #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT}).
   * @param map  the map.
   * 
   * @throws IllegalArgumentException if <code>condition</code> is not one of
   *     the specified values.
   */
Tom Tromey committed
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
  public final void setInputMap(int condition, InputMap map)
  {
    enableEvents(AWTEvent.KEY_EVENT_MASK);
    switch (condition)
      {
      case WHEN_FOCUSED:
        inputMap_whenFocused = map;
        break;

      case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
        inputMap_whenAncestorOfFocused = map;
        break;

      case WHEN_IN_FOCUSED_WINDOW:
2545 2546 2547 2548 2549
        if (map != null && !(map instanceof ComponentInputMap))
            throw new 
              IllegalArgumentException("WHEN_IN_FOCUSED_WINDOW " + 
                                       "InputMap must be a ComponentInputMap");
        inputMap_whenInFocusedWindow = (ComponentInputMap)map;
Tom Tromey committed
2550 2551 2552 2553 2554 2555 2556 2557
        break;
        
      case UNDEFINED_CONDITION:
      default:
        throw new IllegalArgumentException();
      }
  }

2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
  /**
   * Returns the input map associated with this component for the given
   * state/condition.
   * 
   * @param condition  the state (one of {@link #WHEN_FOCUSED}, 
   *     {@link #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT} and 
   *     {@link #WHEN_IN_FOCUSED_WINDOW}).
   * 
   * @return The input map.
   * @throws IllegalArgumentException if <code>condition</code> is not one of 
   *             the specified values.
   * @since 1.3
   */
Tom Tromey committed
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587
  public final InputMap getInputMap(int condition)
  {
    enableEvents(AWTEvent.KEY_EVENT_MASK);
    switch (condition)
      {
      case WHEN_FOCUSED:
        if (inputMap_whenFocused == null)
          inputMap_whenFocused = new InputMap();
        return inputMap_whenFocused;

      case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
        if (inputMap_whenAncestorOfFocused == null)
          inputMap_whenAncestorOfFocused = new InputMap();
        return inputMap_whenAncestorOfFocused;

      case WHEN_IN_FOCUSED_WINDOW:
        if (inputMap_whenInFocusedWindow == null)
2588
          inputMap_whenInFocusedWindow = new ComponentInputMap(this);
Tom Tromey committed
2589 2590 2591 2592
        return inputMap_whenInFocusedWindow;

      case UNDEFINED_CONDITION:
      default:
2593 2594
        throw new IllegalArgumentException("Invalid 'condition' argument: " 
                                           + condition);
Tom Tromey committed
2595 2596 2597
      }
  }

2598 2599 2600 2601 2602 2603 2604 2605 2606
  /**
   * Returns the input map associated with this component for the 
   * {@link #WHEN_FOCUSED} state.
   * 
   * @return The input map.
   * 
   * @since 1.3
   * @see #getInputMap(int)
   */
Tom Tromey committed
2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
  public final InputMap getInputMap()
  {
    return getInputMap(WHEN_FOCUSED);
  }

  public final ActionMap getActionMap()
  {
    if (actionMap == null)
      actionMap = new ActionMap();
    return actionMap;
  }

  public final void setActionMap(ActionMap map)
  {
    actionMap = map;
  }

  /**
   * Return the condition that determines whether a registered action
   * occurs in response to the specified keystroke.
   *
2628 2629 2630
   * As of 1.3 KeyStrokes can be registered with multiple simultaneous
   * conditions.
   *
Tom Tromey committed
2631
   * @param ks The keystroke to return the condition of
Tom Tromey committed
2632 2633 2634 2635 2636
   *
   * @return One of the values {@link #UNDEFINED_CONDITION}, {@link
   *     #WHEN_ANCESTOR_OF_FOCUSED_COMPONENT}, {@link #WHEN_FOCUSED}, or {@link
   *     #WHEN_IN_FOCUSED_WINDOW}
   *
Tom Tromey committed
2637
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)   
Tom Tromey committed
2638
   * @see #unregisterKeyboardAction   
Tom Tromey committed
2639
   * @see #resetKeyboardActions
Tom Tromey committed
2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659
   */
  public int getConditionForKeyStroke(KeyStroke ks)
  {
    if (inputMap_whenFocused != null 
        && inputMap_whenFocused.get(ks) != null)
      return WHEN_FOCUSED;
    else if (inputMap_whenAncestorOfFocused != null 
             && inputMap_whenAncestorOfFocused.get(ks) != null)
      return WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
    else if (inputMap_whenInFocusedWindow != null 
             && inputMap_whenInFocusedWindow.get(ks) != null)
      return WHEN_IN_FOCUSED_WINDOW;
    else
      return UNDEFINED_CONDITION;
  }

  /**
   * Get the ActionListener (typically an {@link Action} object) which is
   * associated with a particular keystroke. 
   *
Tom Tromey committed
2660
   * @param ks The keystroke to retrieve the action of
Tom Tromey committed
2661 2662 2663 2664 2665
   *
   * @return The action associated with the specified keystroke
   */
  public ActionListener getActionForKeyStroke(KeyStroke ks)
  {
2666 2667 2668 2669 2670 2671
    Object key = getInputMap(JComponent.WHEN_FOCUSED).get(ks);
    if (key == null)
      key = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).get(ks);
    if (key == null)
      key = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(ks);
    if (key != null)
Tom Tromey committed
2672
      {
2673 2674 2675 2676
        if (key instanceof ActionListenerProxy)
          return ((ActionListenerProxy) key).target;
        else
          return getActionMap().get(key);
Tom Tromey committed
2677 2678 2679 2680 2681 2682 2683 2684 2685
      }
    return null;
  }

  /**
   * A hook for subclasses which want to customize event processing.
   */
  protected void processComponentKeyEvent(KeyEvent e)
  {
2686
    // This method does nothing, it is meant to be overridden by subclasses.
Tom Tromey committed
2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702
  }

  /**
   * Override the default key dispatch system from Component to hook into
   * the swing {@link InputMap} / {@link ActionMap} system.
   *
   * See <a
   * href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">
   * this report</a> for more details, it's somewhat complex.
   */
  protected void processKeyEvent(KeyEvent e)
  {
    // let the AWT event processing send KeyEvents to registered listeners
    super.processKeyEvent(e);
    processComponentKeyEvent(e);

Tom Tromey committed
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
    if (e.isConsumed())
      return;

    // Input maps are checked in this order:
    // 1. The focused component's WHEN_FOCUSED map is checked.
    // 2. The focused component's WHEN_ANCESTOR_OF_FOCUSED_COMPONENT map.
    // 3. The WHEN_ANCESTOR_OF_FOCUSED_COMPONENT maps of the focused
    //    component's parent, then its parent's parent, and so on.
    //    Note: Input maps for disabled components are skipped.
    // 4. The WHEN_IN_FOCUSED_WINDOW maps of all the enabled components in
    //    the focused window are searched.
    
2715 2716 2717 2718
    KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
    boolean pressed = e.getID() == KeyEvent.KEY_PRESSED;
    
    if (processKeyBinding(keyStroke, e, WHEN_FOCUSED, pressed))
Tom Tromey committed
2719
      {
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
        // This is step 1 from above comment.
        e.consume();
        return;
      }
    else if (processKeyBinding
             (keyStroke, e, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
      {
        // This is step 2 from above comment.
        e.consume();
        return;
      }
    
    // This is step 3 from above comment.
    Container current = getParent();    
    while (current != null)
      { 
        // If current is a JComponent, see if it handles the event in its
        // WHEN_ANCESTOR_OF_FOCUSED_COMPONENT maps.
        if ((current instanceof JComponent) && 
            ((JComponent)current).processKeyBinding 
            (keyStroke, e,WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
Tom Tromey committed
2741
          {
2742 2743 2744 2745 2746 2747 2748
            e.consume();
            return;
          }     
        
        // Stop when we've tried a top-level container and it didn't handle it
        if (current instanceof Window || current instanceof Applet)
          break;        
Tom Tromey committed
2749
        
2750 2751
        // Move up the hierarchy
        current = current.getParent();
Tom Tromey committed
2752
      }
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
    
    // Current being null means the JComponent does not currently have a
    // top-level ancestor, in which case we don't need to check 
    // WHEN_IN_FOCUSED_WINDOW bindings.
    if (current == null || e.isConsumed())
      return;
    
    // This is step 4 from above comment.  KeyboardManager maintains mappings
    // related to WHEN_IN_FOCUSED_WINDOW bindings so that we don't have to 
    // traverse the containment hierarchy each time.
    if (KeyboardManager.getManager().processKeyStroke(current, keyStroke, e))
      e.consume();
Tom Tromey committed
2765 2766 2767 2768 2769 2770
  }

  protected boolean processKeyBinding(KeyStroke ks,
                                      KeyEvent e,
                                      int condition,
                                      boolean pressed)
2771
  {
Tom Tromey committed
2772 2773 2774
    if (isEnabled())
      {
        Action act = null;
2775
        Object cmd = null;
Tom Tromey committed
2776 2777 2778
        InputMap map = getInputMap(condition);
        if (map != null)
          {
2779
            cmd = map.get(ks);
Tom Tromey committed
2780 2781 2782 2783 2784
            if (cmd != null)
              {
                if (cmd instanceof ActionListenerProxy)
                  act = (Action) cmd;
                else 
2785
                  act = getActionMap().get(cmd);
Tom Tromey committed
2786 2787 2788
              }
          }
        if (act != null && act.isEnabled())
2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
          {
            // Need to synchronize here so we don't get in trouble with
            // our __command__ hack.
            synchronized (act)
              {
                // We add the command as value to the action, so that
                // the action can later determine the command with which it
                // was called. This is undocumented, but shouldn't affect
                // compatibility. It allows us to use only one Action instance
                // to do the work for all components of one type, instead of
                // having loads of small Actions. This effectivly saves startup
                // time of Swing.
                act.putValue("__command__", cmd);
                return SwingUtilities.notifyAction(act, ks, e, this,
                                                   e.getModifiers());
              }
          }
Tom Tromey committed
2806 2807 2808 2809 2810 2811 2812
      }
    return false;
  }
  
  /**
   * Remove a keyboard action registry.
   *
Tom Tromey committed
2813
   * @param aKeyStroke The keystroke to unregister
Tom Tromey committed
2814
   *
Tom Tromey committed
2815 2816 2817
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
   * @see #getConditionForKeyStroke
   * @see #resetKeyboardActions
Tom Tromey committed
2818 2819 2820
   */
  public void unregisterKeyboardAction(KeyStroke aKeyStroke)
  {
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
    ActionMap am = getActionMap();
    // This loops through the conditions WHEN_FOCUSED,
    // WHEN_ANCESTOR_OF_FOCUSED_COMPONENT and WHEN_IN_FOCUSED_WINDOW.
    for (int cond = 0; cond < 3; cond++)
      {
        InputMap im = getInputMap(cond);
        if (im != null)
          {
            Object action = im.get(aKeyStroke);
            if (action != null && am != null)
              am.remove(action);
            im.remove(aKeyStroke);
          }
      }
Tom Tromey committed
2835 2836 2837 2838 2839 2840
  }


  /**
   * Reset all keyboard action registries.
   *
Tom Tromey committed
2841
   * @see #registerKeyboardAction(ActionListener, KeyStroke, int)
Tom Tromey committed
2842
   * @see #unregisterKeyboardAction
Tom Tromey committed
2843
   * @see #getConditionForKeyStroke
Tom Tromey committed
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
   */
  public void resetKeyboardActions()
  {
    if (inputMap_whenFocused != null)
      inputMap_whenFocused.clear();
    if (inputMap_whenAncestorOfFocused != null)
      inputMap_whenAncestorOfFocused.clear();
    if (inputMap_whenInFocusedWindow != null)
      inputMap_whenInFocusedWindow.clear();
    if (actionMap != null)
      actionMap.clear();
  }

  /**
   * Mark the described region of this component as dirty in the current
   * {@link RepaintManager}. This will queue an asynchronous repaint using
   * the system painting thread in the near future.
   *
   * @param tm ignored
   * @param x coordinate of the region to mark as dirty
   * @param y coordinate of the region to mark as dirty
   * @param width dimension of the region to mark as dirty
   * @param height dimension of the region to mark as dirty
   */
  public void repaint(long tm, int x, int y, int width, int height)
  {
2870 2871
     RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width,
                                                        height);
Tom Tromey committed
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
  }

  /**
   * Mark the described region of this component as dirty in the current
   * {@link RepaintManager}. This will queue an asynchronous repaint using
   * the system painting thread in the near future.
   *
   * @param r The rectangle to mark as dirty
   */
  public void repaint(Rectangle r)
  {
2883 2884
    RepaintManager.currentManager(this).addDirtyRegion(this, r.x, r.y, r.width,
                                                       r.height);
Tom Tromey committed
2885 2886 2887 2888 2889 2890
  }

  /**
   * Request focus on the default component of this component's {@link
   * FocusTraversalPolicy}.
   *
Tom Tromey committed
2891
   * @return The result of {@link #requestFocus()}
Tom Tromey committed
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
   *
   * @deprecated Use {@link #requestFocus()} on the default component provided
   *     from the {@link FocusTraversalPolicy} instead.
   */
  public boolean requestDefaultFocus()
  {
    return false;
  }

  /**
   * Queue a an invalidation and revalidation of this component, using 
   * {@link RepaintManager#addInvalidComponent}.
   */
  public void revalidate()
  {
2907 2908 2909 2910 2911
    // As long as we don't have a parent we don't need to do any layout, since
    // this is done anyway as soon as we get connected to a parent.
    if (getParent() == null)
      return;

2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
    if (! EventQueue.isDispatchThread())
      SwingUtilities.invokeLater(new Runnable()
        {
          public void run()
          {
            revalidate();
          }
        });
    else
      {
        invalidate();
        RepaintManager.currentManager(this).addInvalidComponent(this);
      }
Tom Tromey committed
2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
  }

  /**
   * Calls <code>scrollRectToVisible</code> on the component's parent. 
   * Components which can service this call should override.
   *
   * @param r The rectangle to make visible
   */
  public void scrollRectToVisible(Rectangle r)
  {
2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
    // Search nearest JComponent.
    int xOffs = getX();
    int yOffs = getY();
    Component p;
    for (p = getParent(); p != null && ! (p instanceof JComponent);
         p = p.getParent())
      {
        xOffs += p.getX();
        yOffs += p.getY();
      }
    if (p != null)
      {
        r.x += xOffs;
        r.y += yOffs;
        JComponent jParent = (JComponent) p;
        jParent.scrollRectToVisible(r);
        r.x -= xOffs;
        r.y -= yOffs;
      }
Tom Tromey committed
2954 2955 2956 2957 2958 2959 2960 2961 2962
  }

  /**
   * Set the value of the {@link #alignmentX} property.
   *
   * @param a The new value of the property
   */
  public void setAlignmentX(float a)
  {
2963 2964 2965 2966 2967 2968
    if (a < 0.0F)
      alignmentX = 0.0F;
    else if (a > 1.0)
      alignmentX = 1.0F;
    else
      alignmentX = a;
Tom Tromey committed
2969 2970 2971 2972 2973 2974 2975 2976 2977
  }

  /**
   * Set the value of the {@link #alignmentY} property.
   *
   * @param a The new value of the property
   */
  public void setAlignmentY(float a)
  {
2978 2979 2980 2981 2982 2983
    if (a < 0.0F)
      alignmentY = 0.0F;
    else if (a > 1.0)
      alignmentY = 1.0F;
    else
      alignmentY = a;
Tom Tromey committed
2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
  }

  /**
   * Set the value of the {@link #autoscrolls} property.
   *
   * @param a The new value of the property
   */
  public void setAutoscrolls(boolean a)
  {
    autoscrolls = a;
2994
    clientAutoscrollsSet = true;
Tom Tromey committed
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017
  }

  /**
   * Set the value of the {@link #debugGraphicsOptions} property.
   *
   * @param debugOptions The new value of the property
   */
  public void setDebugGraphicsOptions(int debugOptions)
  {
    debugGraphicsOptions = debugOptions;
  }

  /**
   * Set the value of the {@link #doubleBuffered} property.
   *
   * @param db The new value of the property
   */
  public void setDoubleBuffered(boolean db)
  {
    doubleBuffered = db;
  }

  /**
Tom Tromey committed
3018
   * Set the value of the <code>enabled</code> property.
Tom Tromey committed
3019 3020 3021 3022 3023
   *
   * @param enable The new value of the property
   */
  public void setEnabled(boolean enable)
  {
3024 3025
    if (enable == isEnabled())
      return;
Tom Tromey committed
3026
    super.setEnabled(enable);
3027 3028
    firePropertyChange("enabled", !enable, enable);
    repaint();
Tom Tromey committed
3029 3030 3031
  }

  /**
Tom Tromey committed
3032
   * Set the value of the <code>font</code> property.
Tom Tromey committed
3033 3034 3035 3036 3037
   *
   * @param f The new value of the property
   */
  public void setFont(Font f)
  {
3038 3039
    if (f == getFont())
      return;
Tom Tromey committed
3040
    super.setFont(f);
3041 3042
    revalidate();
    repaint();
Tom Tromey committed
3043 3044 3045
  }

  /**
Tom Tromey committed
3046
   * Set the value of the <code>background</code> property.
Tom Tromey committed
3047 3048 3049 3050 3051
   *
   * @param bg The new value of the property
   */
  public void setBackground(Color bg)
  {
3052 3053
    if (bg == getBackground())
      return;
Tom Tromey committed
3054
    super.setBackground(bg);
3055
    repaint();
Tom Tromey committed
3056 3057 3058
  }

  /**
Tom Tromey committed
3059
   * Set the value of the <code>foreground</code> property.
Tom Tromey committed
3060 3061 3062 3063 3064
   *
   * @param fg The new value of the property
   */
  public void setForeground(Color fg)
  {
3065 3066
    if (fg == getForeground())
      return;
Tom Tromey committed
3067
    super.setForeground(fg);
3068
    repaint();
Tom Tromey committed
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
  }

  /**
   * Set the specified component to be the next component in the 
   * focus cycle, overriding the {@link FocusTraversalPolicy} for
   * this component.
   *
   * @param aComponent The component to set as the next focusable
   *
   * @deprecated Use FocusTraversalPolicy instead
   */
  public void setNextFocusableComponent(Component aComponent)
  {
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104
    Container focusRoot = this;
    if (! this.isFocusCycleRoot())
      focusRoot = getFocusCycleRootAncestor();

    FocusTraversalPolicy policy  = focusRoot.getFocusTraversalPolicy();
    if (policy instanceof CompatibilityFocusTraversalPolicy)
      {
        policy = new CompatibilityFocusTraversalPolicy(policy);
        focusRoot.setFocusTraversalPolicy(policy);
      }
    CompatibilityFocusTraversalPolicy p =
      (CompatibilityFocusTraversalPolicy) policy;

    Component old = getNextFocusableComponent();
    if (old != null)
      {
        p.removeNextFocusableComponent(this, old);
      }

    if (aComponent != null)
      {
        p.addNextFocusableComponent(this, aComponent);
      }
Tom Tromey committed
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121
  }

  /**
   * Set the value of the {@link #requestFocusEnabled} property.
   *
   * @param e The new value of the property
   */
  public void setRequestFocusEnabled(boolean e)
  {
    requestFocusEnabled = e;
  }

  /**
   * Get the value of the {@link #transferHandler} property.
   *
   * @return The current value of the property
   *
Tom Tromey committed
3122
   * @see #setTransferHandler
Tom Tromey committed
3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134
   */

  public TransferHandler getTransferHandler()
  {
    return transferHandler;
  }

  /**
   * Set the value of the {@link #transferHandler} property.
   *
   * @param newHandler The new value of the property
   *
Tom Tromey committed
3135
   * @see #getTransferHandler
Tom Tromey committed
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
   */

  public void setTransferHandler(TransferHandler newHandler)
  {
    if (transferHandler == newHandler)
      return;

    TransferHandler oldHandler = transferHandler;
    transferHandler = newHandler;
    firePropertyChange("transferHandler", oldHandler, newHandler);
  }

  /**
3149 3150 3151
   * Set if the component should paint all pixels withing its bounds.
   * If this property is set to false, the component expects the cleared
   * background.
Tom Tromey committed
3152
   *
3153 3154
   * @param isOpaque if true, paint all pixels. If false, expect the clean
   * background. 
Tom Tromey committed
3155 3156 3157 3158 3159 3160 3161
   *
   * @see ComponentUI#update
   */
  public void setOpaque(boolean isOpaque)
  {
    boolean oldOpaque = opaque;
    opaque = isOpaque;
3162
    clientOpaqueSet = true;
Tom Tromey committed
3163 3164 3165 3166 3167 3168
    firePropertyChange("opaque", oldOpaque, opaque);
  }

  /**
   * Set the value of the visible property.
   *
3169 3170 3171
   * If the value is changed, then the AncestorListeners of this component
   * and all its children (recursivly) are notified.
   *
Tom Tromey committed
3172 3173 3174 3175
   * @param v The new value of the property
   */
  public void setVisible(boolean v)
  {
3176 3177 3178 3179
    // No need to do anything if the actual value doesn't change.
    if (isVisible() == v)
      return;

Tom Tromey committed
3180
    super.setVisible(v);
3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191

    // Notify AncestorListeners.
    if (v == true)
      fireAncestorEvent(this, AncestorEvent.ANCESTOR_ADDED);
    else
      fireAncestorEvent(this, AncestorEvent.ANCESTOR_REMOVED);

    Container parent = getParent();
    if (parent != null)
      parent.repaint(getX(), getY(), getWidth(), getHeight());
    revalidate();
Tom Tromey committed
3192 3193 3194
  }

  /**
Tom Tromey committed
3195
   * Call {@link #paint}. 
Tom Tromey committed
3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
   * 
   * @param g The graphics context to paint into
   */
  public void update(Graphics g)
  {
    paint(g);
  }

  /**
   * Get the value of the UIClassID property. This property should be a key
   * in the {@link UIDefaults} table managed by {@link UIManager}, the
   * value of which is the name of a class to load for the component's
Tom Tromey committed
3208
   * {@link #ui} property.
Tom Tromey committed
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
   *
   * @return A "symbolic" name which will map to a class to use for the
   * component's UI, such as <code>"ComponentUI"</code>
   *
   * @see #setUI
   * @see #updateUI
   */
  public String getUIClassID()
  {
    return "ComponentUI";
  }

  /**
Tom Tromey committed
3222 3223 3224 3225
   * Install a new UI delegate as the component's {@link #ui} property. In
   * the process, this will call {@link ComponentUI#uninstallUI} on any
   * existing value for the {@link #ui} property, and {@link
   * ComponentUI#installUI} on the new UI delegate.
Tom Tromey committed
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
   *
   * @param newUI The new UI delegate to install
   *
   * @see #updateUI
   * @see #getUIClassID
   */
  protected void setUI(ComponentUI newUI)
  {
    if (ui != null)
      ui.uninstallUI(this);

    ComponentUI oldUI = ui;
    ui = newUI;

    if (ui != null)
      ui.installUI(this);

    firePropertyChange("UI", oldUI, newUI);
3244 3245
    revalidate();
    repaint();
Tom Tromey committed
3246 3247 3248 3249 3250 3251
  }

  /**
   * This method should be overridden in subclasses. In JComponent, the
   * method does nothing. In subclasses, it should a UI delegate
   * (corresponding to the symbolic name returned from {@link
Tom Tromey committed
3252
   * #getUIClassID}) from the {@link UIManager}, and calls {@link #setUI}
Tom Tromey committed
3253 3254 3255 3256
   * with the new delegate.
   */
  public void updateUI()
  {
3257
    // Nothing to do here.
Tom Tromey committed
3258 3259
  }

3260 3261 3262 3263 3264 3265 3266 3267 3268
  /**
   * Returns the locale used as the default for all new components.  The 
   * default value is {@link Locale#getDefault()} (that is, the platform
   * default locale).
   * 
   * @return The locale (never <code>null</code>).
   * 
   * @see #setDefaultLocale(Locale)
   */
Tom Tromey committed
3269 3270
  public static Locale getDefaultLocale()
  {
3271 3272
    if (defaultLocale == null)
      defaultLocale = Locale.getDefault();
Tom Tromey committed
3273 3274 3275
    return defaultLocale;
  }
  
3276 3277 3278 3279 3280 3281 3282
  /**
   * Sets the locale to be used as the default for all new components.  If this
   * is set to <code>null</code>, the {@link #getDefaultLocale()} method will
   * return the platform default locale.
   * 
   * @param l  the locale (<code>null</code> permitted).
   */
Tom Tromey committed
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344
  public static void setDefaultLocale(Locale l)
  {
    defaultLocale = l;
  }
  
  /**
   * Returns the currently set input verifier for this component.
   *
   * @return the input verifier, or <code>null</code> if none
   */
  public InputVerifier getInputVerifier()
  {
    return inputVerifier;
  }

  /**
   * Sets the input verifier to use by this component.
   *
   * @param verifier the input verifier, or <code>null</code>
   */
  public void setInputVerifier(InputVerifier verifier)
  {
    InputVerifier oldVerifier = inputVerifier;
    inputVerifier = verifier;
    firePropertyChange("inputVerifier", oldVerifier, verifier);
  }

  /**
   * @since 1.3
   */
  public boolean getVerifyInputWhenFocusTarget()
  {
    return verifyInputWhenFocusTarget;
  }

  /**
   * @since 1.3
   */
  public void setVerifyInputWhenFocusTarget(boolean verifyInputWhenFocusTarget)
  {
    if (this.verifyInputWhenFocusTarget == verifyInputWhenFocusTarget)
      return;

    this.verifyInputWhenFocusTarget = verifyInputWhenFocusTarget;
    firePropertyChange("verifyInputWhenFocusTarget",
                       ! verifyInputWhenFocusTarget,
                       verifyInputWhenFocusTarget);
  }

  /**
   * Requests that this component gets the input focus if the
   * requestFocusEnabled property is set to <code>true</code>.
   * This also means that this component's top-level window becomes
   * the focused window, if that is not already the case.
   *
   * The preconditions that have to be met to become a focus owner is that
   * the component must be displayable, visible and focusable.
   *
   * Note that this signals only a request for becoming focused. There are
   * situations in which it is not possible to get the focus. So developers
   * should not assume that the component has the focus until it receives
   * a {@link java.awt.event.FocusEvent} with a value of
Tom Tromey committed
3345
   * {@link java.awt.event.FocusEvent#FOCUS_GAINED}.
Tom Tromey committed
3346
   *
Tom Tromey committed
3347
   * @see Component#requestFocus()
Tom Tromey committed
3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359
   */
  public void requestFocus()
  {
    if (isRequestFocusEnabled())
      super.requestFocus();
  }

  /**
   * This method is overridden to make it public so that it can be used
   * by look and feel implementations.
   *
   * You should not use this method directly. Instead you are strongly
Tom Tromey committed
3360 3361
   * encouraged to call {@link #requestFocus()} or 
   * {@link #requestFocusInWindow()} instead.
Tom Tromey committed
3362 3363 3364 3365 3366 3367
   *
   * @param temporary if the focus change is temporary
   *
   * @return <code>false</code> if the focus change request will definitly
   *     fail, <code>true</code> if it will likely succeed
   *
Tom Tromey committed
3368
   * @see Component#requestFocus(boolean)
Tom Tromey committed
3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
   *
   * @since 1.4
   */
  public boolean requestFocus(boolean temporary)
  {
    return super.requestFocus(temporary);
  }

  /**
   * Requests that this component gets the input focus if the top level
   * window that contains this component has the focus and the
   * requestFocusEnabled property is set to <code>true</code>.
   *
   * The preconditions that have to be met to become a focus owner is that
   * the component must be displayable, visible and focusable.
   *
   * Note that this signals only a request for becoming focused. There are
   * situations in which it is not possible to get the focus. So developers
   * should not assume that the component has the focus until it receives
   * a {@link java.awt.event.FocusEvent} with a value of
Tom Tromey committed
3389
   * {@link java.awt.event.FocusEvent#FOCUS_GAINED}.
Tom Tromey committed
3390 3391 3392 3393
   *
   * @return <code>false</code> if the focus change request will definitly
   *     fail, <code>true</code> if it will likely succeed
   *
Tom Tromey committed
3394
   * @see Component#requestFocusInWindow()
Tom Tromey committed
3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408
   */
  public boolean requestFocusInWindow()
  {
    if (isRequestFocusEnabled())
      return super.requestFocusInWindow();
    else
      return false;
  }

  /**
   * This method is overridden to make it public so that it can be used
   * by look and feel implementations.
   *
   * You should not use this method directly. Instead you are strongly
Tom Tromey committed
3409 3410
   * encouraged to call {@link #requestFocus()} or 
   * {@link #requestFocusInWindow()} instead.
Tom Tromey committed
3411 3412 3413 3414 3415 3416
   *
   * @param temporary if the focus change is temporary
   *
   * @return <code>false</code> if the focus change request will definitly
   *     fail, <code>true</code> if it will likely succeed
   *
Tom Tromey committed
3417
   * @see Component#requestFocus(boolean)
Tom Tromey committed
3418 3419 3420
   *
   * @since 1.4
   */
3421
  protected boolean requestFocusInWindow(boolean temporary)
Tom Tromey committed
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441
  {
    return super.requestFocusInWindow(temporary);
  }

  /**
   * Receives notification if this component is added to a parent component.
   *
   * Notification is sent to all registered AncestorListeners about the
   * new parent.
   *
   * This method sets up ActionListeners for all registered KeyStrokes of
   * this component in the chain of parent components.
   *
   * A PropertyChange event is fired to indicate that the ancestor property
   * has changed.
   *
   * This method is used internally and should not be used in applications.
   */
  public void addNotify()
  {
3442 3443 3444 3445 3446 3447 3448 3449 3450
    // Register the WHEN_IN_FOCUSED_WINDOW keyboard bindings
    // Note that here we unregister all bindings associated with
    // this component and then re-register them.  This may be more than
    // necessary if the top-level ancestor hasn't changed.  Should
    // maybe improve this.
    KeyboardManager km = KeyboardManager.getManager();
    km.clearBindingsForComp(this);
    km.registerEntireMap((ComponentInputMap)
                         this.getInputMap(WHEN_IN_FOCUSED_WINDOW));
Tom Tromey committed
3451 3452
    super.addNotify();

3453 3454
    // Notify AncestorListeners.
    fireAncestorEvent(this, AncestorEvent.ANCESTOR_ADDED);
Tom Tromey committed
3455 3456

    // fire property change event for 'ancestor'
3457
    firePropertyChange("ancestor", null, getParent());
Tom Tromey committed
3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
  }

  /**
   * Receives notification that this component no longer has a parent.
   *
   * This method sends an AncestorEvent to all registered AncestorListeners,
   * notifying them that the parent is gone.
   *
   * The keybord actions of this component are removed from the parent and
   * its ancestors.
   *
   * A PropertyChangeEvent is fired to indicate that the 'ancestor' property
   * has changed.
   *
   * This method is called before the component is actually removed from
Tom Tromey committed
3473 3474
   * its parent, so the parent is still visible through 
   * {@link Component#getParent}.
Tom Tromey committed
3475 3476 3477 3478 3479
   */
  public void removeNotify()
  {
    super.removeNotify();

3480
    KeyboardManager.getManager().clearBindingsForComp(this);
3481 3482 3483
    
    // Notify ancestor listeners.
    fireAncestorEvent(this, AncestorEvent.ANCESTOR_REMOVED);
Tom Tromey committed
3484 3485

    // fire property change event for 'ancestor'
3486
    firePropertyChange("ancestor", getParent(), null);
Tom Tromey committed
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
  }

  /**
   * Returns <code>true</code> if the coordinates (x, y) lie within
   * the bounds of this component and <code>false</code> otherwise.
   * x and y are relative to the coordinate space of the component.
   *
   * @param x the X coordinate of the point to check
   * @param y the Y coordinate of the point to check
   *
   * @return <code>true</code> if the specified point lies within the bounds
   *     of this component, <code>false</code> otherwise
   */
  public boolean contains(int x, int y)
  {
    if (ui == null)
      return super.contains(x, y);
    else
      return ui.contains(this, x, y);
  }

  /**
   * Disables this component.
   *
   * @deprecated replaced by {@link #setEnabled(boolean)}
   */
  public void disable()
  {
    super.disable();
  }

  /**
   * Enables this component.
   *
   * @deprecated replaced by {@link #setEnabled(boolean)}
   */
  public void enable()
  {
    super.enable();
  }

  /**
   * Returns the Graphics context for this component. This can be used
   * to draw on a component.
   *
   * @return the Graphics context for this component
   */
  public Graphics getGraphics()
  {
    return super.getGraphics();
  }

  /**
   * Returns the X coordinate of the upper left corner of this component.
   * Prefer this method over {@link #getBounds} or {@link #getLocation}
   * because it does not cause any heap allocation.
   *
   * @return the X coordinate of the upper left corner of the component
   */
  public int getX()
  {
    return super.getX();
  }

  /**
   * Returns the Y coordinate of the upper left corner of this component.
   * Prefer this method over {@link #getBounds} or {@link #getLocation}
   * because it does not cause any heap allocation.
   *
   * @return the Y coordinate of the upper left corner of the component
   */
  public int getY()
  {
    return super.getY();
  }

  /**
   * Returns the height of this component. Prefer this method over
   * {@link #getBounds} or {@link #getSize} because it does not cause
   * any heap allocation.
   *
   * @return the height of the component
   */
  public int getHeight()
  {
    return super.getHeight();
  }

  /**
   * Returns the width of this component. Prefer this method over
   * {@link #getBounds} or {@link #getSize} because it does not cause
   * any heap allocation.
   *
   * @return the width of the component
   */
  public int getWidth()
  {
    return super.getWidth();
  }

  /**
   * Prints this component to the given Graphics context. A call to this
   * method results in calls to the methods {@link #printComponent},
Tom Tromey committed
3590
   * {@link #printBorder} and {@link #printChildren} in this order.
Tom Tromey committed
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
   *
   * Double buffering is temporarily turned off so the painting goes directly
   * to the supplied Graphics context.
   *
   * @param g the Graphics context to print onto
   */
  public void print(Graphics g)
  {
    boolean doubleBufferState = isDoubleBuffered();
    setDoubleBuffered(false);
    printComponent(g);
    printBorder(g);
    printChildren(g);
    setDoubleBuffered(doubleBufferState);
  }

  /**
   * Prints this component to the given Graphics context. This invokes
   * {@link #print}.
   *
   * @param g the Graphics context to print onto
   */
  public void printAll(Graphics g)
  {
    print(g);
  }

  /**
   * Prints this component to the specified Graphics context. The default
   * behaviour is to invoke {@link #paintComponent}. Override this
   * if you want special behaviour for printing.
   *
   * @param g the Graphics context to print onto
   *
   * @since 1.3
   */
3627
  protected void printComponent(Graphics g)
Tom Tromey committed
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
  {
    paintComponent(g);
  }

  /**
   * Print this component's children to the specified Graphics context.
   * The default behaviour is to invoke {@link #paintChildren}. Override this
   * if you want special behaviour for printing.
   *
   * @param g the Graphics context to print onto
   *
   * @since 1.3
   */
3641
  protected void printChildren(Graphics g)
Tom Tromey committed
3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654
  {
    paintChildren(g);
  }

  /**
   * Print this component's border to the specified Graphics context.
   * The default behaviour is to invoke {@link #paintBorder}. Override this
   * if you want special behaviour for printing.
   *
   * @param g the Graphics context to print onto
   *
   * @since 1.3
   */
3655
  protected void printBorder(Graphics g)
Tom Tromey committed
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679
  {
    paintBorder(g);
  }

  /**
   * Processes mouse motion event, like dragging and moving.
   *
   * @param ev the MouseEvent describing the mouse motion
   */
  protected void processMouseMotionEvent(MouseEvent ev)
  {
    super.processMouseMotionEvent(ev);
  }

  /**
   * Moves and resizes the component.
   *
   * @param x the new horizontal location
   * @param y the new vertial location
   * @param w the new width
   * @param h the new height
   */
  public void reshape(int x, int y, int w, int h)
  {
3680 3681
    int oldX = getX();
    int oldY = getY();
Tom Tromey committed
3682
    super.reshape(x, y, w, h);
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719
    // Notify AncestorListeners.
    if (oldX != getX() || oldY != getY())
      fireAncestorEvent(this, AncestorEvent.ANCESTOR_MOVED);
  }

  /**
   * Fires an AncestorEvent to this component's and all of its child
   * component's AncestorListeners.
   *
   * @param ancestor the component that triggered the event
   * @param id the kind of ancestor event that should be fired
   */
  void fireAncestorEvent(JComponent ancestor, int id)
  {
    // Fire event for registered ancestor listeners of this component.
    AncestorListener[] listeners = getAncestorListeners();
    if (listeners.length > 0)
      {
        AncestorEvent ev = new AncestorEvent(this, id,
                                             ancestor, ancestor.getParent());
        for (int i = 0; i < listeners.length; i++)
          {
            switch (id)
              {
              case AncestorEvent.ANCESTOR_MOVED:
                listeners[i].ancestorMoved(ev);
                break;
              case AncestorEvent.ANCESTOR_ADDED:
                listeners[i].ancestorAdded(ev);
                break;
              case AncestorEvent.ANCESTOR_REMOVED:
                listeners[i].ancestorRemoved(ev);
                break;
              }
          }
      }
    // Dispatch event to all children.
3720 3721
    int numChildren = getComponentCount();
    for (int i = 0; i < numChildren; i++)
3722
      {
3723 3724
        Component child = getComponent(i);
        if (! (child instanceof JComponent))
3725
          continue;
3726
        JComponent jc = (JComponent) child;
3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
        jc.fireAncestorEvent(ancestor, id);
      }
  }
  
  /**
   * This is the method that gets called when the WHEN_IN_FOCUSED_WINDOW map
   * is changed.
   *
   * @param changed the JComponent associated with the WHEN_IN_FOCUSED_WINDOW
   *        map
   */
  void updateComponentInputMap(ComponentInputMap changed)
  {
    // Since you can change a component's input map via
    // setInputMap, we have to check if <code>changed</code>
    // is still in our WHEN_IN_FOCUSED_WINDOW map hierarchy
    InputMap curr = getInputMap(WHEN_IN_FOCUSED_WINDOW);
    while (curr != null && curr != changed)
      curr = curr.getParent();
    
    // If curr is null then changed is not in the hierarchy
    if (curr == null)
      return;
    
    // Now we have to update the keyboard manager's hashtable
    KeyboardManager km = KeyboardManager.getManager();
    
    // This is a poor strategy, should be improved.  We currently 
    // delete all the old bindings for the component and then register
    // the current bindings.
    km.clearBindingsForComp(changed.getComponent());
    km.registerEntireMap((ComponentInputMap) 
                         getInputMap(WHEN_IN_FOCUSED_WINDOW));
Tom Tromey committed
3760
  }
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800

  /**
   * Helper method for
   * {@link LookAndFeel#installProperty(JComponent, String, Object)}.
   * 
   * @param propertyName the name of the property
   * @param value the value of the property
   *
   * @throws IllegalArgumentException if the specified property cannot be set
   *         by this method
   * @throws ClassCastException if the property value does not match the
   *         property type
   * @throws NullPointerException if <code>c</code> or
   *         <code>propertyValue</code> is <code>null</code>
   */
  void setUIProperty(String propertyName, Object value)
  {
    if (propertyName.equals("opaque"))
      {
        if (! clientOpaqueSet)
          {
            setOpaque(((Boolean) value).booleanValue());
            clientOpaqueSet = false;
          }
      }
    else if (propertyName.equals("autoscrolls"))
      {
        if (! clientAutoscrollsSet)
          {
            setAutoscrolls(((Boolean) value).booleanValue());
            clientAutoscrollsSet = false;
          }
      }
    else
      {
        throw new IllegalArgumentException
            ("Unsupported property for LookAndFeel.installProperty(): "
             + propertyName);
      }
  }
Tom Tromey committed
3801
}