View Javadoc
1   /*
2    * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4    *
5    * This code is free software; you can redistribute it and/or modify it
6    * under the terms of the GNU General Public License version 2 only, as
7    * published by the Free Software Foundation.  Oracle designates this
8    * particular file as subject to the "Classpath" exception as provided
9    * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14   * version 2 for more details (a copy is included in the LICENSE file that
15   * accompanied this code).
16   *
17   * You should have received a copy of the GNU General Public License version
18   * 2 along with this work; if not, write to the Free Software Foundation,
19   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20   *
21   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22   * or visit www.oracle.com if you need additional information or have any
23   * questions.
24   */
25  package java.awt;
26  
27  import java.io.PrintStream;
28  import java.io.PrintWriter;
29  import java.util.Vector;
30  import java.util.Locale;
31  import java.util.EventListener;
32  import java.util.Iterator;
33  import java.util.HashSet;
34  import java.util.Map;
35  import java.util.Set;
36  import java.util.Collections;
37  import java.awt.peer.ComponentPeer;
38  import java.awt.peer.ContainerPeer;
39  import java.awt.peer.LightweightPeer;
40  import java.awt.image.BufferStrategy;
41  import java.awt.image.ImageObserver;
42  import java.awt.image.ImageProducer;
43  import java.awt.image.ColorModel;
44  import java.awt.image.VolatileImage;
45  import java.awt.event.*;
46  import java.io.Serializable;
47  import java.io.ObjectOutputStream;
48  import java.io.ObjectInputStream;
49  import java.io.IOException;
50  import java.beans.PropertyChangeListener;
51  import java.beans.PropertyChangeSupport;
52  import java.beans.Transient;
53  import java.awt.event.InputMethodListener;
54  import java.awt.event.InputMethodEvent;
55  import java.awt.im.InputContext;
56  import java.awt.im.InputMethodRequests;
57  import java.awt.dnd.DropTarget;
58  import java.lang.reflect.InvocationTargetException;
59  import java.lang.reflect.Method;
60  import java.security.AccessController;
61  import java.security.PrivilegedAction;
62  import java.security.AccessControlContext;
63  import javax.accessibility.*;
64  import java.applet.Applet;
65  
66  import sun.security.action.GetPropertyAction;
67  import sun.awt.AppContext;
68  import sun.awt.AWTAccessor;
69  import sun.awt.ConstrainableGraphics;
70  import sun.awt.SubRegionShowable;
71  import sun.awt.SunToolkit;
72  import sun.awt.WindowClosingListener;
73  import sun.awt.CausedFocusEvent;
74  import sun.awt.EmbeddedFrame;
75  import sun.awt.dnd.SunDropTargetEvent;
76  import sun.awt.im.CompositionArea;
77  import sun.font.FontManager;
78  import sun.font.FontManagerFactory;
79  import sun.font.SunFontManager;
80  import sun.java2d.SunGraphics2D;
81  import sun.java2d.pipe.Region;
82  import sun.awt.image.VSyncedBSManager;
83  import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
84  import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
85  import sun.awt.RequestFocusController;
86  import sun.java2d.SunGraphicsEnvironment;
87  import sun.util.logging.PlatformLogger;
88  
89  /**
90   * A <em>component</em> is an object having a graphical representation
91   * that can be displayed on the screen and that can interact with the
92   * user. Examples of components are the buttons, checkboxes, and scrollbars
93   * of a typical graphical user interface. <p>
94   * The <code>Component</code> class is the abstract superclass of
95   * the nonmenu-related Abstract Window Toolkit components. Class
96   * <code>Component</code> can also be extended directly to create a
97   * lightweight component. A lightweight component is a component that is
98   * not associated with a native window. On the contrary, a heavyweight
99   * component is associated with a native window. The {@link #isLightweight()}
100  * method may be used to distinguish between the two kinds of the components.
101  * <p>
102  * Lightweight and heavyweight components may be mixed in a single component
103  * hierarchy. However, for correct operating of such a mixed hierarchy of
104  * components, the whole hierarchy must be valid. When the hierarchy gets
105  * invalidated, like after changing the bounds of components, or
106  * adding/removing components to/from containers, the whole hierarchy must be
107  * validated afterwards by means of the {@link Container#validate()} method
108  * invoked on the top-most invalid container of the hierarchy.
109  *
110  * <h3>Serialization</h3>
111  * It is important to note that only AWT listeners which conform
112  * to the <code>Serializable</code> protocol will be saved when
113  * the object is stored.  If an AWT object has listeners that
114  * aren't marked serializable, they will be dropped at
115  * <code>writeObject</code> time.  Developers will need, as always,
116  * to consider the implications of making an object serializable.
117  * One situation to watch out for is this:
118  * <pre>
119  *    import java.awt.*;
120  *    import java.awt.event.*;
121  *    import java.io.Serializable;
122  *
123  *    class MyApp implements ActionListener, Serializable
124  *    {
125  *        BigObjectThatShouldNotBeSerializedWithAButton bigOne;
126  *        Button aButton = new Button();
127  *
128  *        MyApp()
129  *        {
130  *            // Oops, now aButton has a listener with a reference
131  *            // to bigOne!
132  *            aButton.addActionListener(this);
133  *        }
134  *
135  *        public void actionPerformed(ActionEvent e)
136  *        {
137  *            System.out.println("Hello There");
138  *        }
139  *    }
140  * </pre>
141  * In this example, serializing <code>aButton</code> by itself
142  * will cause <code>MyApp</code> and everything it refers to
143  * to be serialized as well.  The problem is that the listener
144  * is serializable by coincidence, not by design.  To separate
145  * the decisions about <code>MyApp</code> and the
146  * <code>ActionListener</code> being serializable one can use a
147  * nested class, as in the following example:
148  * <pre>
149  *    import java.awt.*;
150  *    import java.awt.event.*;
151  *    import java.io.Serializable;
152  *
153  *    class MyApp implements java.io.Serializable
154  *    {
155  *         BigObjectThatShouldNotBeSerializedWithAButton bigOne;
156  *         Button aButton = new Button();
157  *
158  *         static class MyActionListener implements ActionListener
159  *         {
160  *             public void actionPerformed(ActionEvent e)
161  *             {
162  *                 System.out.println("Hello There");
163  *             }
164  *         }
165  *
166  *         MyApp()
167  *         {
168  *             aButton.addActionListener(new MyActionListener());
169  *         }
170  *    }
171  * </pre>
172  * <p>
173  * <b>Note</b>: For more information on the paint mechanisms utilitized
174  * by AWT and Swing, including information on how to write the most
175  * efficient painting code, see
176  * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
177  * <p>
178  * For details on the focus subsystem, see
179  * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
180  * How to Use the Focus Subsystem</a>,
181  * a section in <em>The Java Tutorial</em>, and the
182  * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
183  * for more information.
184  *
185  * @author      Arthur van Hoff
186  * @author      Sami Shaio
187  */
188 public abstract class Component implements ImageObserver, MenuContainer,
189                                            Serializable
190 {
191 
192     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");
193     private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");
194     private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");
195     private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");
196 
197     /**
198      * The peer of the component. The peer implements the component's
199      * behavior. The peer is set when the <code>Component</code> is
200      * added to a container that also is a peer.
201      * @see #addNotify
202      * @see #removeNotify
203      */
204     transient ComponentPeer peer;
205 
206     /**
207      * The parent of the object. It may be <code>null</code>
208      * for top-level components.
209      * @see #getParent
210      */
211     transient Container parent;
212 
213     /**
214      * The <code>AppContext</code> of the component. Applets/Plugin may
215      * change the AppContext.
216      */
217     transient AppContext appContext;
218 
219     /**
220      * The x position of the component in the parent's coordinate system.
221      *
222      * @serial
223      * @see #getLocation
224      */
225     int x;
226 
227     /**
228      * The y position of the component in the parent's coordinate system.
229      *
230      * @serial
231      * @see #getLocation
232      */
233     int y;
234 
235     /**
236      * The width of the component.
237      *
238      * @serial
239      * @see #getSize
240      */
241     int width;
242 
243     /**
244      * The height of the component.
245      *
246      * @serial
247      * @see #getSize
248      */
249     int height;
250 
251     /**
252      * The foreground color for this component.
253      * <code>foreground</code> can be <code>null</code>.
254      *
255      * @serial
256      * @see #getForeground
257      * @see #setForeground
258      */
259     Color       foreground;
260 
261     /**
262      * The background color for this component.
263      * <code>background</code> can be <code>null</code>.
264      *
265      * @serial
266      * @see #getBackground
267      * @see #setBackground
268      */
269     Color       background;
270 
271     /**
272      * The font used by this component.
273      * The <code>font</code> can be <code>null</code>.
274      *
275      * @serial
276      * @see #getFont
277      * @see #setFont
278      */
279     volatile Font font;
280 
281     /**
282      * The font which the peer is currently using.
283      * (<code>null</code> if no peer exists.)
284      */
285     Font        peerFont;
286 
287     /**
288      * The cursor displayed when pointer is over this component.
289      * This value can be <code>null</code>.
290      *
291      * @serial
292      * @see #getCursor
293      * @see #setCursor
294      */
295     Cursor      cursor;
296 
297     /**
298      * The locale for the component.
299      *
300      * @serial
301      * @see #getLocale
302      * @see #setLocale
303      */
304     Locale      locale;
305 
306     /**
307      * A reference to a <code>GraphicsConfiguration</code> object
308      * used to describe the characteristics of a graphics
309      * destination.
310      * This value can be <code>null</code>.
311      *
312      * @since 1.3
313      * @serial
314      * @see GraphicsConfiguration
315      * @see #getGraphicsConfiguration
316      */
317     private transient GraphicsConfiguration graphicsConfig = null;
318 
319     /**
320      * A reference to a <code>BufferStrategy</code> object
321      * used to manipulate the buffers on this component.
322      *
323      * @since 1.4
324      * @see java.awt.image.BufferStrategy
325      * @see #getBufferStrategy()
326      */
327     transient BufferStrategy bufferStrategy = null;
328 
329     /**
330      * True when the object should ignore all repaint events.
331      *
332      * @since 1.4
333      * @serial
334      * @see #setIgnoreRepaint
335      * @see #getIgnoreRepaint
336      */
337     boolean ignoreRepaint = false;
338 
339     /**
340      * True when the object is visible. An object that is not
341      * visible is not drawn on the screen.
342      *
343      * @serial
344      * @see #isVisible
345      * @see #setVisible
346      */
347     boolean visible = true;
348 
349     /**
350      * True when the object is enabled. An object that is not
351      * enabled does not interact with the user.
352      *
353      * @serial
354      * @see #isEnabled
355      * @see #setEnabled
356      */
357     boolean enabled = true;
358 
359     /**
360      * True when the object is valid. An invalid object needs to
361      * be layed out. This flag is set to false when the object
362      * size is changed.
363      *
364      * @serial
365      * @see #isValid
366      * @see #validate
367      * @see #invalidate
368      */
369     private volatile boolean valid = false;
370 
371     /**
372      * The <code>DropTarget</code> associated with this component.
373      *
374      * @since 1.2
375      * @serial
376      * @see #setDropTarget
377      * @see #getDropTarget
378      */
379     DropTarget dropTarget;
380 
381     /**
382      * @serial
383      * @see #add
384      */
385     Vector<PopupMenu> popups;
386 
387     /**
388      * A component's name.
389      * This field can be <code>null</code>.
390      *
391      * @serial
392      * @see #getName
393      * @see #setName(String)
394      */
395     private String name;
396 
397     /**
398      * A bool to determine whether the name has
399      * been set explicitly. <code>nameExplicitlySet</code> will
400      * be false if the name has not been set and
401      * true if it has.
402      *
403      * @serial
404      * @see #getName
405      * @see #setName(String)
406      */
407     private boolean nameExplicitlySet = false;
408 
409     /**
410      * Indicates whether this Component can be focused.
411      *
412      * @serial
413      * @see #setFocusable
414      * @see #isFocusable
415      * @since 1.4
416      */
417     private boolean focusable = true;
418 
419     private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
420     private static final int FOCUS_TRAVERSABLE_DEFAULT = 1;
421     private static final int FOCUS_TRAVERSABLE_SET = 2;
422 
423     /**
424      * Tracks whether this Component is relying on default focus travesability.
425      *
426      * @serial
427      * @since 1.4
428      */
429     private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
430 
431     /**
432      * The focus traversal keys. These keys will generate focus traversal
433      * behavior for Components for which focus traversal keys are enabled. If a
434      * value of null is specified for a traversal key, this Component inherits
435      * that traversal key from its parent. If all ancestors of this Component
436      * have null specified for that traversal key, then the current
437      * KeyboardFocusManager's default traversal key is used.
438      *
439      * @serial
440      * @see #setFocusTraversalKeys
441      * @see #getFocusTraversalKeys
442      * @since 1.4
443      */
444     Set<AWTKeyStroke>[] focusTraversalKeys;
445 
446     private static final String[] focusTraversalKeyPropertyNames = {
447         "forwardFocusTraversalKeys",
448         "backwardFocusTraversalKeys",
449         "upCycleFocusTraversalKeys",
450         "downCycleFocusTraversalKeys"
451     };
452 
453     /**
454      * Indicates whether focus traversal keys are enabled for this Component.
455      * Components for which focus traversal keys are disabled receive key
456      * events for focus traversal keys. Components for which focus traversal
457      * keys are enabled do not see these events; instead, the events are
458      * automatically converted to traversal operations.
459      *
460      * @serial
461      * @see #setFocusTraversalKeysEnabled
462      * @see #getFocusTraversalKeysEnabled
463      * @since 1.4
464      */
465     private boolean focusTraversalKeysEnabled = true;
466 
467     /**
468      * The locking object for AWT component-tree and layout operations.
469      *
470      * @see #getTreeLock
471      */
472     static final Object LOCK = new AWTTreeLock();
473     static class AWTTreeLock {}
474 
475     /*
476      * The component's AccessControlContext.
477      */
478     private transient volatile AccessControlContext acc =
479         AccessController.getContext();
480 
481     /**
482      * Minimum size.
483      * (This field perhaps should have been transient).
484      *
485      * @serial
486      */
487     Dimension minSize;
488 
489     /**
490      * Whether or not setMinimumSize has been invoked with a non-null value.
491      */
492     boolean minSizeSet;
493 
494     /**
495      * Preferred size.
496      * (This field perhaps should have been transient).
497      *
498      * @serial
499      */
500     Dimension prefSize;
501 
502     /**
503      * Whether or not setPreferredSize has been invoked with a non-null value.
504      */
505     boolean prefSizeSet;
506 
507     /**
508      * Maximum size
509      *
510      * @serial
511      */
512     Dimension maxSize;
513 
514     /**
515      * Whether or not setMaximumSize has been invoked with a non-null value.
516      */
517     boolean maxSizeSet;
518 
519     /**
520      * The orientation for this component.
521      * @see #getComponentOrientation
522      * @see #setComponentOrientation
523      */
524     transient ComponentOrientation componentOrientation
525     = ComponentOrientation.UNKNOWN;
526 
527     /**
528      * <code>newEventsOnly</code> will be true if the event is
529      * one of the event types enabled for the component.
530      * It will then allow for normal processing to
531      * continue.  If it is false the event is passed
532      * to the component's parent and up the ancestor
533      * tree until the event has been consumed.
534      *
535      * @serial
536      * @see #dispatchEvent
537      */
538     boolean newEventsOnly = false;
539     transient ComponentListener componentListener;
540     transient FocusListener focusListener;
541     transient HierarchyListener hierarchyListener;
542     transient HierarchyBoundsListener hierarchyBoundsListener;
543     transient KeyListener keyListener;
544     transient MouseListener mouseListener;
545     transient MouseMotionListener mouseMotionListener;
546     transient MouseWheelListener mouseWheelListener;
547     transient InputMethodListener inputMethodListener;
548 
549     transient RuntimeException windowClosingException = null;
550 
551     /** Internal, constants for serialization */
552     final static String actionListenerK = "actionL";
553     final static String adjustmentListenerK = "adjustmentL";
554     final static String componentListenerK = "componentL";
555     final static String containerListenerK = "containerL";
556     final static String focusListenerK = "focusL";
557     final static String itemListenerK = "itemL";
558     final static String keyListenerK = "keyL";
559     final static String mouseListenerK = "mouseL";
560     final static String mouseMotionListenerK = "mouseMotionL";
561     final static String mouseWheelListenerK = "mouseWheelL";
562     final static String textListenerK = "textL";
563     final static String ownedWindowK = "ownedL";
564     final static String windowListenerK = "windowL";
565     final static String inputMethodListenerK = "inputMethodL";
566     final static String hierarchyListenerK = "hierarchyL";
567     final static String hierarchyBoundsListenerK = "hierarchyBoundsL";
568     final static String windowStateListenerK = "windowStateL";
569     final static String windowFocusListenerK = "windowFocusL";
570 
571     /**
572      * The <code>eventMask</code> is ONLY set by subclasses via
573      * <code>enableEvents</code>.
574      * The mask should NOT be set when listeners are registered
575      * so that we can distinguish the difference between when
576      * listeners request events and subclasses request them.
577      * One bit is used to indicate whether input methods are
578      * enabled; this bit is set by <code>enableInputMethods</code> and is
579      * on by default.
580      *
581      * @serial
582      * @see #enableInputMethods
583      * @see AWTEvent
584      */
585     long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
586 
587     /**
588      * Static properties for incremental drawing.
589      * @see #imageUpdate
590      */
591     static boolean isInc;
592     static int incRate;
593     static {
594         /* ensure that the necessary native libraries are loaded */
595         Toolkit.loadLibraries();
596         /* initialize JNI field and method ids */
597         if (!GraphicsEnvironment.isHeadless()) {
598             initIDs();
599         }
600 
601         String s = java.security.AccessController.doPrivileged(
602                                                                new GetPropertyAction("awt.image.incrementaldraw"));
603         isInc = (s == null || s.equals("true"));
604 
605         s = java.security.AccessController.doPrivileged(
606                                                         new GetPropertyAction("awt.image.redrawrate"));
607         incRate = (s != null) ? Integer.parseInt(s) : 100;
608     }
609 
610     /**
611      * Ease-of-use constant for <code>getAlignmentY()</code>.
612      * Specifies an alignment to the top of the component.
613      * @see     #getAlignmentY
614      */
615     public static final float TOP_ALIGNMENT = 0.0f;
616 
617     /**
618      * Ease-of-use constant for <code>getAlignmentY</code> and
619      * <code>getAlignmentX</code>. Specifies an alignment to
620      * the center of the component
621      * @see     #getAlignmentX
622      * @see     #getAlignmentY
623      */
624     public static final float CENTER_ALIGNMENT = 0.5f;
625 
626     /**
627      * Ease-of-use constant for <code>getAlignmentY</code>.
628      * Specifies an alignment to the bottom of the component.
629      * @see     #getAlignmentY
630      */
631     public static final float BOTTOM_ALIGNMENT = 1.0f;
632 
633     /**
634      * Ease-of-use constant for <code>getAlignmentX</code>.
635      * Specifies an alignment to the left side of the component.
636      * @see     #getAlignmentX
637      */
638     public static final float LEFT_ALIGNMENT = 0.0f;
639 
640     /**
641      * Ease-of-use constant for <code>getAlignmentX</code>.
642      * Specifies an alignment to the right side of the component.
643      * @see     #getAlignmentX
644      */
645     public static final float RIGHT_ALIGNMENT = 1.0f;
646 
647     /*
648      * JDK 1.1 serialVersionUID
649      */
650     private static final long serialVersionUID = -7644114512714619750L;
651 
652     /**
653      * If any <code>PropertyChangeListeners</code> have been registered,
654      * the <code>changeSupport</code> field describes them.
655      *
656      * @serial
657      * @since 1.2
658      * @see #addPropertyChangeListener
659      * @see #removePropertyChangeListener
660      * @see #firePropertyChange
661      */
662     private PropertyChangeSupport changeSupport;
663 
664     /*
665      * In some cases using "this" as an object to synchronize by
666      * can lead to a deadlock if client code also uses synchronization
667      * by a component object. For every such situation revealed we should
668      * consider possibility of replacing "this" with the package private
669      * objectLock object introduced below. So far there're 3 issues known:
670      * - CR 6708322 (the getName/setName methods);
671      * - CR 6608764 (the PropertyChangeListener machinery);
672      * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods).
673      *
674      * Note: this field is considered final, though readObject() prohibits
675      * initializing final fields.
676      */
677     private transient Object objectLock = new Object();
678     Object getObjectLock() {
679         return objectLock;
680     }
681 
682     /*
683      * Returns the acc this component was constructed with.
684      */
685     final AccessControlContext getAccessControlContext() {
686         if (acc == null) {
687             throw new SecurityException("Component is missing AccessControlContext");
688         }
689         return acc;
690     }
691 
692     boolean isPacked = false;
693 
694     /**
695      * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
696      * to signal setBounds what's changing. Should be used under TreeLock.
697      * This is only needed due to the inability to change the cross-calling
698      * order of public and deprecated methods.
699      */
700     private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
701 
702     /**
703      * Enumeration of the common ways the baseline of a component can
704      * change as the size changes.  The baseline resize behavior is
705      * primarily for layout managers that need to know how the
706      * position of the baseline changes as the component size changes.
707      * In general the baseline resize behavior will be valid for sizes
708      * greater than or equal to the minimum size (the actual minimum
709      * size; not a developer specified minimum size).  For sizes
710      * smaller than the minimum size the baseline may change in a way
711      * other than the baseline resize behavior indicates.  Similarly,
712      * as the size approaches <code>Integer.MAX_VALUE</code> and/or
713      * <code>Short.MAX_VALUE</code> the baseline may change in a way
714      * other than the baseline resize behavior indicates.
715      *
716      * @see #getBaselineResizeBehavior
717      * @see #getBaseline(int,int)
718      * @since 1.6
719      */
720     public enum BaselineResizeBehavior {
721         /**
722          * Indicates the baseline remains fixed relative to the
723          * y-origin.  That is, <code>getBaseline</code> returns
724          * the same value regardless of the height or width.  For example, a
725          * <code>JLabel</code> containing non-empty text with a
726          * vertical alignment of <code>TOP</code> should have a
727          * baseline type of <code>CONSTANT_ASCENT</code>.
728          */
729         CONSTANT_ASCENT,
730 
731         /**
732          * Indicates the baseline remains fixed relative to the height
733          * and does not change as the width is varied.  That is, for
734          * any height H the difference between H and
735          * <code>getBaseline(w, H)</code> is the same.  For example, a
736          * <code>JLabel</code> containing non-empty text with a
737          * vertical alignment of <code>BOTTOM</code> should have a
738          * baseline type of <code>CONSTANT_DESCENT</code>.
739          */
740         CONSTANT_DESCENT,
741 
742         /**
743          * Indicates the baseline remains a fixed distance from
744          * the center of the component.  That is, for any height H the
745          * difference between <code>getBaseline(w, H)</code> and
746          * <code>H / 2</code> is the same (plus or minus one depending upon
747          * rounding error).
748          * <p>
749          * Because of possible rounding errors it is recommended
750          * you ask for the baseline with two consecutive heights and use
751          * the return value to determine if you need to pad calculations
752          * by 1.  The following shows how to calculate the baseline for
753          * any height:
754          * <pre>
755          *   Dimension preferredSize = component.getPreferredSize();
756          *   int baseline = getBaseline(preferredSize.width,
757          *                              preferredSize.height);
758          *   int nextBaseline = getBaseline(preferredSize.width,
759          *                                  preferredSize.height + 1);
760          *   // Amount to add to height when calculating where baseline
761          *   // lands for a particular height:
762          *   int padding = 0;
763          *   // Where the baseline is relative to the mid point
764          *   int baselineOffset = baseline - height / 2;
765          *   if (preferredSize.height % 2 == 0 &amp;&amp;
766          *       baseline != nextBaseline) {
767          *       padding = 1;
768          *   }
769          *   else if (preferredSize.height % 2 == 1 &amp;&amp;
770          *            baseline == nextBaseline) {
771          *       baselineOffset--;
772          *       padding = 1;
773          *   }
774          *   // The following calculates where the baseline lands for
775          *   // the height z:
776          *   int calculatedBaseline = (z + padding) / 2 + baselineOffset;
777          * </pre>
778          */
779         CENTER_OFFSET,
780 
781         /**
782          * Indicates the baseline resize behavior can not be expressed using
783          * any of the other constants.  This may also indicate the baseline
784          * varies with the width of the component.  This is also returned
785          * by components that do not have a baseline.
786          */
787         OTHER
788     }
789 
790     /*
791      * The shape set with the applyCompoundShape() method. It uncludes the result
792      * of the HW/LW mixing related shape computation. It may also include
793      * the user-specified shape of the component.
794      * The 'null' value means the component has normal shape (or has no shape at all)
795      * and applyCompoundShape() will skip the following shape identical to normal.
796      */
797     private transient Region compoundShape = null;
798 
799     /*
800      * Represents the shape of this lightweight component to be cut out from
801      * heavyweight components should they intersect. Possible values:
802      *    1. null - consider the shape rectangular
803      *    2. EMPTY_REGION - nothing gets cut out (children still get cut out)
804      *    3. non-empty - this shape gets cut out.
805      */
806     private transient Region mixingCutoutRegion = null;
807 
808     /*
809      * Indicates whether addNotify() is complete
810      * (i.e. the peer is created).
811      */
812     private transient boolean isAddNotifyComplete = false;
813 
814     /**
815      * Should only be used in subclass getBounds to check that part of bounds
816      * is actualy changing
817      */
818     int getBoundsOp() {
819         assert Thread.holdsLock(getTreeLock());
820         return boundsOp;
821     }
822 
823     void setBoundsOp(int op) {
824         assert Thread.holdsLock(getTreeLock());
825         if (op == ComponentPeer.RESET_OPERATION) {
826             boundsOp = ComponentPeer.DEFAULT_OPERATION;
827         } else
828             if (boundsOp == ComponentPeer.DEFAULT_OPERATION) {
829                 boundsOp = op;
830             }
831     }
832 
833     // Whether this Component has had the background erase flag
834     // specified via SunToolkit.disableBackgroundErase(). This is
835     // needed in order to make this function work on X11 platforms,
836     // where currently there is no chance to interpose on the creation
837     // of the peer and therefore the call to XSetBackground.
838     transient boolean backgroundEraseDisabled;
839 
840     static {
841         AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() {
842             public void setBackgroundEraseDisabled(Component comp, boolean disabled) {
843                 comp.backgroundEraseDisabled = disabled;
844             }
845             public boolean getBackgroundEraseDisabled(Component comp) {
846                 return comp.backgroundEraseDisabled;
847             }
848             public Rectangle getBounds(Component comp) {
849                 return new Rectangle(comp.x, comp.y, comp.width, comp.height);
850             }
851             public void setMixingCutoutShape(Component comp, Shape shape) {
852                 Region region = shape == null ?  null :
853                     Region.getInstance(shape, null);
854 
855                 synchronized (comp.getTreeLock()) {
856                     boolean needShowing = false;
857                     boolean needHiding = false;
858 
859                     if (!comp.isNonOpaqueForMixing()) {
860                         needHiding = true;
861                     }
862 
863                     comp.mixingCutoutRegion = region;
864 
865                     if (!comp.isNonOpaqueForMixing()) {
866                         needShowing = true;
867                     }
868 
869                     if (comp.isMixingNeeded()) {
870                         if (needHiding) {
871                             comp.mixOnHiding(comp.isLightweight());
872                         }
873                         if (needShowing) {
874                             comp.mixOnShowing();
875                         }
876                     }
877                 }
878             }
879 
880             public void setGraphicsConfiguration(Component comp,
881                     GraphicsConfiguration gc)
882             {
883                 comp.setGraphicsConfiguration(gc);
884             }
885             public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) {
886                 return comp.requestFocus(cause);
887             }
888             public boolean canBeFocusOwner(Component comp) {
889                 return comp.canBeFocusOwner();
890             }
891 
892             public boolean isVisible(Component comp) {
893                 return comp.isVisible_NoClientCode();
894             }
895             public void setRequestFocusController
896                 (RequestFocusController requestController)
897             {
898                  Component.setRequestFocusController(requestController);
899             }
900             public AppContext getAppContext(Component comp) {
901                  return comp.appContext;
902             }
903             public void setAppContext(Component comp, AppContext appContext) {
904                  comp.appContext = appContext;
905             }
906             public Container getParent(Component comp) {
907                 return comp.getParent_NoClientCode();
908             }
909             public void setParent(Component comp, Container parent) {
910                 comp.parent = parent;
911             }
912             public void setSize(Component comp, int width, int height) {
913                 comp.width = width;
914                 comp.height = height;
915             }
916             public Point getLocation(Component comp) {
917                 return comp.location_NoClientCode();
918             }
919             public void setLocation(Component comp, int x, int y) {
920                 comp.x = x;
921                 comp.y = y;
922             }
923             public boolean isEnabled(Component comp) {
924                 return comp.isEnabledImpl();
925             }
926             public boolean isDisplayable(Component comp) {
927                 return comp.peer != null;
928             }
929             public Cursor getCursor(Component comp) {
930                 return comp.getCursor_NoClientCode();
931             }
932             public ComponentPeer getPeer(Component comp) {
933                 return comp.peer;
934             }
935             public void setPeer(Component comp, ComponentPeer peer) {
936                 comp.peer = peer;
937             }
938             public boolean isLightweight(Component comp) {
939                 return (comp.peer instanceof LightweightPeer);
940             }
941             public boolean getIgnoreRepaint(Component comp) {
942                 return comp.ignoreRepaint;
943             }
944             public int getWidth(Component comp) {
945                 return comp.width;
946             }
947             public int getHeight(Component comp) {
948                 return comp.height;
949             }
950             public int getX(Component comp) {
951                 return comp.x;
952             }
953             public int getY(Component comp) {
954                 return comp.y;
955             }
956             public Color getForeground(Component comp) {
957                 return comp.foreground;
958             }
959             public Color getBackground(Component comp) {
960                 return comp.background;
961             }
962             public void setBackground(Component comp, Color background) {
963                 comp.background = background;
964             }
965             public Font getFont(Component comp) {
966                 return comp.getFont_NoClientCode();
967             }
968             public void processEvent(Component comp, AWTEvent e) {
969                 comp.processEvent(e);
970             }
971 
972             public AccessControlContext getAccessControlContext(Component comp) {
973                 return comp.getAccessControlContext();
974             }
975 
976             public void revalidateSynchronously(Component comp) {
977                 comp.revalidateSynchronously();
978             }
979         });
980     }
981 
982     /**
983      * Constructs a new component. Class <code>Component</code> can be
984      * extended directly to create a lightweight component that does not
985      * utilize an opaque native window. A lightweight component must be
986      * hosted by a native container somewhere higher up in the component
987      * tree (for example, by a <code>Frame</code> object).
988      */
989     protected Component() {
990         appContext = AppContext.getAppContext();
991     }
992 
993     @SuppressWarnings({"rawtypes", "unchecked"})
994     void initializeFocusTraversalKeys() {
995         focusTraversalKeys = new Set[3];
996     }
997 
998     /**
999      * Constructs a name for this component.  Called by <code>getName</code>
1000      * when the name is <code>null</code>.
1001      */
1002     String constructComponentName() {
1003         return null; // For strict compliance with prior platform versions, a Component
1004                      // that doesn't set its name should return null from
1005                      // getName()
1006     }
1007 
1008     /**
1009      * Gets the name of the component.
1010      * @return this component's name
1011      * @see    #setName
1012      * @since JDK1.1
1013      */
1014     public String getName() {
1015         if (name == null && !nameExplicitlySet) {
1016             synchronized(getObjectLock()) {
1017                 if (name == null && !nameExplicitlySet)
1018                     name = constructComponentName();
1019             }
1020         }
1021         return name;
1022     }
1023 
1024     /**
1025      * Sets the name of the component to the specified string.
1026      * @param name  the string that is to be this
1027      *           component's name
1028      * @see #getName
1029      * @since JDK1.1
1030      */
1031     public void setName(String name) {
1032         String oldName;
1033         synchronized(getObjectLock()) {
1034             oldName = this.name;
1035             this.name = name;
1036             nameExplicitlySet = true;
1037         }
1038         firePropertyChange("name", oldName, name);
1039     }
1040 
1041     /**
1042      * Gets the parent of this component.
1043      * @return the parent container of this component
1044      * @since JDK1.0
1045      */
1046     public Container getParent() {
1047         return getParent_NoClientCode();
1048     }
1049 
1050     // NOTE: This method may be called by privileged threads.
1051     //       This functionality is implemented in a package-private method
1052     //       to insure that it cannot be overridden by client subclasses.
1053     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1054     final Container getParent_NoClientCode() {
1055         return parent;
1056     }
1057 
1058     // This method is overridden in the Window class to return null,
1059     //    because the parent field of the Window object contains
1060     //    the owner of the window, not its parent.
1061     Container getContainer() {
1062         return getParent_NoClientCode();
1063     }
1064 
1065     /**
1066      * @deprecated As of JDK version 1.1,
1067      * programs should not directly manipulate peers;
1068      * replaced by <code>boolean isDisplayable()</code>.
1069      */
1070     @Deprecated
1071     public ComponentPeer getPeer() {
1072         return peer;
1073     }
1074 
1075     /**
1076      * Associate a <code>DropTarget</code> with this component.
1077      * The <code>Component</code> will receive drops only if it
1078      * is enabled.
1079      *
1080      * @see #isEnabled
1081      * @param dt The DropTarget
1082      */
1083 
1084     public synchronized void setDropTarget(DropTarget dt) {
1085         if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1086             return;
1087 
1088         DropTarget old;
1089 
1090         if ((old = dropTarget) != null) {
1091             if (peer != null) dropTarget.removeNotify(peer);
1092 
1093             DropTarget t = dropTarget;
1094 
1095             dropTarget = null;
1096 
1097             try {
1098                 t.setComponent(null);
1099             } catch (IllegalArgumentException iae) {
1100                 // ignore it.
1101             }
1102         }
1103 
1104         // if we have a new one, and we have a peer, add it!
1105 
1106         if ((dropTarget = dt) != null) {
1107             try {
1108                 dropTarget.setComponent(this);
1109                 if (peer != null) dropTarget.addNotify(peer);
1110             } catch (IllegalArgumentException iae) {
1111                 if (old != null) {
1112                     try {
1113                         old.setComponent(this);
1114                         if (peer != null) dropTarget.addNotify(peer);
1115                     } catch (IllegalArgumentException iae1) {
1116                         // ignore it!
1117                     }
1118                 }
1119             }
1120         }
1121     }
1122 
1123     /**
1124      * Gets the <code>DropTarget</code> associated with this
1125      * <code>Component</code>.
1126      */
1127 
1128     public synchronized DropTarget getDropTarget() { return dropTarget; }
1129 
1130     /**
1131      * Gets the <code>GraphicsConfiguration</code> associated with this
1132      * <code>Component</code>.
1133      * If the <code>Component</code> has not been assigned a specific
1134      * <code>GraphicsConfiguration</code>,
1135      * the <code>GraphicsConfiguration</code> of the
1136      * <code>Component</code> object's top-level container is
1137      * returned.
1138      * If the <code>Component</code> has been created, but not yet added
1139      * to a <code>Container</code>, this method returns <code>null</code>.
1140      *
1141      * @return the <code>GraphicsConfiguration</code> used by this
1142      *          <code>Component</code> or <code>null</code>
1143      * @since 1.3
1144      */
1145     public GraphicsConfiguration getGraphicsConfiguration() {
1146         synchronized(getTreeLock()) {
1147             return getGraphicsConfiguration_NoClientCode();
1148         }
1149     }
1150 
1151     final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1152         return graphicsConfig;
1153     }
1154 
1155     void setGraphicsConfiguration(GraphicsConfiguration gc) {
1156         synchronized(getTreeLock()) {
1157             if (updateGraphicsData(gc)) {
1158                 removeNotify();
1159                 addNotify();
1160             }
1161         }
1162     }
1163 
1164     boolean updateGraphicsData(GraphicsConfiguration gc) {
1165         checkTreeLock();
1166 
1167         if (graphicsConfig == gc) {
1168             return false;
1169         }
1170 
1171         graphicsConfig = gc;
1172 
1173         ComponentPeer peer = getPeer();
1174         if (peer != null) {
1175             return peer.updateGraphicsData(gc);
1176         }
1177         return false;
1178     }
1179 
1180     /**
1181      * Checks that this component's <code>GraphicsDevice</code>
1182      * <code>idString</code> matches the string argument.
1183      */
1184     void checkGD(String stringID) {
1185         if (graphicsConfig != null) {
1186             if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1187                 throw new IllegalArgumentException(
1188                                                    "adding a container to a container on a different GraphicsDevice");
1189             }
1190         }
1191     }
1192 
1193     /**
1194      * Gets this component's locking object (the object that owns the thread
1195      * synchronization monitor) for AWT component-tree and layout
1196      * operations.
1197      * @return this component's locking object
1198      */
1199     public final Object getTreeLock() {
1200         return LOCK;
1201     }
1202 
1203     final void checkTreeLock() {
1204         if (!Thread.holdsLock(getTreeLock())) {
1205             throw new IllegalStateException("This function should be called while holding treeLock");
1206         }
1207     }
1208 
1209     /**
1210      * Gets the toolkit of this component. Note that
1211      * the frame that contains a component controls which
1212      * toolkit is used by that component. Therefore if the component
1213      * is moved from one frame to another, the toolkit it uses may change.
1214      * @return  the toolkit of this component
1215      * @since JDK1.0
1216      */
1217     public Toolkit getToolkit() {
1218         return getToolkitImpl();
1219     }
1220 
1221     /*
1222      * This is called by the native code, so client code can't
1223      * be called on the toolkit thread.
1224      */
1225     final Toolkit getToolkitImpl() {
1226         Container parent = this.parent;
1227         if (parent != null) {
1228             return parent.getToolkitImpl();
1229         }
1230         return Toolkit.getDefaultToolkit();
1231     }
1232 
1233     /**
1234      * Determines whether this component is valid. A component is valid
1235      * when it is correctly sized and positioned within its parent
1236      * container and all its children are also valid.
1237      * In order to account for peers' size requirements, components are invalidated
1238      * before they are first shown on the screen. By the time the parent container
1239      * is fully realized, all its components will be valid.
1240      * @return <code>true</code> if the component is valid, <code>false</code>
1241      * otherwise
1242      * @see #validate
1243      * @see #invalidate
1244      * @since JDK1.0
1245      */
1246     public boolean isValid() {
1247         return (peer != null) && valid;
1248     }
1249 
1250     /**
1251      * Determines whether this component is displayable. A component is
1252      * displayable when it is connected to a native screen resource.
1253      * <p>
1254      * A component is made displayable either when it is added to
1255      * a displayable containment hierarchy or when its containment
1256      * hierarchy is made displayable.
1257      * A containment hierarchy is made displayable when its ancestor
1258      * window is either packed or made visible.
1259      * <p>
1260      * A component is made undisplayable either when it is removed from
1261      * a displayable containment hierarchy or when its containment hierarchy
1262      * is made undisplayable.  A containment hierarchy is made
1263      * undisplayable when its ancestor window is disposed.
1264      *
1265      * @return <code>true</code> if the component is displayable,
1266      * <code>false</code> otherwise
1267      * @see Container#add(Component)
1268      * @see Window#pack
1269      * @see Window#show
1270      * @see Container#remove(Component)
1271      * @see Window#dispose
1272      * @since 1.2
1273      */
1274     public boolean isDisplayable() {
1275         return getPeer() != null;
1276     }
1277 
1278     /**
1279      * Determines whether this component should be visible when its
1280      * parent is visible. Components are
1281      * initially visible, with the exception of top level components such
1282      * as <code>Frame</code> objects.
1283      * @return <code>true</code> if the component is visible,
1284      * <code>false</code> otherwise
1285      * @see #setVisible
1286      * @since JDK1.0
1287      */
1288     @Transient
1289     public boolean isVisible() {
1290         return isVisible_NoClientCode();
1291     }
1292     final boolean isVisible_NoClientCode() {
1293         return visible;
1294     }
1295 
1296     /**
1297      * Determines whether this component will be displayed on the screen.
1298      * @return <code>true</code> if the component and all of its ancestors
1299      *          until a toplevel window or null parent are visible,
1300      *          <code>false</code> otherwise
1301      */
1302     boolean isRecursivelyVisible() {
1303         return visible && (parent == null || parent.isRecursivelyVisible());
1304     }
1305 
1306     /**
1307      * Translates absolute coordinates into coordinates in the coordinate
1308      * space of this component.
1309      */
1310     Point pointRelativeToComponent(Point absolute) {
1311         Point compCoords = getLocationOnScreen();
1312         return new Point(absolute.x - compCoords.x,
1313                          absolute.y - compCoords.y);
1314     }
1315 
1316     /**
1317      * Assuming that mouse location is stored in PointerInfo passed
1318      * to this method, it finds a Component that is in the same
1319      * Window as this Component and is located under the mouse pointer.
1320      * If no such Component exists, null is returned.
1321      * NOTE: this method should be called under the protection of
1322      * tree lock, as it is done in Component.getMousePosition() and
1323      * Container.getMousePosition(boolean).
1324      */
1325     Component findUnderMouseInWindow(PointerInfo pi) {
1326         if (!isShowing()) {
1327             return null;
1328         }
1329         Window win = getContainingWindow();
1330         if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) {
1331             return null;
1332         }
1333         final boolean INCLUDE_DISABLED = true;
1334         Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1335         Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1336                                                         relativeToWindow.y,
1337                                                         INCLUDE_DISABLED);
1338         return inTheSameWindow;
1339     }
1340 
1341     /**
1342      * Returns the position of the mouse pointer in this <code>Component</code>'s
1343      * coordinate space if the <code>Component</code> is directly under the mouse
1344      * pointer, otherwise returns <code>null</code>.
1345      * If the <code>Component</code> is not showing on the screen, this method
1346      * returns <code>null</code> even if the mouse pointer is above the area
1347      * where the <code>Component</code> would be displayed.
1348      * If the <code>Component</code> is partially or fully obscured by other
1349      * <code>Component</code>s or native windows, this method returns a non-null
1350      * value only if the mouse pointer is located above the unobscured part of the
1351      * <code>Component</code>.
1352      * <p>
1353      * For <code>Container</code>s it returns a non-null value if the mouse is
1354      * above the <code>Container</code> itself or above any of its descendants.
1355      * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1356      * <p>
1357      * Sometimes the exact mouse coordinates are not important, and the only thing
1358      * that matters is whether a specific <code>Component</code> is under the mouse
1359      * pointer. If the return value of this method is <code>null</code>, mouse
1360      * pointer is not directly above the <code>Component</code>.
1361      *
1362      * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1363      * @see       #isShowing
1364      * @see       Container#getMousePosition
1365      * @return    mouse coordinates relative to this <code>Component</code>, or null
1366      * @since     1.5
1367      */
1368     public Point getMousePosition() throws HeadlessException {
1369         if (GraphicsEnvironment.isHeadless()) {
1370             throw new HeadlessException();
1371         }
1372 
1373         PointerInfo pi = java.security.AccessController.doPrivileged(
1374                                                                      new java.security.PrivilegedAction<PointerInfo>() {
1375                                                                          public PointerInfo run() {
1376                                                                              return MouseInfo.getPointerInfo();
1377                                                                          }
1378                                                                      }
1379                                                                      );
1380 
1381         synchronized (getTreeLock()) {
1382             Component inTheSameWindow = findUnderMouseInWindow(pi);
1383             if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1384                 return null;
1385             }
1386             return pointRelativeToComponent(pi.getLocation());
1387         }
1388     }
1389 
1390     /**
1391      * Overridden in Container. Must be called under TreeLock.
1392      */
1393     boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1394         return comp == this;
1395     }
1396 
1397     /**
1398      * Determines whether this component is showing on screen. This means
1399      * that the component must be visible, and it must be in a container
1400      * that is visible and showing.
1401      * <p>
1402      * <strong>Note:</strong> sometimes there is no way to detect whether the
1403      * {@code Component} is actually visible to the user.  This can happen when:
1404      * <ul>
1405      * <li>the component has been added to a visible {@code ScrollPane} but
1406      * the {@code Component} is not currently in the scroll pane's view port.
1407      * <li>the {@code Component} is obscured by another {@code Component} or
1408      * {@code Container}.
1409      * </ul>
1410      * @return <code>true</code> if the component is showing,
1411      *          <code>false</code> otherwise
1412      * @see #setVisible
1413      * @since JDK1.0
1414      */
1415     public boolean isShowing() {
1416         if (visible && (peer != null)) {
1417             Container parent = this.parent;
1418             return (parent == null) || parent.isShowing();
1419         }
1420         return false;
1421     }
1422 
1423     /**
1424      * Determines whether this component is enabled. An enabled component
1425      * can respond to user input and generate events. Components are
1426      * enabled initially by default. A component may be enabled or disabled by
1427      * calling its <code>setEnabled</code> method.
1428      * @return <code>true</code> if the component is enabled,
1429      *          <code>false</code> otherwise
1430      * @see #setEnabled
1431      * @since JDK1.0
1432      */
1433     public boolean isEnabled() {
1434         return isEnabledImpl();
1435     }
1436 
1437     /*
1438      * This is called by the native code, so client code can't
1439      * be called on the toolkit thread.
1440      */
1441     final boolean isEnabledImpl() {
1442         return enabled;
1443     }
1444 
1445     /**
1446      * Enables or disables this component, depending on the value of the
1447      * parameter <code>b</code>. An enabled component can respond to user
1448      * input and generate events. Components are enabled initially by default.
1449      *
1450      * <p>Note: Disabling a lightweight component does not prevent it from
1451      * receiving MouseEvents.
1452      * <p>Note: Disabling a heavyweight container prevents all components
1453      * in this container from receiving any input events.  But disabling a
1454      * lightweight container affects only this container.
1455      *
1456      * @param     b   If <code>true</code>, this component is
1457      *            enabled; otherwise this component is disabled
1458      * @see #isEnabled
1459      * @see #isLightweight
1460      * @since JDK1.1
1461      */
1462     public void setEnabled(boolean b) {
1463         enable(b);
1464     }
1465 
1466     /**
1467      * @deprecated As of JDK version 1.1,
1468      * replaced by <code>setEnabled(boolean)</code>.
1469      */
1470     @Deprecated
1471     public void enable() {
1472         if (!enabled) {
1473             synchronized (getTreeLock()) {
1474                 enabled = true;
1475                 ComponentPeer peer = this.peer;
1476                 if (peer != null) {
1477                     peer.setEnabled(true);
1478                     if (visible) {
1479                         updateCursorImmediately();
1480                     }
1481                 }
1482             }
1483             if (accessibleContext != null) {
1484                 accessibleContext.firePropertyChange(
1485                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1486                                                      null, AccessibleState.ENABLED);
1487             }
1488         }
1489     }
1490 
1491     /**
1492      * @deprecated As of JDK version 1.1,
1493      * replaced by <code>setEnabled(boolean)</code>.
1494      */
1495     @Deprecated
1496     public void enable(boolean b) {
1497         if (b) {
1498             enable();
1499         } else {
1500             disable();
1501         }
1502     }
1503 
1504     /**
1505      * @deprecated As of JDK version 1.1,
1506      * replaced by <code>setEnabled(boolean)</code>.
1507      */
1508     @Deprecated
1509     public void disable() {
1510         if (enabled) {
1511             KeyboardFocusManager.clearMostRecentFocusOwner(this);
1512             synchronized (getTreeLock()) {
1513                 enabled = false;
1514                 // A disabled lw container is allowed to contain a focus owner.
1515                 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1516                     KeyboardFocusManager.isAutoFocusTransferEnabled())
1517                 {
1518                     // Don't clear the global focus owner. If transferFocus
1519                     // fails, we want the focus to stay on the disabled
1520                     // Component so that keyboard traversal, et. al. still
1521                     // makes sense to the user.
1522                     transferFocus(false);
1523                 }
1524                 ComponentPeer peer = this.peer;
1525                 if (peer != null) {
1526                     peer.setEnabled(false);
1527                     if (visible) {
1528                         updateCursorImmediately();
1529                     }
1530                 }
1531             }
1532             if (accessibleContext != null) {
1533                 accessibleContext.firePropertyChange(
1534                                                      AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1535                                                      null, AccessibleState.ENABLED);
1536             }
1537         }
1538     }
1539 
1540     /**
1541      * Returns true if this component is painted to an offscreen image
1542      * ("buffer") that's copied to the screen later.  Component
1543      * subclasses that support double buffering should override this
1544      * method to return true if double buffering is enabled.
1545      *
1546      * @return false by default
1547      */
1548     public boolean isDoubleBuffered() {
1549         return false;
1550     }
1551 
1552     /**
1553      * Enables or disables input method support for this component. If input
1554      * method support is enabled and the component also processes key events,
1555      * incoming events are offered to
1556      * the current input method and will only be processed by the component or
1557      * dispatched to its listeners if the input method does not consume them.
1558      * By default, input method support is enabled.
1559      *
1560      * @param enable true to enable, false to disable
1561      * @see #processKeyEvent
1562      * @since 1.2
1563      */
1564     public void enableInputMethods(boolean enable) {
1565         if (enable) {
1566             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0)
1567                 return;
1568 
1569             // If this component already has focus, then activate the
1570             // input method by dispatching a synthesized focus gained
1571             // event.
1572             if (isFocusOwner()) {
1573                 InputContext inputContext = getInputContext();
1574                 if (inputContext != null) {
1575                     FocusEvent focusGainedEvent =
1576                         new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1577                     inputContext.dispatchEvent(focusGainedEvent);
1578                 }
1579             }
1580 
1581             eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1582         } else {
1583             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1584                 InputContext inputContext = getInputContext();
1585                 if (inputContext != null) {
1586                     inputContext.endComposition();
1587                     inputContext.removeNotify(this);
1588                 }
1589             }
1590             eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1591         }
1592     }
1593 
1594     /**
1595      * Shows or hides this component depending on the value of parameter
1596      * <code>b</code>.
1597      * <p>
1598      * This method changes layout-related information, and therefore,
1599      * invalidates the component hierarchy.
1600      *
1601      * @param b  if <code>true</code>, shows this component;
1602      * otherwise, hides this component
1603      * @see #isVisible
1604      * @see #invalidate
1605      * @since JDK1.1
1606      */
1607     public void setVisible(boolean b) {
1608         show(b);
1609     }
1610 
1611     /**
1612      * @deprecated As of JDK version 1.1,
1613      * replaced by <code>setVisible(boolean)</code>.
1614      */
1615     @Deprecated
1616     public void show() {
1617         if (!visible) {
1618             synchronized (getTreeLock()) {
1619                 visible = true;
1620                 mixOnShowing();
1621                 ComponentPeer peer = this.peer;
1622                 if (peer != null) {
1623                     peer.setVisible(true);
1624                     createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1625                                           this, parent,
1626                                           HierarchyEvent.SHOWING_CHANGED,
1627                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1628                     if (peer instanceof LightweightPeer) {
1629                         repaint();
1630                     }
1631                     updateCursorImmediately();
1632                 }
1633 
1634                 if (componentListener != null ||
1635                     (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1636                     Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1637                     ComponentEvent e = new ComponentEvent(this,
1638                                                           ComponentEvent.COMPONENT_SHOWN);
1639                     Toolkit.getEventQueue().postEvent(e);
1640                 }
1641             }
1642             Container parent = this.parent;
1643             if (parent != null) {
1644                 parent.invalidate();
1645             }
1646         }
1647     }
1648 
1649     /**
1650      * @deprecated As of JDK version 1.1,
1651      * replaced by <code>setVisible(boolean)</code>.
1652      */
1653     @Deprecated
1654     public void show(boolean b) {
1655         if (b) {
1656             show();
1657         } else {
1658             hide();
1659         }
1660     }
1661 
1662     boolean containsFocus() {
1663         return isFocusOwner();
1664     }
1665 
1666     void clearMostRecentFocusOwnerOnHide() {
1667         KeyboardFocusManager.clearMostRecentFocusOwner(this);
1668     }
1669 
1670     void clearCurrentFocusCycleRootOnHide() {
1671         /* do nothing */
1672     }
1673 
1674     /*
1675      * Delete references from LightweithDispatcher of a heavyweight parent
1676      */
1677     void clearLightweightDispatcherOnRemove(Component removedComponent) {
1678         if (parent != null) {
1679             parent.clearLightweightDispatcherOnRemove(removedComponent);
1680         }
1681     }
1682 
1683     /**
1684      * @deprecated As of JDK version 1.1,
1685      * replaced by <code>setVisible(boolean)</code>.
1686      */
1687     @Deprecated
1688     public void hide() {
1689         isPacked = false;
1690 
1691         if (visible) {
1692             clearCurrentFocusCycleRootOnHide();
1693             clearMostRecentFocusOwnerOnHide();
1694             synchronized (getTreeLock()) {
1695                 visible = false;
1696                 mixOnHiding(isLightweight());
1697                 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
1698                     transferFocus(true);
1699                 }
1700                 ComponentPeer peer = this.peer;
1701                 if (peer != null) {
1702                     peer.setVisible(false);
1703                     createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1704                                           this, parent,
1705                                           HierarchyEvent.SHOWING_CHANGED,
1706                                           Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1707                     if (peer instanceof LightweightPeer) {
1708                         repaint();
1709                     }
1710                     updateCursorImmediately();
1711                 }
1712                 if (componentListener != null ||
1713                     (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1714                     Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1715                     ComponentEvent e = new ComponentEvent(this,
1716                                                           ComponentEvent.COMPONENT_HIDDEN);
1717                     Toolkit.getEventQueue().postEvent(e);
1718                 }
1719             }
1720             Container parent = this.parent;
1721             if (parent != null) {
1722                 parent.invalidate();
1723             }
1724         }
1725     }
1726 
1727     /**
1728      * Gets the foreground color of this component.
1729      * @return this component's foreground color; if this component does
1730      * not have a foreground color, the foreground color of its parent
1731      * is returned
1732      * @see #setForeground
1733      * @since JDK1.0
1734      * @beaninfo
1735      *       bound: true
1736      */
1737     @Transient
1738     public Color getForeground() {
1739         Color foreground = this.foreground;
1740         if (foreground != null) {
1741             return foreground;
1742         }
1743         Container parent = this.parent;
1744         return (parent != null) ? parent.getForeground() : null;
1745     }
1746 
1747     /**
1748      * Sets the foreground color of this component.
1749      * @param c the color to become this component's
1750      *          foreground color; if this parameter is <code>null</code>
1751      *          then this component will inherit
1752      *          the foreground color of its parent
1753      * @see #getForeground
1754      * @since JDK1.0
1755      */
1756     public void setForeground(Color c) {
1757         Color oldColor = foreground;
1758         ComponentPeer peer = this.peer;
1759         foreground = c;
1760         if (peer != null) {
1761             c = getForeground();
1762             if (c != null) {
1763                 peer.setForeground(c);
1764             }
1765         }
1766         // This is a bound property, so report the change to
1767         // any registered listeners.  (Cheap if there are none.)
1768         firePropertyChange("foreground", oldColor, c);
1769     }
1770 
1771     /**
1772      * Returns whether the foreground color has been explicitly set for this
1773      * Component. If this method returns <code>false</code>, this Component is
1774      * inheriting its foreground color from an ancestor.
1775      *
1776      * @return <code>true</code> if the foreground color has been explicitly
1777      *         set for this Component; <code>false</code> otherwise.
1778      * @since 1.4
1779      */
1780     public boolean isForegroundSet() {
1781         return (foreground != null);
1782     }
1783 
1784     /**
1785      * Gets the background color of this component.
1786      * @return this component's background color; if this component does
1787      *          not have a background color,
1788      *          the background color of its parent is returned
1789      * @see #setBackground
1790      * @since JDK1.0
1791      */
1792     @Transient
1793     public Color getBackground() {
1794         Color background = this.background;
1795         if (background != null) {
1796             return background;
1797         }
1798         Container parent = this.parent;
1799         return (parent != null) ? parent.getBackground() : null;
1800     }
1801 
1802     /**
1803      * Sets the background color of this component.
1804      * <p>
1805      * The background color affects each component differently and the
1806      * parts of the component that are affected by the background color
1807      * may differ between operating systems.
1808      *
1809      * @param c the color to become this component's color;
1810      *          if this parameter is <code>null</code>, then this
1811      *          component will inherit the background color of its parent
1812      * @see #getBackground
1813      * @since JDK1.0
1814      * @beaninfo
1815      *       bound: true
1816      */
1817     public void setBackground(Color c) {
1818         Color oldColor = background;
1819         ComponentPeer peer = this.peer;
1820         background = c;
1821         if (peer != null) {
1822             c = getBackground();
1823             if (c != null) {
1824                 peer.setBackground(c);
1825             }
1826         }
1827         // This is a bound property, so report the change to
1828         // any registered listeners.  (Cheap if there are none.)
1829         firePropertyChange("background", oldColor, c);
1830     }
1831 
1832     /**
1833      * Returns whether the background color has been explicitly set for this
1834      * Component. If this method returns <code>false</code>, this Component is
1835      * inheriting its background color from an ancestor.
1836      *
1837      * @return <code>true</code> if the background color has been explicitly
1838      *         set for this Component; <code>false</code> otherwise.
1839      * @since 1.4
1840      */
1841     public boolean isBackgroundSet() {
1842         return (background != null);
1843     }
1844 
1845     /**
1846      * Gets the font of this component.
1847      * @return this component's font; if a font has not been set
1848      * for this component, the font of its parent is returned
1849      * @see #setFont
1850      * @since JDK1.0
1851      */
1852     @Transient
1853     public Font getFont() {
1854         return getFont_NoClientCode();
1855     }
1856 
1857     // NOTE: This method may be called by privileged threads.
1858     //       This functionality is implemented in a package-private method
1859     //       to insure that it cannot be overridden by client subclasses.
1860     //       DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1861     final Font getFont_NoClientCode() {
1862         Font font = this.font;
1863         if (font != null) {
1864             return font;
1865         }
1866         Container parent = this.parent;
1867         return (parent != null) ? parent.getFont_NoClientCode() : null;
1868     }
1869 
1870     /**
1871      * Sets the font of this component.
1872      * <p>
1873      * This method changes layout-related information, and therefore,
1874      * invalidates the component hierarchy.
1875      *
1876      * @param f the font to become this component's font;
1877      *          if this parameter is <code>null</code> then this
1878      *          component will inherit the font of its parent
1879      * @see #getFont
1880      * @see #invalidate
1881      * @since JDK1.0
1882      * @beaninfo
1883      *       bound: true
1884      */
1885     public void setFont(Font f) {
1886         Font oldFont, newFont;
1887         synchronized(getTreeLock()) {
1888             oldFont = font;
1889             newFont = font = f;
1890             ComponentPeer peer = this.peer;
1891             if (peer != null) {
1892                 f = getFont();
1893                 if (f != null) {
1894                     peer.setFont(f);
1895                     peerFont = f;
1896                 }
1897             }
1898         }
1899         // This is a bound property, so report the change to
1900         // any registered listeners.  (Cheap if there are none.)
1901         firePropertyChange("font", oldFont, newFont);
1902 
1903         // This could change the preferred size of the Component.
1904         // Fix for 6213660. Should compare old and new fonts and do not
1905         // call invalidate() if they are equal.
1906         if (f != oldFont && (oldFont == null ||
1907                                       !oldFont.equals(f))) {
1908             invalidateIfValid();
1909         }
1910     }
1911 
1912     /**
1913      * Returns whether the font has been explicitly set for this Component. If
1914      * this method returns <code>false</code>, this Component is inheriting its
1915      * font from an ancestor.
1916      *
1917      * @return <code>true</code> if the font has been explicitly set for this
1918      *         Component; <code>false</code> otherwise.
1919      * @since 1.4
1920      */
1921     public boolean isFontSet() {
1922         return (font != null);
1923     }
1924 
1925     /**
1926      * Gets the locale of this component.
1927      * @return this component's locale; if this component does not
1928      *          have a locale, the locale of its parent is returned
1929      * @see #setLocale
1930      * @exception IllegalComponentStateException if the <code>Component</code>
1931      *          does not have its own locale and has not yet been added to
1932      *          a containment hierarchy such that the locale can be determined
1933      *          from the containing parent
1934      * @since  JDK1.1
1935      */
1936     public Locale getLocale() {
1937         Locale locale = this.locale;
1938         if (locale != null) {
1939             return locale;
1940         }
1941         Container parent = this.parent;
1942 
1943         if (parent == null) {
1944             throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");
1945         } else {
1946             return parent.getLocale();
1947         }
1948     }
1949 
1950     /**
1951      * Sets the locale of this component.  This is a bound property.
1952      * <p>
1953      * This method changes layout-related information, and therefore,
1954      * invalidates the component hierarchy.
1955      *
1956      * @param l the locale to become this component's locale
1957      * @see #getLocale
1958      * @see #invalidate
1959      * @since JDK1.1
1960      */
1961     public void setLocale(Locale l) {
1962         Locale oldValue = locale;
1963         locale = l;
1964 
1965         // This is a bound property, so report the change to
1966         // any registered listeners.  (Cheap if there are none.)
1967         firePropertyChange("locale", oldValue, l);
1968 
1969         // This could change the preferred size of the Component.
1970         invalidateIfValid();
1971     }
1972 
1973     /**
1974      * Gets the instance of <code>ColorModel</code> used to display
1975      * the component on the output device.
1976      * @return the color model used by this component
1977      * @see java.awt.image.ColorModel
1978      * @see java.awt.peer.ComponentPeer#getColorModel()
1979      * @see Toolkit#getColorModel()
1980      * @since JDK1.0
1981      */
1982     public ColorModel getColorModel() {
1983         ComponentPeer peer = this.peer;
1984         if ((peer != null) && ! (peer instanceof LightweightPeer)) {
1985             return peer.getColorModel();
1986         } else if (GraphicsEnvironment.isHeadless()) {
1987             return ColorModel.getRGBdefault();
1988         } // else
1989         return getToolkit().getColorModel();
1990     }
1991 
1992     /**
1993      * Gets the location of this component in the form of a
1994      * point specifying the component's top-left corner.
1995      * The location will be relative to the parent's coordinate space.
1996      * <p>
1997      * Due to the asynchronous nature of native event handling, this
1998      * method can return outdated values (for instance, after several calls
1999      * of <code>setLocation()</code> in rapid succession).  For this
2000      * reason, the recommended method of obtaining a component's position is
2001      * within <code>java.awt.event.ComponentListener.componentMoved()</code>,
2002      * which is called after the operating system has finished moving the
2003      * component.
2004      * </p>
2005      * @return an instance of <code>Point</code> representing
2006      *          the top-left corner of the component's bounds in
2007      *          the coordinate space of the component's parent
2008      * @see #setLocation
2009      * @see #getLocationOnScreen
2010      * @since JDK1.1
2011      */
2012     public Point getLocation() {
2013         return location();
2014     }
2015 
2016     /**
2017      * Gets the location of this component in the form of a point
2018      * specifying the component's top-left corner in the screen's
2019      * coordinate space.
2020      * @return an instance of <code>Point</code> representing
2021      *          the top-left corner of the component's bounds in the
2022      *          coordinate space of the screen
2023      * @throws IllegalComponentStateException if the
2024      *          component is not showing on the screen
2025      * @see #setLocation
2026      * @see #getLocation
2027      */
2028     public Point getLocationOnScreen() {
2029         synchronized (getTreeLock()) {
2030             return getLocationOnScreen_NoTreeLock();
2031         }
2032     }
2033 
2034     /*
2035      * a package private version of getLocationOnScreen
2036      * used by GlobalCursormanager to update cursor
2037      */
2038     final Point getLocationOnScreen_NoTreeLock() {
2039 
2040         if (peer != null && isShowing()) {
2041             if (peer instanceof LightweightPeer) {
2042                 // lightweight component location needs to be translated
2043                 // relative to a native component.
2044                 Container host = getNativeContainer();
2045                 Point pt = host.peer.getLocationOnScreen();
2046                 for(Component c = this; c != host; c = c.getParent()) {
2047                     pt.x += c.x;
2048                     pt.y += c.y;
2049                 }
2050                 return pt;
2051             } else {
2052                 Point pt = peer.getLocationOnScreen();
2053                 return pt;
2054             }
2055         } else {
2056             throw new IllegalComponentStateException("component must be showing on the screen to determine its location");
2057         }
2058     }
2059 
2060 
2061     /**
2062      * @deprecated As of JDK version 1.1,
2063      * replaced by <code>getLocation()</code>.
2064      */
2065     @Deprecated
2066     public Point location() {
2067         return location_NoClientCode();
2068     }
2069 
2070     private Point location_NoClientCode() {
2071         return new Point(x, y);
2072     }
2073 
2074     /**
2075      * Moves this component to a new location. The top-left corner of
2076      * the new location is specified by the <code>x</code> and <code>y</code>
2077      * parameters in the coordinate space of this component's parent.
2078      * <p>
2079      * This method changes layout-related information, and therefore,
2080      * invalidates the component hierarchy.
2081      *
2082      * @param x the <i>x</i>-coordinate of the new location's
2083      *          top-left corner in the parent's coordinate space
2084      * @param y the <i>y</i>-coordinate of the new location's
2085      *          top-left corner in the parent's coordinate space
2086      * @see #getLocation
2087      * @see #setBounds
2088      * @see #invalidate
2089      * @since JDK1.1
2090      */
2091     public void setLocation(int x, int y) {
2092         move(x, y);
2093     }
2094 
2095     /**
2096      * @deprecated As of JDK version 1.1,
2097      * replaced by <code>setLocation(int, int)</code>.
2098      */
2099     @Deprecated
2100     public void move(int x, int y) {
2101         synchronized(getTreeLock()) {
2102             setBoundsOp(ComponentPeer.SET_LOCATION);
2103             setBounds(x, y, width, height);
2104         }
2105     }
2106 
2107     /**
2108      * Moves this component to a new location. The top-left corner of
2109      * the new location is specified by point <code>p</code>. Point
2110      * <code>p</code> is given in the parent's coordinate space.
2111      * <p>
2112      * This method changes layout-related information, and therefore,
2113      * invalidates the component hierarchy.
2114      *
2115      * @param p the point defining the top-left corner
2116      *          of the new location, given in the coordinate space of this
2117      *          component's parent
2118      * @see #getLocation
2119      * @see #setBounds
2120      * @see #invalidate
2121      * @since JDK1.1
2122      */
2123     public void setLocation(Point p) {
2124         setLocation(p.x, p.y);
2125     }
2126 
2127     /**
2128      * Returns the size of this component in the form of a
2129      * <code>Dimension</code> object. The <code>height</code>
2130      * field of the <code>Dimension</code> object contains
2131      * this component's height, and the <code>width</code>
2132      * field of the <code>Dimension</code> object contains
2133      * this component's width.
2134      * @return a <code>Dimension</code> object that indicates the
2135      *          size of this component
2136      * @see #setSize
2137      * @since JDK1.1
2138      */
2139     public Dimension getSize() {
2140         return size();
2141     }
2142 
2143     /**
2144      * @deprecated As of JDK version 1.1,
2145      * replaced by <code>getSize()</code>.
2146      */
2147     @Deprecated
2148     public Dimension size() {
2149         return new Dimension(width, height);
2150     }
2151 
2152     /**
2153      * Resizes this component so that it has width <code>width</code>
2154      * and height <code>height</code>.
2155      * <p>
2156      * This method changes layout-related information, and therefore,
2157      * invalidates the component hierarchy.
2158      *
2159      * @param width the new width of this component in pixels
2160      * @param height the new height of this component in pixels
2161      * @see #getSize
2162      * @see #setBounds
2163      * @see #invalidate
2164      * @since JDK1.1
2165      */
2166     public void setSize(int width, int height) {
2167         resize(width, height);
2168     }
2169 
2170     /**
2171      * @deprecated As of JDK version 1.1,
2172      * replaced by <code>setSize(int, int)</code>.
2173      */
2174     @Deprecated
2175     public void resize(int width, int height) {
2176         synchronized(getTreeLock()) {
2177             setBoundsOp(ComponentPeer.SET_SIZE);
2178             setBounds(x, y, width, height);
2179         }
2180     }
2181 
2182     /**
2183      * Resizes this component so that it has width <code>d.width</code>
2184      * and height <code>d.height</code>.
2185      * <p>
2186      * This method changes layout-related information, and therefore,
2187      * invalidates the component hierarchy.
2188      *
2189      * @param d the dimension specifying the new size
2190      *          of this component
2191      * @throws NullPointerException if {@code d} is {@code null}
2192      * @see #setSize
2193      * @see #setBounds
2194      * @see #invalidate
2195      * @since JDK1.1
2196      */
2197     public void setSize(Dimension d) {
2198         resize(d);
2199     }
2200 
2201     /**
2202      * @deprecated As of JDK version 1.1,
2203      * replaced by <code>setSize(Dimension)</code>.
2204      */
2205     @Deprecated
2206     public void resize(Dimension d) {
2207         setSize(d.width, d.height);
2208     }
2209 
2210     /**
2211      * Gets the bounds of this component in the form of a
2212      * <code>Rectangle</code> object. The bounds specify this
2213      * component's width, height, and location relative to
2214      * its parent.
2215      * @return a rectangle indicating this component's bounds
2216      * @see #setBounds
2217      * @see #getLocation
2218      * @see #getSize
2219      */
2220     public Rectangle getBounds() {
2221         return bounds();
2222     }
2223 
2224     /**
2225      * @deprecated As of JDK version 1.1,
2226      * replaced by <code>getBounds()</code>.
2227      */
2228     @Deprecated
2229     public Rectangle bounds() {
2230         return new Rectangle(x, y, width, height);
2231     }
2232 
2233     /**
2234      * Moves and resizes this component. The new location of the top-left
2235      * corner is specified by <code>x</code> and <code>y</code>, and the
2236      * new size is specified by <code>width</code> and <code>height</code>.
2237      * <p>
2238      * This method changes layout-related information, and therefore,
2239      * invalidates the component hierarchy.
2240      *
2241      * @param x the new <i>x</i>-coordinate of this component
2242      * @param y the new <i>y</i>-coordinate of this component
2243      * @param width the new <code>width</code> of this component
2244      * @param height the new <code>height</code> of this
2245      *          component
2246      * @see #getBounds
2247      * @see #setLocation(int, int)
2248      * @see #setLocation(Point)
2249      * @see #setSize(int, int)
2250      * @see #setSize(Dimension)
2251      * @see #invalidate
2252      * @since JDK1.1
2253      */
2254     public void setBounds(int x, int y, int width, int height) {
2255         reshape(x, y, width, height);
2256     }
2257 
2258     /**
2259      * @deprecated As of JDK version 1.1,
2260      * replaced by <code>setBounds(int, int, int, int)</code>.
2261      */
2262     @Deprecated
2263     public void reshape(int x, int y, int width, int height) {
2264         synchronized (getTreeLock()) {
2265             try {
2266                 setBoundsOp(ComponentPeer.SET_BOUNDS);
2267                 boolean resized = (this.width != width) || (this.height != height);
2268                 boolean moved = (this.x != x) || (this.y != y);
2269                 if (!resized && !moved) {
2270                     return;
2271                 }
2272                 int oldX = this.x;
2273                 int oldY = this.y;
2274                 int oldWidth = this.width;
2275                 int oldHeight = this.height;
2276                 this.x = x;
2277                 this.y = y;
2278                 this.width = width;
2279                 this.height = height;
2280 
2281                 if (resized) {
2282                     isPacked = false;
2283                 }
2284 
2285                 boolean needNotify = true;
2286                 mixOnReshaping();
2287                 if (peer != null) {
2288                     // LightwightPeer is an empty stub so can skip peer.reshape
2289                     if (!(peer instanceof LightweightPeer)) {
2290                         reshapeNativePeer(x, y, width, height, getBoundsOp());
2291                         // Check peer actualy changed coordinates
2292                         resized = (oldWidth != this.width) || (oldHeight != this.height);
2293                         moved = (oldX != this.x) || (oldY != this.y);
2294                         // fix for 5025858: do not send ComponentEvents for toplevel
2295                         // windows here as it is done from peer or native code when
2296                         // the window is really resized or moved, otherwise some
2297                         // events may be sent twice
2298                         if (this instanceof Window) {
2299                             needNotify = false;
2300                         }
2301                     }
2302                     if (resized) {
2303                         invalidate();
2304                     }
2305                     if (parent != null) {
2306                         parent.invalidateIfValid();
2307                     }
2308                 }
2309                 if (needNotify) {
2310                     notifyNewBounds(resized, moved);
2311                 }
2312                 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight);
2313             } finally {
2314                 setBoundsOp(ComponentPeer.RESET_OPERATION);
2315             }
2316         }
2317     }
2318 
2319     private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth,
2320                                        int oldHeight)
2321     {
2322         if (parent != null && peer instanceof LightweightPeer && isShowing()) {
2323             // Have the parent redraw the area this component occupied.
2324             parent.repaint(oldX, oldY, oldWidth, oldHeight);
2325             // Have the parent redraw the area this component *now* occupies.
2326             repaint();
2327         }
2328     }
2329 
2330     private void reshapeNativePeer(int x, int y, int width, int height, int op) {
2331         // native peer might be offset by more than direct
2332         // parent since parent might be lightweight.
2333         int nativeX = x;
2334         int nativeY = y;
2335         for (Component c = parent;
2336              (c != null) && (c.peer instanceof LightweightPeer);
2337              c = c.parent)
2338         {
2339             nativeX += c.x;
2340             nativeY += c.y;
2341         }
2342         peer.setBounds(nativeX, nativeY, width, height, op);
2343     }
2344 
2345     @SuppressWarnings("deprecation")
2346     private void notifyNewBounds(boolean resized, boolean moved) {
2347         if (componentListener != null
2348             || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0
2349             || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK))
2350             {
2351                 if (resized) {
2352                     ComponentEvent e = new ComponentEvent(this,
2353                                                           ComponentEvent.COMPONENT_RESIZED);
2354                     Toolkit.getEventQueue().postEvent(e);
2355                 }
2356                 if (moved) {
2357                     ComponentEvent e = new ComponentEvent(this,
2358                                                           ComponentEvent.COMPONENT_MOVED);
2359                     Toolkit.getEventQueue().postEvent(e);
2360                 }
2361             } else {
2362                 if (this instanceof Container && ((Container)this).countComponents() > 0) {
2363                     boolean enabledOnToolkit =
2364                         Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
2365                     if (resized) {
2366 
2367                         ((Container)this).createChildHierarchyEvents(
2368                                                                      HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);
2369                     }
2370                     if (moved) {
2371                         ((Container)this).createChildHierarchyEvents(
2372                                                                      HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);
2373                     }
2374                 }
2375                 }
2376     }
2377 
2378     /**
2379      * Moves and resizes this component to conform to the new
2380      * bounding rectangle <code>r</code>. This component's new
2381      * position is specified by <code>r.x</code> and <code>r.y</code>,
2382      * and its new size is specified by <code>r.width</code> and
2383      * <code>r.height</code>
2384      * <p>
2385      * This method changes layout-related information, and therefore,
2386      * invalidates the component hierarchy.
2387      *
2388      * @param r the new bounding rectangle for this component
2389      * @throws NullPointerException if {@code r} is {@code null}
2390      * @see       #getBounds
2391      * @see       #setLocation(int, int)
2392      * @see       #setLocation(Point)
2393      * @see       #setSize(int, int)
2394      * @see       #setSize(Dimension)
2395      * @see #invalidate
2396      * @since     JDK1.1
2397      */
2398     public void setBounds(Rectangle r) {
2399         setBounds(r.x, r.y, r.width, r.height);
2400     }
2401 
2402 
2403     /**
2404      * Returns the current x coordinate of the components origin.
2405      * This method is preferable to writing
2406      * <code>component.getBounds().x</code>,
2407      * or <code>component.getLocation().x</code> because it doesn't
2408      * cause any heap allocations.
2409      *
2410      * @return the current x coordinate of the components origin
2411      * @since 1.2
2412      */
2413     public int getX() {
2414         return x;
2415     }
2416 
2417 
2418     /**
2419      * Returns the current y coordinate of the components origin.
2420      * This method is preferable to writing
2421      * <code>component.getBounds().y</code>,
2422      * or <code>component.getLocation().y</code> because it
2423      * doesn't cause any heap allocations.
2424      *
2425      * @return the current y coordinate of the components origin
2426      * @since 1.2
2427      */
2428     public int getY() {
2429         return y;
2430     }
2431 
2432 
2433     /**
2434      * Returns the current width of this component.
2435      * This method is preferable to writing
2436      * <code>component.getBounds().width</code>,
2437      * or <code>component.getSize().width</code> because it
2438      * doesn't cause any heap allocations.
2439      *
2440      * @return the current width of this component
2441      * @since 1.2
2442      */
2443     public int getWidth() {
2444         return width;
2445     }
2446 
2447 
2448     /**
2449      * Returns the current height of this component.
2450      * This method is preferable to writing
2451      * <code>component.getBounds().height</code>,
2452      * or <code>component.getSize().height</code> because it
2453      * doesn't cause any heap allocations.
2454      *
2455      * @return the current height of this component
2456      * @since 1.2
2457      */
2458     public int getHeight() {
2459         return height;
2460     }
2461 
2462     /**
2463      * Stores the bounds of this component into "return value" <b>rv</b> and
2464      * return <b>rv</b>.  If rv is <code>null</code> a new
2465      * <code>Rectangle</code> is allocated.
2466      * This version of <code>getBounds</code> is useful if the caller
2467      * wants to avoid allocating a new <code>Rectangle</code> object
2468      * on the heap.
2469      *
2470      * @param rv the return value, modified to the components bounds
2471      * @return rv
2472      */
2473     public Rectangle getBounds(Rectangle rv) {
2474         if (rv == null) {
2475             return new Rectangle(getX(), getY(), getWidth(), getHeight());
2476         }
2477         else {
2478             rv.setBounds(getX(), getY(), getWidth(), getHeight());
2479             return rv;
2480         }
2481     }
2482 
2483     /**
2484      * Stores the width/height of this component into "return value" <b>rv</b>
2485      * and return <b>rv</b>.   If rv is <code>null</code> a new
2486      * <code>Dimension</code> object is allocated.  This version of
2487      * <code>getSize</code> is useful if the caller wants to avoid
2488      * allocating a new <code>Dimension</code> object on the heap.
2489      *
2490      * @param rv the return value, modified to the components size
2491      * @return rv
2492      */
2493     public Dimension getSize(Dimension rv) {
2494         if (rv == null) {
2495             return new Dimension(getWidth(), getHeight());
2496         }
2497         else {
2498             rv.setSize(getWidth(), getHeight());
2499             return rv;
2500         }
2501     }
2502 
2503     /**
2504      * Stores the x,y origin of this component into "return value" <b>rv</b>
2505      * and return <b>rv</b>.   If rv is <code>null</code> a new
2506      * <code>Point</code> is allocated.
2507      * This version of <code>getLocation</code> is useful if the
2508      * caller wants to avoid allocating a new <code>Point</code>
2509      * object on the heap.
2510      *
2511      * @param rv the return value, modified to the components location
2512      * @return rv
2513      */
2514     public Point getLocation(Point rv) {
2515         if (rv == null) {
2516             return new Point(getX(), getY());
2517         }
2518         else {
2519             rv.setLocation(getX(), getY());
2520             return rv;
2521         }
2522     }
2523 
2524     /**
2525      * Returns true if this component is completely opaque, returns
2526      * false by default.
2527      * <p>
2528      * An opaque component paints every pixel within its
2529      * rectangular region. A non-opaque component paints only some of
2530      * its pixels, allowing the pixels underneath it to "show through".
2531      * A component that does not fully paint its pixels therefore
2532      * provides a degree of transparency.
2533      * <p>
2534      * Subclasses that guarantee to always completely paint their
2535      * contents should override this method and return true.
2536      *
2537      * @return true if this component is completely opaque
2538      * @see #isLightweight
2539      * @since 1.2
2540      */
2541     public boolean isOpaque() {
2542         if (getPeer() == null) {
2543             return false;
2544         }
2545         else {
2546             return !isLightweight();
2547         }
2548     }
2549 
2550 
2551     /**
2552      * A lightweight component doesn't have a native toolkit peer.
2553      * Subclasses of <code>Component</code> and <code>Container</code>,
2554      * other than the ones defined in this package like <code>Button</code>
2555      * or <code>Scrollbar</code>, are lightweight.
2556      * All of the Swing components are lightweights.
2557      * <p>
2558      * This method will always return <code>false</code> if this component
2559      * is not displayable because it is impossible to determine the
2560      * weight of an undisplayable component.
2561      *
2562      * @return true if this component has a lightweight peer; false if
2563      *         it has a native peer or no peer
2564      * @see #isDisplayable
2565      * @since 1.2
2566      */
2567     public boolean isLightweight() {
2568         return getPeer() instanceof LightweightPeer;
2569     }
2570 
2571 
2572     /**
2573      * Sets the preferred size of this component to a constant
2574      * value.  Subsequent calls to <code>getPreferredSize</code> will always
2575      * return this value.  Setting the preferred size to <code>null</code>
2576      * restores the default behavior.
2577      *
2578      * @param preferredSize The new preferred size, or null
2579      * @see #getPreferredSize
2580      * @see #isPreferredSizeSet
2581      * @since 1.5
2582      */
2583     public void setPreferredSize(Dimension preferredSize) {
2584         Dimension old;
2585         // If the preferred size was set, use it as the old value, otherwise
2586         // use null to indicate we didn't previously have a set preferred
2587         // size.
2588         if (prefSizeSet) {
2589             old = this.prefSize;
2590         }
2591         else {
2592             old = null;
2593         }
2594         this.prefSize = preferredSize;
2595         prefSizeSet = (preferredSize != null);
2596         firePropertyChange("preferredSize", old, preferredSize);
2597     }
2598 
2599 
2600     /**
2601      * Returns true if the preferred size has been set to a
2602      * non-<code>null</code> value otherwise returns false.
2603      *
2604      * @return true if <code>setPreferredSize</code> has been invoked
2605      *         with a non-null value.
2606      * @since 1.5
2607      */
2608     public boolean isPreferredSizeSet() {
2609         return prefSizeSet;
2610     }
2611 
2612 
2613     /**
2614      * Gets the preferred size of this component.
2615      * @return a dimension object indicating this component's preferred size
2616      * @see #getMinimumSize
2617      * @see LayoutManager
2618      */
2619     public Dimension getPreferredSize() {
2620         return preferredSize();
2621     }
2622 
2623 
2624     /**
2625      * @deprecated As of JDK version 1.1,
2626      * replaced by <code>getPreferredSize()</code>.
2627      */
2628     @Deprecated
2629     public Dimension preferredSize() {
2630         /* Avoid grabbing the lock if a reasonable cached size value
2631          * is available.
2632          */
2633         Dimension dim = prefSize;
2634         if (dim == null || !(isPreferredSizeSet() || isValid())) {
2635             synchronized (getTreeLock()) {
2636                 prefSize = (peer != null) ?
2637                     peer.getPreferredSize() :
2638                     getMinimumSize();
2639                 dim = prefSize;
2640             }
2641         }
2642         return new Dimension(dim);
2643     }
2644 
2645     /**
2646      * Sets the minimum size of this component to a constant
2647      * value.  Subsequent calls to <code>getMinimumSize</code> will always
2648      * return this value.  Setting the minimum size to <code>null</code>
2649      * restores the default behavior.
2650      *
2651      * @param minimumSize the new minimum size of this component
2652      * @see #getMinimumSize
2653      * @see #isMinimumSizeSet
2654      * @since 1.5
2655      */
2656     public void setMinimumSize(Dimension minimumSize) {
2657         Dimension old;
2658         // If the minimum size was set, use it as the old value, otherwise
2659         // use null to indicate we didn't previously have a set minimum
2660         // size.
2661         if (minSizeSet) {
2662             old = this.minSize;
2663         }
2664         else {
2665             old = null;
2666         }
2667         this.minSize = minimumSize;
2668         minSizeSet = (minimumSize != null);
2669         firePropertyChange("minimumSize", old, minimumSize);
2670     }
2671 
2672     /**
2673      * Returns whether or not <code>setMinimumSize</code> has been
2674      * invoked with a non-null value.
2675      *
2676      * @return true if <code>setMinimumSize</code> has been invoked with a
2677      *              non-null value.
2678      * @since 1.5
2679      */
2680     public boolean isMinimumSizeSet() {
2681         return minSizeSet;
2682     }
2683 
2684     /**
2685      * Gets the minimum size of this component.
2686      * @return a dimension object indicating this component's minimum size
2687      * @see #getPreferredSize
2688      * @see LayoutManager
2689      */
2690     public Dimension getMinimumSize() {
2691         return minimumSize();
2692     }
2693 
2694     /**
2695      * @deprecated As of JDK version 1.1,
2696      * replaced by <code>getMinimumSize()</code>.
2697      */
2698     @Deprecated
2699     public Dimension minimumSize() {
2700         /* Avoid grabbing the lock if a reasonable cached size value
2701          * is available.
2702          */
2703         Dimension dim = minSize;
2704         if (dim == null || !(isMinimumSizeSet() || isValid())) {
2705             synchronized (getTreeLock()) {
2706                 minSize = (peer != null) ?
2707                     peer.getMinimumSize() :
2708                     size();
2709                 dim = minSize;
2710             }
2711         }
2712         return new Dimension(dim);
2713     }
2714 
2715     /**
2716      * Sets the maximum size of this component to a constant
2717      * value.  Subsequent calls to <code>getMaximumSize</code> will always
2718      * return this value.  Setting the maximum size to <code>null</code>
2719      * restores the default behavior.
2720      *
2721      * @param maximumSize a <code>Dimension</code> containing the
2722      *          desired maximum allowable size
2723      * @see #getMaximumSize
2724      * @see #isMaximumSizeSet
2725      * @since 1.5
2726      */
2727     public void setMaximumSize(Dimension maximumSize) {
2728         // If the maximum size was set, use it as the old value, otherwise
2729         // use null to indicate we didn't previously have a set maximum
2730         // size.
2731         Dimension old;
2732         if (maxSizeSet) {
2733             old = this.maxSize;
2734         }
2735         else {
2736             old = null;
2737         }
2738         this.maxSize = maximumSize;
2739         maxSizeSet = (maximumSize != null);
2740         firePropertyChange("maximumSize", old, maximumSize);
2741     }
2742 
2743     /**
2744      * Returns true if the maximum size has been set to a non-<code>null</code>
2745      * value otherwise returns false.
2746      *
2747      * @return true if <code>maximumSize</code> is non-<code>null</code>,
2748      *          false otherwise
2749      * @since 1.5
2750      */
2751     public boolean isMaximumSizeSet() {
2752         return maxSizeSet;
2753     }
2754 
2755     /**
2756      * Gets the maximum size of this component.
2757      * @return a dimension object indicating this component's maximum size
2758      * @see #getMinimumSize
2759      * @see #getPreferredSize
2760      * @see LayoutManager
2761      */
2762     public Dimension getMaximumSize() {
2763         if (isMaximumSizeSet()) {
2764             return new Dimension(maxSize);
2765         }
2766         return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
2767     }
2768 
2769     /**
2770      * Returns the alignment along the x axis.  This specifies how
2771      * the component would like to be aligned relative to other
2772      * components.  The value should be a number between 0 and 1
2773      * where 0 represents alignment along the origin, 1 is aligned
2774      * the furthest away from the origin, 0.5 is centered, etc.
2775      */
2776     public float getAlignmentX() {
2777         return CENTER_ALIGNMENT;
2778     }
2779 
2780     /**
2781      * Returns the alignment along the y axis.  This specifies how
2782      * the component would like to be aligned relative to other
2783      * components.  The value should be a number between 0 and 1
2784      * where 0 represents alignment along the origin, 1 is aligned
2785      * the furthest away from the origin, 0.5 is centered, etc.
2786      */
2787     public float getAlignmentY() {
2788         return CENTER_ALIGNMENT;
2789     }
2790 
2791     /**
2792      * Returns the baseline.  The baseline is measured from the top of
2793      * the component.  This method is primarily meant for
2794      * <code>LayoutManager</code>s to align components along their
2795      * baseline.  A return value less than 0 indicates this component
2796      * does not have a reasonable baseline and that
2797      * <code>LayoutManager</code>s should not align this component on
2798      * its baseline.
2799      * <p>
2800      * The default implementation returns -1.  Subclasses that support
2801      * baseline should override appropriately.  If a value &gt;= 0 is
2802      * returned, then the component has a valid baseline for any
2803      * size &gt;= the minimum size and <code>getBaselineResizeBehavior</code>
2804      * can be used to determine how the baseline changes with size.
2805      *
2806      * @param width the width to get the baseline for
2807      * @param height the height to get the baseline for
2808      * @return the baseline or &lt; 0 indicating there is no reasonable
2809      *         baseline
2810      * @throws IllegalArgumentException if width or height is &lt; 0
2811      * @see #getBaselineResizeBehavior
2812      * @see java.awt.FontMetrics
2813      * @since 1.6
2814      */
2815     public int getBaseline(int width, int height) {
2816         if (width < 0 || height < 0) {
2817             throw new IllegalArgumentException(
2818                     "Width and height must be >= 0");
2819         }
2820         return -1;
2821     }
2822 
2823     /**
2824      * Returns an enum indicating how the baseline of the component
2825      * changes as the size changes.  This method is primarily meant for
2826      * layout managers and GUI builders.
2827      * <p>
2828      * The default implementation returns
2829      * <code>BaselineResizeBehavior.OTHER</code>.  Subclasses that have a
2830      * baseline should override appropriately.  Subclasses should
2831      * never return <code>null</code>; if the baseline can not be
2832      * calculated return <code>BaselineResizeBehavior.OTHER</code>.  Callers
2833      * should first ask for the baseline using
2834      * <code>getBaseline</code> and if a value &gt;= 0 is returned use
2835      * this method.  It is acceptable for this method to return a
2836      * value other than <code>BaselineResizeBehavior.OTHER</code> even if
2837      * <code>getBaseline</code> returns a value less than 0.
2838      *
2839      * @return an enum indicating how the baseline changes as the component
2840      *         size changes
2841      * @see #getBaseline(int, int)
2842      * @since 1.6
2843      */
2844     public BaselineResizeBehavior getBaselineResizeBehavior() {
2845         return BaselineResizeBehavior.OTHER;
2846     }
2847 
2848     /**
2849      * Prompts the layout manager to lay out this component. This is
2850      * usually called when the component (more specifically, container)
2851      * is validated.
2852      * @see #validate
2853      * @see LayoutManager
2854      */
2855     public void doLayout() {
2856         layout();
2857     }
2858 
2859     /**
2860      * @deprecated As of JDK version 1.1,
2861      * replaced by <code>doLayout()</code>.
2862      */
2863     @Deprecated
2864     public void layout() {
2865     }
2866 
2867     /**
2868      * Validates this component.
2869      * <p>
2870      * The meaning of the term <i>validating</i> is defined by the ancestors of
2871      * this class. See {@link Container#validate} for more details.
2872      *
2873      * @see       #invalidate
2874      * @see       #doLayout()
2875      * @see       LayoutManager
2876      * @see       Container#validate
2877      * @since     JDK1.0
2878      */
2879     public void validate() {
2880         synchronized (getTreeLock()) {
2881             ComponentPeer peer = this.peer;
2882             boolean wasValid = isValid();
2883             if (!wasValid && peer != null) {
2884                 Font newfont = getFont();
2885                 Font oldfont = peerFont;
2886                 if (newfont != oldfont && (oldfont == null
2887                                            || !oldfont.equals(newfont))) {
2888                     peer.setFont(newfont);
2889                     peerFont = newfont;
2890                 }
2891                 peer.layout();
2892             }
2893             valid = true;
2894             if (!wasValid) {
2895                 mixOnValidating();
2896             }
2897         }
2898     }
2899 
2900     /**
2901      * Invalidates this component and its ancestors.
2902      * <p>
2903      * By default, all the ancestors of the component up to the top-most
2904      * container of the hierarchy are marked invalid. If the {@code
2905      * java.awt.smartInvalidate} system property is set to {@code true},
2906      * invalidation stops on the nearest validate root of this component.
2907      * Marking a container <i>invalid</i> indicates that the container needs to
2908      * be laid out.
2909      * <p>
2910      * This method is called automatically when any layout-related information
2911      * changes (e.g. setting the bounds of the component, or adding the
2912      * component to a container).
2913      * <p>
2914      * This method might be called often, so it should work fast.
2915      *
2916      * @see       #validate
2917      * @see       #doLayout
2918      * @see       LayoutManager
2919      * @see       java.awt.Container#isValidateRoot
2920      * @since     JDK1.0
2921      */
2922     public void invalidate() {
2923         synchronized (getTreeLock()) {
2924             /* Nullify cached layout and size information.
2925              * For efficiency, propagate invalidate() upwards only if
2926              * some other component hasn't already done so first.
2927              */
2928             valid = false;
2929             if (!isPreferredSizeSet()) {
2930                 prefSize = null;
2931             }
2932             if (!isMinimumSizeSet()) {
2933                 minSize = null;
2934             }
2935             if (!isMaximumSizeSet()) {
2936                 maxSize = null;
2937             }
2938             invalidateParent();
2939         }
2940     }
2941 
2942     /**
2943      * Invalidates the parent of this component if any.
2944      *
2945      * This method MUST BE invoked under the TreeLock.
2946      */
2947     void invalidateParent() {
2948         if (parent != null) {
2949             parent.invalidateIfValid();
2950         }
2951     }
2952 
2953     /** Invalidates the component unless it is already invalid.
2954      */
2955     final void invalidateIfValid() {
2956         if (isValid()) {
2957             invalidate();
2958         }
2959     }
2960 
2961     /**
2962      * Revalidates the component hierarchy up to the nearest validate root.
2963      * <p>
2964      * This method first invalidates the component hierarchy starting from this
2965      * component up to the nearest validate root. Afterwards, the component
2966      * hierarchy is validated starting from the nearest validate root.
2967      * <p>
2968      * This is a convenience method supposed to help application developers
2969      * avoid looking for validate roots manually. Basically, it's equivalent to
2970      * first calling the {@link #invalidate()} method on this component, and
2971      * then calling the {@link #validate()} method on the nearest validate
2972      * root.
2973      *
2974      * @see Container#isValidateRoot
2975      * @since 1.7
2976      */
2977     public void revalidate() {
2978         revalidateSynchronously();
2979     }
2980 
2981     /**
2982      * Revalidates the component synchronously.
2983      */
2984     final void revalidateSynchronously() {
2985         synchronized (getTreeLock()) {
2986             invalidate();
2987 
2988             Container root = getContainer();
2989             if (root == null) {
2990                 // There's no parents. Just validate itself.
2991                 validate();
2992             } else {
2993                 while (!root.isValidateRoot()) {
2994                     if (root.getContainer() == null) {
2995                         // If there's no validate roots, we'll validate the
2996                         // topmost container
2997                         break;
2998                     }
2999 
3000                     root = root.getContainer();
3001                 }
3002 
3003                 root.validate();
3004             }
3005         }
3006     }
3007 
3008     /**
3009      * Creates a graphics context for this component. This method will
3010      * return <code>null</code> if this component is currently not
3011      * displayable.
3012      * @return a graphics context for this component, or <code>null</code>
3013      *             if it has none
3014      * @see       #paint
3015      * @since     JDK1.0
3016      */
3017     public Graphics getGraphics() {
3018         if (peer instanceof LightweightPeer) {
3019             // This is for a lightweight component, need to
3020             // translate coordinate spaces and clip relative
3021             // to the parent.
3022             if (parent == null) return null;
3023             Graphics g = parent.getGraphics();
3024             if (g == null) return null;
3025             if (g instanceof ConstrainableGraphics) {
3026                 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3027             } else {
3028                 g.translate(x,y);
3029                 g.setClip(0, 0, width, height);
3030             }
3031             g.setFont(getFont());
3032             return g;
3033         } else {
3034             ComponentPeer peer = this.peer;
3035             return (peer != null) ? peer.getGraphics() : null;
3036         }
3037     }
3038 
3039     final Graphics getGraphics_NoClientCode() {
3040         ComponentPeer peer = this.peer;
3041         if (peer instanceof LightweightPeer) {
3042             // This is for a lightweight component, need to
3043             // translate coordinate spaces and clip relative
3044             // to the parent.
3045             Container parent = this.parent;
3046             if (parent == null) return null;
3047             Graphics g = parent.getGraphics_NoClientCode();
3048             if (g == null) return null;
3049             if (g instanceof ConstrainableGraphics) {
3050                 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3051             } else {
3052                 g.translate(x,y);
3053                 g.setClip(0, 0, width, height);
3054             }
3055             g.setFont(getFont_NoClientCode());
3056             return g;
3057         } else {
3058             return (peer != null) ? peer.getGraphics() : null;
3059         }
3060     }
3061 
3062     /**
3063      * Gets the font metrics for the specified font.
3064      * Warning: Since Font metrics are affected by the
3065      * {@link java.awt.font.FontRenderContext FontRenderContext} and
3066      * this method does not provide one, it can return only metrics for
3067      * the default render context which may not match that used when
3068      * rendering on the Component if {@link Graphics2D} functionality is being
3069      * used. Instead metrics can be obtained at rendering time by calling
3070      * {@link Graphics#getFontMetrics()} or text measurement APIs on the
3071      * {@link Font Font} class.
3072      * @param font the font for which font metrics is to be
3073      *          obtained
3074      * @return the font metrics for <code>font</code>
3075      * @see       #getFont
3076      * @see       #getPeer
3077      * @see       java.awt.peer.ComponentPeer#getFontMetrics(Font)
3078      * @see       Toolkit#getFontMetrics(Font)
3079      * @since     JDK1.0
3080      */
3081     public FontMetrics getFontMetrics(Font font) {
3082         // This is an unsupported hack, but left in for a customer.
3083         // Do not remove.
3084         FontManager fm = FontManagerFactory.getInstance();
3085         if (fm instanceof SunFontManager
3086             && ((SunFontManager) fm).usePlatformFontMetrics()) {
3087 
3088             if (peer != null &&
3089                 !(peer instanceof LightweightPeer)) {
3090                 return peer.getFontMetrics(font);
3091             }
3092         }
3093         return sun.font.FontDesignMetrics.getMetrics(font);
3094     }
3095 
3096     /**
3097      * Sets the cursor image to the specified cursor.  This cursor
3098      * image is displayed when the <code>contains</code> method for
3099      * this component returns true for the current cursor location, and
3100      * this Component is visible, displayable, and enabled. Setting the
3101      * cursor of a <code>Container</code> causes that cursor to be displayed
3102      * within all of the container's subcomponents, except for those
3103      * that have a non-<code>null</code> cursor.
3104      * <p>
3105      * The method may have no visual effect if the Java platform
3106      * implementation and/or the native system do not support
3107      * changing the mouse cursor shape.
3108      * @param cursor One of the constants defined
3109      *          by the <code>Cursor</code> class;
3110      *          if this parameter is <code>null</code>
3111      *          then this component will inherit
3112      *          the cursor of its parent
3113      * @see       #isEnabled
3114      * @see       #isShowing
3115      * @see       #getCursor
3116      * @see       #contains
3117      * @see       Toolkit#createCustomCursor
3118      * @see       Cursor
3119      * @since     JDK1.1
3120      */
3121     public void setCursor(Cursor cursor) {
3122         this.cursor = cursor;
3123         updateCursorImmediately();
3124     }
3125 
3126     /**
3127      * Updates the cursor.  May not be invoked from the native
3128      * message pump.
3129      */
3130     final void updateCursorImmediately() {
3131         if (peer instanceof LightweightPeer) {
3132             Container nativeContainer = getNativeContainer();
3133 
3134             if (nativeContainer == null) return;
3135 
3136             ComponentPeer cPeer = nativeContainer.getPeer();
3137 
3138             if (cPeer != null) {
3139                 cPeer.updateCursorImmediately();
3140             }
3141         } else if (peer != null) {
3142             peer.updateCursorImmediately();
3143         }
3144     }
3145 
3146     /**
3147      * Gets the cursor set in the component. If the component does
3148      * not have a cursor set, the cursor of its parent is returned.
3149      * If no cursor is set in the entire hierarchy,
3150      * <code>Cursor.DEFAULT_CURSOR</code> is returned.
3151      * @see #setCursor
3152      * @since      JDK1.1
3153      */
3154     public Cursor getCursor() {
3155         return getCursor_NoClientCode();
3156     }
3157 
3158     final Cursor getCursor_NoClientCode() {
3159         Cursor cursor = this.cursor;
3160         if (cursor != null) {
3161             return cursor;
3162         }
3163         Container parent = this.parent;
3164         if (parent != null) {
3165             return parent.getCursor_NoClientCode();
3166         } else {
3167             return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
3168         }
3169     }
3170 
3171     /**
3172      * Returns whether the cursor has been explicitly set for this Component.
3173      * If this method returns <code>false</code>, this Component is inheriting
3174      * its cursor from an ancestor.
3175      *
3176      * @return <code>true</code> if the cursor has been explicitly set for this
3177      *         Component; <code>false</code> otherwise.
3178      * @since 1.4
3179      */
3180     public boolean isCursorSet() {
3181         return (cursor != null);
3182     }
3183 
3184     /**
3185      * Paints this component.
3186      * <p>
3187      * This method is called when the contents of the component should
3188      * be painted; such as when the component is first being shown or
3189      * is damaged and in need of repair.  The clip rectangle in the
3190      * <code>Graphics</code> parameter is set to the area
3191      * which needs to be painted.
3192      * Subclasses of <code>Component</code> that override this
3193      * method need not call <code>super.paint(g)</code>.
3194      * <p>
3195      * For performance reasons, <code>Component</code>s with zero width
3196      * or height aren't considered to need painting when they are first shown,
3197      * and also aren't considered to need repair.
3198      * <p>
3199      * <b>Note</b>: For more information on the paint mechanisms utilitized
3200      * by AWT and Swing, including information on how to write the most
3201      * efficient painting code, see
3202      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3203      *
3204      * @param g the graphics context to use for painting
3205      * @see       #update
3206      * @since     JDK1.0
3207      */
3208     public void paint(Graphics g) {
3209     }
3210 
3211     /**
3212      * Updates this component.
3213      * <p>
3214      * If this component is not a lightweight component, the
3215      * AWT calls the <code>update</code> method in response to
3216      * a call to <code>repaint</code>.  You can assume that
3217      * the background is not cleared.
3218      * <p>
3219      * The <code>update</code> method of <code>Component</code>
3220      * calls this component's <code>paint</code> method to redraw
3221      * this component.  This method is commonly overridden by subclasses
3222      * which need to do additional work in response to a call to
3223      * <code>repaint</code>.
3224      * Subclasses of Component that override this method should either
3225      * call <code>super.update(g)</code>, or call <code>paint(g)</code>
3226      * directly from their <code>update</code> method.
3227      * <p>
3228      * The origin of the graphics context, its
3229      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3230      * top-left corner of this component. The clipping region of the
3231      * graphics context is the bounding rectangle of this component.
3232      *
3233      * <p>
3234      * <b>Note</b>: For more information on the paint mechanisms utilitized
3235      * by AWT and Swing, including information on how to write the most
3236      * efficient painting code, see
3237      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3238      *
3239      * @param g the specified context to use for updating
3240      * @see       #paint
3241      * @see       #repaint()
3242      * @since     JDK1.0
3243      */
3244     public void update(Graphics g) {
3245         paint(g);
3246     }
3247 
3248     /**
3249      * Paints this component and all of its subcomponents.
3250      * <p>
3251      * The origin of the graphics context, its
3252      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3253      * top-left corner of this component. The clipping region of the
3254      * graphics context is the bounding rectangle of this component.
3255      *
3256      * @param     g   the graphics context to use for painting
3257      * @see       #paint
3258      * @since     JDK1.0
3259      */
3260     public void paintAll(Graphics g) {
3261         if (isShowing()) {
3262             GraphicsCallback.PeerPaintCallback.getInstance().
3263                 runOneComponent(this, new Rectangle(0, 0, width, height),
3264                                 g, g.getClip(),
3265                                 GraphicsCallback.LIGHTWEIGHTS |
3266                                 GraphicsCallback.HEAVYWEIGHTS);
3267         }
3268     }
3269 
3270     /**
3271      * Simulates the peer callbacks into java.awt for painting of
3272      * lightweight Components.
3273      * @param     g   the graphics context to use for painting
3274      * @see       #paintAll
3275      */
3276     void lightweightPaint(Graphics g) {
3277         paint(g);
3278     }
3279 
3280     /**
3281      * Paints all the heavyweight subcomponents.
3282      */
3283     void paintHeavyweightComponents(Graphics g) {
3284     }
3285 
3286     /**
3287      * Repaints this component.
3288      * <p>
3289      * If this component is a lightweight component, this method
3290      * causes a call to this component's <code>paint</code>
3291      * method as soon as possible.  Otherwise, this method causes
3292      * a call to this component's <code>update</code> method as soon
3293      * as possible.
3294      * <p>
3295      * <b>Note</b>: For more information on the paint mechanisms utilitized
3296      * by AWT and Swing, including information on how to write the most
3297      * efficient painting code, see
3298      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3299 
3300      *
3301      * @see       #update(Graphics)
3302      * @since     JDK1.0
3303      */
3304     public void repaint() {
3305         repaint(0, 0, 0, width, height);
3306     }
3307 
3308     /**
3309      * Repaints the component.  If this component is a lightweight
3310      * component, this results in a call to <code>paint</code>
3311      * within <code>tm</code> milliseconds.
3312      * <p>
3313      * <b>Note</b>: For more information on the paint mechanisms utilitized
3314      * by AWT and Swing, including information on how to write the most
3315      * efficient painting code, see
3316      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3317      *
3318      * @param tm maximum time in milliseconds before update
3319      * @see #paint
3320      * @see #update(Graphics)
3321      * @since JDK1.0
3322      */
3323     public void repaint(long tm) {
3324         repaint(tm, 0, 0, width, height);
3325     }
3326 
3327     /**
3328      * Repaints the specified rectangle of this component.
3329      * <p>
3330      * If this component is a lightweight component, this method
3331      * causes a call to this component's <code>paint</code> method
3332      * as soon as possible.  Otherwise, this method causes a call to
3333      * this component's <code>update</code> method as soon as possible.
3334      * <p>
3335      * <b>Note</b>: For more information on the paint mechanisms utilitized
3336      * by AWT and Swing, including information on how to write the most
3337      * efficient painting code, see
3338      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3339      *
3340      * @param     x   the <i>x</i> coordinate
3341      * @param     y   the <i>y</i> coordinate
3342      * @param     width   the width
3343      * @param     height  the height
3344      * @see       #update(Graphics)
3345      * @since     JDK1.0
3346      */
3347     public void repaint(int x, int y, int width, int height) {
3348         repaint(0, x, y, width, height);
3349     }
3350 
3351     /**
3352      * Repaints the specified rectangle of this component within
3353      * <code>tm</code> milliseconds.
3354      * <p>
3355      * If this component is a lightweight component, this method causes
3356      * a call to this component's <code>paint</code> method.
3357      * Otherwise, this method causes a call to this component's
3358      * <code>update</code> method.
3359      * <p>
3360      * <b>Note</b>: For more information on the paint mechanisms utilitized
3361      * by AWT and Swing, including information on how to write the most
3362      * efficient painting code, see
3363      * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3364      *
3365      * @param     tm   maximum time in milliseconds before update
3366      * @param     x    the <i>x</i> coordinate
3367      * @param     y    the <i>y</i> coordinate
3368      * @param     width    the width
3369      * @param     height   the height
3370      * @see       #update(Graphics)
3371      * @since     JDK1.0
3372      */
3373     public void repaint(long tm, int x, int y, int width, int height) {
3374         if (this.peer instanceof LightweightPeer) {
3375             // Needs to be translated to parent coordinates since
3376             // a parent native container provides the actual repaint
3377             // services.  Additionally, the request is restricted to
3378             // the bounds of the component.
3379             if (parent != null) {
3380                 if (x < 0) {
3381                     width += x;
3382                     x = 0;
3383                 }
3384                 if (y < 0) {
3385                     height += y;
3386                     y = 0;
3387                 }
3388 
3389                 int pwidth = (width > this.width) ? this.width : width;
3390                 int pheight = (height > this.height) ? this.height : height;
3391 
3392                 if (pwidth <= 0 || pheight <= 0) {
3393                     return;
3394                 }
3395 
3396                 int px = this.x + x;
3397                 int py = this.y + y;
3398                 parent.repaint(tm, px, py, pwidth, pheight);
3399             }
3400         } else {
3401             if (isVisible() && (this.peer != null) &&
3402                 (width > 0) && (height > 0)) {
3403                 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
3404                                               new Rectangle(x, y, width, height));
3405                 Toolkit.getEventQueue().postEvent(e);
3406             }
3407         }
3408     }
3409 
3410     /**
3411      * Prints this component. Applications should override this method
3412      * for components that must do special processing before being
3413      * printed or should be printed differently than they are painted.
3414      * <p>
3415      * The default implementation of this method calls the
3416      * <code>paint</code> method.
3417      * <p>
3418      * The origin of the graphics context, its
3419      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3420      * top-left corner of this component. The clipping region of the
3421      * graphics context is the bounding rectangle of this component.
3422      * @param     g   the graphics context to use for printing
3423      * @see       #paint(Graphics)
3424      * @since     JDK1.0
3425      */
3426     public void print(Graphics g) {
3427         paint(g);
3428     }
3429 
3430     /**
3431      * Prints this component and all of its subcomponents.
3432      * <p>
3433      * The origin of the graphics context, its
3434      * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3435      * top-left corner of this component. The clipping region of the
3436      * graphics context is the bounding rectangle of this component.
3437      * @param     g   the graphics context to use for printing
3438      * @see       #print(Graphics)
3439      * @since     JDK1.0
3440      */
3441     public void printAll(Graphics g) {
3442         if (isShowing()) {
3443             GraphicsCallback.PeerPrintCallback.getInstance().
3444                 runOneComponent(this, new Rectangle(0, 0, width, height),
3445                                 g, g.getClip(),
3446                                 GraphicsCallback.LIGHTWEIGHTS |
3447                                 GraphicsCallback.HEAVYWEIGHTS);
3448         }
3449     }
3450 
3451     /**
3452      * Simulates the peer callbacks into java.awt for printing of
3453      * lightweight Components.
3454      * @param     g   the graphics context to use for printing
3455      * @see       #printAll
3456      */
3457     void lightweightPrint(Graphics g) {
3458         print(g);
3459     }
3460 
3461     /**
3462      * Prints all the heavyweight subcomponents.
3463      */
3464     void printHeavyweightComponents(Graphics g) {
3465     }
3466 
3467     private Insets getInsets_NoClientCode() {
3468         ComponentPeer peer = this.peer;
3469         if (peer instanceof ContainerPeer) {
3470             return (Insets)((ContainerPeer)peer).getInsets().clone();
3471         }
3472         return new Insets(0, 0, 0, 0);
3473     }
3474 
3475     /**
3476      * Repaints the component when the image has changed.
3477      * This <code>imageUpdate</code> method of an <code>ImageObserver</code>
3478      * is called when more information about an
3479      * image which had been previously requested using an asynchronous
3480      * routine such as the <code>drawImage</code> method of
3481      * <code>Graphics</code> becomes available.
3482      * See the definition of <code>imageUpdate</code> for
3483      * more information on this method and its arguments.
3484      * <p>
3485      * The <code>imageUpdate</code> method of <code>Component</code>
3486      * incrementally draws an image on the component as more of the bits
3487      * of the image are available.
3488      * <p>
3489      * If the system property <code>awt.image.incrementaldraw</code>
3490      * is missing or has the value <code>true</code>, the image is
3491      * incrementally drawn. If the system property has any other value,
3492      * then the image is not drawn until it has been completely loaded.
3493      * <p>
3494      * Also, if incremental drawing is in effect, the value of the
3495      * system property <code>awt.image.redrawrate</code> is interpreted
3496      * as an integer to give the maximum redraw rate, in milliseconds. If
3497      * the system property is missing or cannot be interpreted as an
3498      * integer, the redraw rate is once every 100ms.
3499      * <p>
3500      * The interpretation of the <code>x</code>, <code>y</code>,
3501      * <code>width</code>, and <code>height</code> arguments depends on
3502      * the value of the <code>infoflags</code> argument.
3503      *
3504      * @param     img   the image being observed
3505      * @param     infoflags   see <code>imageUpdate</code> for more information
3506      * @param     x   the <i>x</i> coordinate
3507      * @param     y   the <i>y</i> coordinate
3508      * @param     w   the width
3509      * @param     h   the height
3510      * @return    <code>false</code> if the infoflags indicate that the
3511      *            image is completely loaded; <code>true</code> otherwise.
3512      *
3513      * @see     java.awt.image.ImageObserver
3514      * @see     Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
3515      * @see     Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)
3516      * @see     Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
3517      * @see     Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
3518      * @see     java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
3519      * @since   JDK1.0
3520      */
3521     public boolean imageUpdate(Image img, int infoflags,
3522                                int x, int y, int w, int h) {
3523         int rate = -1;
3524         if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
3525             rate = 0;
3526         } else if ((infoflags & SOMEBITS) != 0) {
3527             if (isInc) {
3528                 rate = incRate;
3529                 if (rate < 0) {
3530                     rate = 0;
3531                 }
3532             }
3533         }
3534         if (rate >= 0) {
3535             repaint(rate, 0, 0, width, height);
3536         }
3537         return (infoflags & (ALLBITS|ABORT)) == 0;
3538     }
3539 
3540     /**
3541      * Creates an image from the specified image producer.
3542      * @param     producer  the image producer
3543      * @return    the image produced
3544      * @since     JDK1.0
3545      */
3546     public Image createImage(ImageProducer producer) {
3547         ComponentPeer peer = this.peer;
3548         if ((peer != null) && ! (peer instanceof LightweightPeer)) {
3549             return peer.createImage(producer);
3550         }
3551         return getToolkit().createImage(producer);
3552     }
3553 
3554     /**
3555      * Creates an off-screen drawable image
3556      *     to be used for double buffering.
3557      * @param     width the specified width
3558      * @param     height the specified height
3559      * @return    an off-screen drawable image, which can be used for double
3560      *    buffering.  The return value may be <code>null</code> if the
3561      *    component is not displayable.  This will always happen if
3562      *    <code>GraphicsEnvironment.isHeadless()</code> returns
3563      *    <code>true</code>.
3564      * @see #isDisplayable
3565      * @see GraphicsEnvironment#isHeadless
3566      * @since     JDK1.0
3567      */
3568     public Image createImage(int width, int height) {
3569         ComponentPeer peer = this.peer;
3570         if (peer instanceof LightweightPeer) {
3571             if (parent != null) { return parent.createImage(width, height); }
3572             else { return null;}
3573         } else {
3574             return (peer != null) ? peer.createImage(width, height) : null;
3575         }
3576     }
3577 
3578     /**
3579      * Creates a volatile off-screen drawable image
3580      *     to be used for double buffering.
3581      * @param     width the specified width.
3582      * @param     height the specified height.
3583      * @return    an off-screen drawable image, which can be used for double
3584      *    buffering.  The return value may be <code>null</code> if the
3585      *    component is not displayable.  This will always happen if
3586      *    <code>GraphicsEnvironment.isHeadless()</code> returns
3587      *    <code>true</code>.
3588      * @see java.awt.image.VolatileImage
3589      * @see #isDisplayable
3590      * @see GraphicsEnvironment#isHeadless
3591      * @since     1.4
3592      */
3593     public VolatileImage createVolatileImage(int width, int height) {
3594         ComponentPeer peer = this.peer;
3595         if (peer instanceof LightweightPeer) {
3596             if (parent != null) {
3597                 return parent.createVolatileImage(width, height);
3598             }
3599             else { return null;}
3600         } else {
3601             return (peer != null) ?
3602                 peer.createVolatileImage(width, height) : null;
3603         }
3604     }
3605 
3606     /**
3607      * Creates a volatile off-screen drawable image, with the given capabilities.
3608      * The contents of this image may be lost at any time due
3609      * to operating system issues, so the image must be managed
3610      * via the <code>VolatileImage</code> interface.
3611      * @param width the specified width.
3612      * @param height the specified height.
3613      * @param caps the image capabilities
3614      * @exception AWTException if an image with the specified capabilities cannot
3615      * be created
3616      * @return a VolatileImage object, which can be used
3617      * to manage surface contents loss and capabilities.
3618      * @see java.awt.image.VolatileImage
3619      * @since 1.4
3620      */
3621     public VolatileImage createVolatileImage(int width, int height,
3622                                              ImageCapabilities caps) throws AWTException {
3623         // REMIND : check caps
3624         return createVolatileImage(width, height);
3625     }
3626 
3627     /**
3628      * Prepares an image for rendering on this component.  The image
3629      * data is downloaded asynchronously in another thread and the
3630      * appropriate screen representation of the image is generated.
3631      * @param     image   the <code>Image</code> for which to
3632      *                    prepare a screen representation
3633      * @param     observer   the <code>ImageObserver</code> object
3634      *                       to be notified as the image is being prepared
3635      * @return    <code>true</code> if the image has already been fully
3636      *           prepared; <code>false</code> otherwise
3637      * @since     JDK1.0
3638      */
3639     public boolean prepareImage(Image image, ImageObserver observer) {
3640         return prepareImage(image, -1, -1, observer);
3641     }
3642 
3643     /**
3644      * Prepares an image for rendering on this component at the
3645      * specified width and height.
3646      * <p>
3647      * The image data is downloaded asynchronously in another thread,
3648      * and an appropriately scaled screen representation of the image is
3649      * generated.
3650      * @param     image    the instance of <code>Image</code>
3651      *            for which to prepare a screen representation
3652      * @param     width    the width of the desired screen representation
3653      * @param     height   the height of the desired screen representation
3654      * @param     observer   the <code>ImageObserver</code> object
3655      *            to be notified as the image is being prepared
3656      * @return    <code>true</code> if the image has already been fully
3657      *          prepared; <code>false</code> otherwise
3658      * @see       java.awt.image.ImageObserver
3659      * @since     JDK1.0
3660      */
3661     public boolean prepareImage(Image image, int width, int height,
3662                                 ImageObserver observer) {
3663         ComponentPeer peer = this.peer;
3664         if (peer instanceof LightweightPeer) {
3665             return (parent != null)
3666                 ? parent.prepareImage(image, width, height, observer)
3667                 : getToolkit().prepareImage(image, width, height, observer);
3668         } else {
3669             return (peer != null)
3670                 ? peer.prepareImage(image, width, height, observer)
3671                 : getToolkit().prepareImage(image, width, height, observer);
3672         }
3673     }
3674 
3675     /**
3676      * Returns the status of the construction of a screen representation
3677      * of the specified image.
3678      * <p>
3679      * This method does not cause the image to begin loading. An
3680      * application must use the <code>prepareImage</code> method
3681      * to force the loading of an image.
3682      * <p>
3683      * Information on the flags returned by this method can be found
3684      * with the discussion of the <code>ImageObserver</code> interface.
3685      * @param     image   the <code>Image</code> object whose status
3686      *            is being checked
3687      * @param     observer   the <code>ImageObserver</code>
3688      *            object to be notified as the image is being prepared
3689      * @return  the bitwise inclusive <b>OR</b> of
3690      *            <code>ImageObserver</code> flags indicating what
3691      *            information about the image is currently available
3692      * @see      #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3693      * @see      Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3694      * @see      java.awt.image.ImageObserver
3695      * @since    JDK1.0
3696      */
3697     public int checkImage(Image image, ImageObserver observer) {
3698         return checkImage(image, -1, -1, observer);
3699     }
3700 
3701     /**
3702      * Returns the status of the construction of a screen representation
3703      * of the specified image.
3704      * <p>
3705      * This method does not cause the image to begin loading. An
3706      * application must use the <code>prepareImage</code> method
3707      * to force the loading of an image.
3708      * <p>
3709      * The <code>checkImage</code> method of <code>Component</code>
3710      * calls its peer's <code>checkImage</code> method to calculate
3711      * the flags. If this component does not yet have a peer, the
3712      * component's toolkit's <code>checkImage</code> method is called
3713      * instead.
3714      * <p>
3715      * Information on the flags returned by this method can be found
3716      * with the discussion of the <code>ImageObserver</code> interface.
3717      * @param     image   the <code>Image</code> object whose status
3718      *                    is being checked
3719      * @param     width   the width of the scaled version
3720      *                    whose status is to be checked
3721      * @param     height  the height of the scaled version
3722      *                    whose status is to be checked
3723      * @param     observer   the <code>ImageObserver</code> object
3724      *                    to be notified as the image is being prepared
3725      * @return    the bitwise inclusive <b>OR</b> of
3726      *            <code>ImageObserver</code> flags indicating what
3727      *            information about the image is currently available
3728      * @see      #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3729      * @see      Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3730      * @see      java.awt.image.ImageObserver
3731      * @since    JDK1.0
3732      */
3733     public int checkImage(Image image, int width, int height,
3734                           ImageObserver observer) {
3735         ComponentPeer peer = this.peer;
3736         if (peer instanceof LightweightPeer) {
3737             return (parent != null)
3738                 ? parent.checkImage(image, width, height, observer)
3739                 : getToolkit().checkImage(image, width, height, observer);
3740         } else {
3741             return (peer != null)
3742                 ? peer.checkImage(image, width, height, observer)
3743                 : getToolkit().checkImage(image, width, height, observer);
3744         }
3745     }
3746 
3747     /**
3748      * Creates a new strategy for multi-buffering on this component.
3749      * Multi-buffering is useful for rendering performance.  This method
3750      * attempts to create the best strategy available with the number of
3751      * buffers supplied.  It will always create a <code>BufferStrategy</code>
3752      * with that number of buffers.
3753      * A page-flipping strategy is attempted first, then a blitting strategy
3754      * using accelerated buffers.  Finally, an unaccelerated blitting
3755      * strategy is used.
3756      * <p>
3757      * Each time this method is called,
3758      * the existing buffer strategy for this component is discarded.
3759      * @param numBuffers number of buffers to create, including the front buffer
3760      * @exception IllegalArgumentException if numBuffers is less than 1.
3761      * @exception IllegalStateException if the component is not displayable
3762      * @see #isDisplayable
3763      * @see Window#getBufferStrategy()
3764      * @see Canvas#getBufferStrategy()
3765      * @since 1.4
3766      */
3767     void createBufferStrategy(int numBuffers) {
3768         BufferCapabilities bufferCaps;
3769         if (numBuffers > 1) {
3770             // Try to create a page-flipping strategy
3771             bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3772                                                 new ImageCapabilities(true),
3773                                                 BufferCapabilities.FlipContents.UNDEFINED);
3774             try {
3775                 createBufferStrategy(numBuffers, bufferCaps);
3776                 return; // Success
3777             } catch (AWTException e) {
3778                 // Failed
3779             }
3780         }
3781         // Try a blitting (but still accelerated) strategy
3782         bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3783                                             new ImageCapabilities(true),
3784                                             null);
3785         try {
3786             createBufferStrategy(numBuffers, bufferCaps);
3787             return; // Success
3788         } catch (AWTException e) {
3789             // Failed
3790         }
3791         // Try an unaccelerated blitting strategy
3792         bufferCaps = new BufferCapabilities(new ImageCapabilities(false),
3793                                             new ImageCapabilities(false),
3794                                             null);
3795         try {
3796             createBufferStrategy(numBuffers, bufferCaps);
3797             return; // Success
3798         } catch (AWTException e) {
3799             // Code should never reach here (an unaccelerated blitting
3800             // strategy should always work)
3801             throw new InternalError("Could not create a buffer strategy", e);
3802         }
3803     }
3804 
3805     /**
3806      * Creates a new strategy for multi-buffering on this component with the
3807      * required buffer capabilities.  This is useful, for example, if only
3808      * accelerated memory or page flipping is desired (as specified by the
3809      * buffer capabilities).
3810      * <p>
3811      * Each time this method
3812      * is called, <code>dispose</code> will be invoked on the existing
3813      * <code>BufferStrategy</code>.
3814      * @param numBuffers number of buffers to create
3815      * @param caps the required capabilities for creating the buffer strategy;
3816      * cannot be <code>null</code>
3817      * @exception AWTException if the capabilities supplied could not be
3818      * supported or met; this may happen, for example, if there is not enough
3819      * accelerated memory currently available, or if page flipping is specified
3820      * but not possible.
3821      * @exception IllegalArgumentException if numBuffers is less than 1, or if
3822      * caps is <code>null</code>
3823      * @see Window#getBufferStrategy()
3824      * @see Canvas#getBufferStrategy()
3825      * @since 1.4
3826      */
3827     void createBufferStrategy(int numBuffers,
3828                               BufferCapabilities caps) throws AWTException {
3829         // Check arguments
3830         if (numBuffers < 1) {
3831             throw new IllegalArgumentException(
3832                 "Number of buffers must be at least 1");
3833         }
3834         if (caps == null) {
3835             throw new IllegalArgumentException("No capabilities specified");
3836         }
3837         // Destroy old buffers
3838         if (bufferStrategy != null) {
3839             bufferStrategy.dispose();
3840         }
3841         if (numBuffers == 1) {
3842             bufferStrategy = new SingleBufferStrategy(caps);
3843         } else {
3844             SunGraphicsEnvironment sge = (SunGraphicsEnvironment)
3845                 GraphicsEnvironment.getLocalGraphicsEnvironment();
3846             if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) {
3847                 caps = new ProxyCapabilities(caps);
3848             }
3849             // assert numBuffers > 1;
3850             if (caps.isPageFlipping()) {
3851                 bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps);
3852             } else {
3853                 bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps);
3854             }
3855         }
3856     }
3857 
3858     /**
3859      * This is a proxy capabilities class used when a FlipBufferStrategy
3860      * is created instead of the requested Blit strategy.
3861      *
3862      * @see sun.java2d.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer)
3863      */
3864     private class ProxyCapabilities extends ExtendedBufferCapabilities {
3865         private BufferCapabilities orig;
3866         private ProxyCapabilities(BufferCapabilities orig) {
3867             super(orig.getFrontBufferCapabilities(),
3868                   orig.getBackBufferCapabilities(),
3869                   orig.getFlipContents() ==
3870                       BufferCapabilities.FlipContents.BACKGROUND ?
3871                       BufferCapabilities.FlipContents.BACKGROUND :
3872                       BufferCapabilities.FlipContents.COPIED);
3873             this.orig = orig;
3874         }
3875     }
3876 
3877     /**
3878      * @return the buffer strategy used by this component
3879      * @see Window#createBufferStrategy
3880      * @see Canvas#createBufferStrategy
3881      * @since 1.4
3882      */
3883     BufferStrategy getBufferStrategy() {
3884         return bufferStrategy;
3885     }
3886 
3887     /**
3888      * @return the back buffer currently used by this component's
3889      * BufferStrategy.  If there is no BufferStrategy or no
3890      * back buffer, this method returns null.
3891      */
3892     Image getBackBuffer() {
3893         if (bufferStrategy != null) {
3894             if (bufferStrategy instanceof BltBufferStrategy) {
3895                 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;
3896                 return bltBS.getBackBuffer();
3897             } else if (bufferStrategy instanceof FlipBufferStrategy) {
3898                 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;
3899                 return flipBS.getBackBuffer();
3900             }
3901         }
3902         return null;
3903     }
3904 
3905     /**
3906      * Inner class for flipping buffers on a component.  That component must
3907      * be a <code>Canvas</code> or <code>Window</code>.
3908      * @see Canvas
3909      * @see Window
3910      * @see java.awt.image.BufferStrategy
3911      * @author Michael Martak
3912      * @since 1.4
3913      */
3914     protected class FlipBufferStrategy extends BufferStrategy {
3915         /**
3916          * The number of buffers
3917          */
3918         protected int numBuffers; // = 0
3919         /**
3920          * The buffering capabilities
3921          */
3922         protected BufferCapabilities caps; // = null
3923         /**
3924          * The drawing buffer
3925          */
3926         protected Image drawBuffer; // = null
3927         /**
3928          * The drawing buffer as a volatile image
3929          */
3930         protected VolatileImage drawVBuffer; // = null
3931         /**
3932          * Whether or not the drawing buffer has been recently restored from
3933          * a lost state.
3934          */
3935         protected boolean validatedContents; // = false
3936         /**
3937          * Size of the back buffers.  (Note: these fields were added in 6.0
3938          * but kept package-private to avoid exposing them in the spec.
3939          * None of these fields/methods really should have been marked
3940          * protected when they were introduced in 1.4, but now we just have
3941          * to live with that decision.)
3942          */
3943         int width;
3944         int height;
3945 
3946         /**
3947          * Creates a new flipping buffer strategy for this component.
3948          * The component must be a <code>Canvas</code> or <code>Window</code>.
3949          * @see Canvas
3950          * @see Window
3951          * @param numBuffers the number of buffers
3952          * @param caps the capabilities of the buffers
3953          * @exception AWTException if the capabilities supplied could not be
3954          * supported or met
3955          * @exception ClassCastException if the component is not a canvas or
3956          * window.
3957          * @exception IllegalStateException if the component has no peer
3958          * @exception IllegalArgumentException if {@code numBuffers} is less than two,
3959          * or if {@code BufferCapabilities.isPageFlipping} is not
3960          * {@code true}.
3961          * @see #createBuffers(int, BufferCapabilities)
3962          */
3963         protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)
3964             throws AWTException
3965         {
3966             if (!(Component.this instanceof Window) &&
3967                 !(Component.this instanceof Canvas))
3968             {
3969                 throw new ClassCastException(
3970                     "Component must be a Canvas or Window");
3971             }
3972             this.numBuffers = numBuffers;
3973             this.caps = caps;
3974             createBuffers(numBuffers, caps);
3975         }
3976 
3977         /**
3978          * Creates one or more complex, flipping buffers with the given
3979          * capabilities.
3980          * @param numBuffers number of buffers to create; must be greater than
3981          * one
3982          * @param caps the capabilities of the buffers.
3983          * <code>BufferCapabilities.isPageFlipping</code> must be
3984          * <code>true</code>.
3985          * @exception AWTException if the capabilities supplied could not be
3986          * supported or met
3987          * @exception IllegalStateException if the component has no peer
3988          * @exception IllegalArgumentException if numBuffers is less than two,
3989          * or if <code>BufferCapabilities.isPageFlipping</code> is not
3990          * <code>true</code>.
3991          * @see java.awt.BufferCapabilities#isPageFlipping()
3992          */
3993         protected void createBuffers(int numBuffers, BufferCapabilities caps)
3994             throws AWTException
3995         {
3996             if (numBuffers < 2) {
3997                 throw new IllegalArgumentException(
3998                     "Number of buffers cannot be less than two");
3999             } else if (peer == null) {
4000                 throw new IllegalStateException(
4001                     "Component must have a valid peer");
4002             } else if (caps == null || !caps.isPageFlipping()) {
4003                 throw new IllegalArgumentException(
4004                     "Page flipping capabilities must be specified");
4005             }
4006 
4007             // save the current bounds
4008             width = getWidth();
4009             height = getHeight();
4010 
4011             if (drawBuffer != null) {
4012                 // dispose the existing backbuffers
4013                 drawBuffer = null;
4014                 drawVBuffer = null;
4015                 destroyBuffers();
4016                 // ... then recreate the backbuffers
4017             }
4018 
4019             if (caps instanceof ExtendedBufferCapabilities) {
4020                 ExtendedBufferCapabilities ebc =
4021                     (ExtendedBufferCapabilities)caps;
4022                 if (ebc.getVSync() == VSYNC_ON) {
4023                     // if this buffer strategy is not allowed to be v-synced,
4024                     // change the caps that we pass to the peer but keep on
4025                     // trying to create v-synced buffers;
4026                     // do not throw IAE here in case it is disallowed, see
4027                     // ExtendedBufferCapabilities for more info
4028                     if (!VSyncedBSManager.vsyncAllowed(this)) {
4029                         caps = ebc.derive(VSYNC_DEFAULT);
4030                     }
4031                 }
4032             }
4033 
4034             peer.createBuffers(numBuffers, caps);
4035             updateInternalBuffers();
4036         }
4037 
4038         /**
4039          * Updates internal buffers (both volatile and non-volatile)
4040          * by requesting the back-buffer from the peer.
4041          */
4042         private void updateInternalBuffers() {
4043             // get the images associated with the draw buffer
4044             drawBuffer = getBackBuffer();
4045             if (drawBuffer instanceof VolatileImage) {
4046                 drawVBuffer = (VolatileImage)drawBuffer;
4047             } else {
4048                 drawVBuffer = null;
4049             }
4050         }
4051 
4052         /**
4053          * @return direct access to the back buffer, as an image.
4054          * @exception IllegalStateException if the buffers have not yet
4055          * been created
4056          */
4057         protected Image getBackBuffer() {
4058             if (peer != null) {
4059                 return peer.getBackBuffer();
4060             } else {
4061                 throw new IllegalStateException(
4062                     "Component must have a valid peer");
4063             }
4064         }
4065 
4066         /**
4067          * Flipping moves the contents of the back buffer to the front buffer,
4068          * either by copying or by moving the video pointer.
4069          * @param flipAction an integer value describing the flipping action
4070          * for the contents of the back buffer.  This should be one of the
4071          * values of the <code>BufferCapabilities.FlipContents</code>
4072          * property.
4073          * @exception IllegalStateException if the buffers have not yet
4074          * been created
4075          * @see java.awt.BufferCapabilities#getFlipContents()
4076          */
4077         protected void flip(BufferCapabilities.FlipContents flipAction) {
4078             if (peer != null) {
4079                 Image backBuffer = getBackBuffer();
4080                 if (backBuffer != null) {
4081                     peer.flip(0, 0,
4082                               backBuffer.getWidth(null),
4083                               backBuffer.getHeight(null), flipAction);
4084                 }
4085             } else {
4086                 throw new IllegalStateException(
4087                     "Component must have a valid peer");
4088             }
4089         }
4090 
4091         void flipSubRegion(int x1, int y1, int x2, int y2,
4092                       BufferCapabilities.FlipContents flipAction)
4093         {
4094             if (peer != null) {
4095                 peer.flip(x1, y1, x2, y2, flipAction);
4096             } else {
4097                 throw new IllegalStateException(
4098                     "Component must have a valid peer");
4099             }
4100         }
4101 
4102         /**
4103          * Destroys the buffers created through this object
4104          */
4105         protected void destroyBuffers() {
4106             VSyncedBSManager.releaseVsync(this);
4107             if (peer != null) {
4108                 peer.destroyBuffers();
4109             } else {
4110                 throw new IllegalStateException(
4111                     "Component must have a valid peer");
4112             }
4113         }
4114 
4115         /**
4116          * @return the buffering capabilities of this strategy
4117          */
4118         public BufferCapabilities getCapabilities() {
4119             if (caps instanceof ProxyCapabilities) {
4120                 return ((ProxyCapabilities)caps).orig;
4121             } else {
4122                 return caps;
4123             }
4124         }
4125 
4126         /**
4127          * @return the graphics on the drawing buffer.  This method may not
4128          * be synchronized for performance reasons; use of this method by multiple
4129          * threads should be handled at the application level.  Disposal of the
4130          * graphics object must be handled by the application.
4131          */
4132         public Graphics getDrawGraphics() {
4133             revalidate();
4134             return drawBuffer.getGraphics();
4135         }
4136 
4137         /**
4138          * Restore the drawing buffer if it has been lost
4139          */
4140         protected void revalidate() {
4141             revalidate(true);
4142         }
4143 
4144         void revalidate(boolean checkSize) {
4145             validatedContents = false;
4146 
4147             if (checkSize && (getWidth() != width || getHeight() != height)) {
4148                 // component has been resized; recreate the backbuffers
4149                 try {
4150                     createBuffers(numBuffers, caps);
4151                 } catch (AWTException e) {
4152                     // shouldn't be possible
4153                 }
4154                 validatedContents = true;
4155             }
4156 
4157             // get the buffers from the peer every time since they
4158             // might have been replaced in response to a display change event
4159             updateInternalBuffers();
4160 
4161             // now validate the backbuffer
4162             if (drawVBuffer != null) {
4163                 GraphicsConfiguration gc =
4164                         getGraphicsConfiguration_NoClientCode();
4165                 int returnCode = drawVBuffer.validate(gc);
4166                 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4167                     try {
4168                         createBuffers(numBuffers, caps);
4169                     } catch (AWTException e) {
4170                         // shouldn't be possible
4171                     }
4172                     if (drawVBuffer != null) {
4173                         // backbuffers were recreated, so validate again
4174                         drawVBuffer.validate(gc);
4175                     }
4176                     validatedContents = true;
4177                 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4178                     validatedContents = true;
4179                 }
4180             }
4181         }
4182 
4183         /**
4184          * @return whether the drawing buffer was lost since the last call to
4185          * <code>getDrawGraphics</code>
4186          */
4187         public boolean contentsLost() {
4188             if (drawVBuffer == null) {
4189                 return false;
4190             }
4191             return drawVBuffer.contentsLost();
4192         }
4193 
4194         /**
4195          * @return whether the drawing buffer was recently restored from a lost
4196          * state and reinitialized to the default background color (white)
4197          */
4198         public boolean contentsRestored() {
4199             return validatedContents;
4200         }
4201 
4202         /**
4203          * Makes the next available buffer visible by either blitting or
4204          * flipping.
4205          */
4206         public void show() {
4207             flip(caps.getFlipContents());
4208         }
4209 
4210         /**
4211          * Makes specified region of the the next available buffer visible
4212          * by either blitting or flipping.
4213          */
4214         void showSubRegion(int x1, int y1, int x2, int y2) {
4215             flipSubRegion(x1, y1, x2, y2, caps.getFlipContents());
4216         }
4217 
4218         /**
4219          * {@inheritDoc}
4220          * @since 1.6
4221          */
4222         public void dispose() {
4223             if (Component.this.bufferStrategy == this) {
4224                 Component.this.bufferStrategy = null;
4225                 if (peer != null) {
4226                     destroyBuffers();
4227                 }
4228             }
4229         }
4230 
4231     } // Inner class FlipBufferStrategy
4232 
4233     /**
4234      * Inner class for blitting offscreen surfaces to a component.
4235      *
4236      * @author Michael Martak
4237      * @since 1.4
4238      */
4239     protected class BltBufferStrategy extends BufferStrategy {
4240 
4241         /**
4242          * The buffering capabilities
4243          */
4244         protected BufferCapabilities caps; // = null
4245         /**
4246          * The back buffers
4247          */
4248         protected VolatileImage[] backBuffers; // = null
4249         /**
4250          * Whether or not the drawing buffer has been recently restored from
4251          * a lost state.
4252          */
4253         protected boolean validatedContents; // = false
4254         /**
4255          * Size of the back buffers
4256          */
4257         protected int width;
4258         protected int height;
4259 
4260         /**
4261          * Insets for the hosting Component.  The size of the back buffer
4262          * is constrained by these.
4263          */
4264         private Insets insets;
4265 
4266         /**
4267          * Creates a new blt buffer strategy around a component
4268          * @param numBuffers number of buffers to create, including the
4269          * front buffer
4270          * @param caps the capabilities of the buffers
4271          */
4272         protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) {
4273             this.caps = caps;
4274             createBackBuffers(numBuffers - 1);
4275         }
4276 
4277         /**
4278          * {@inheritDoc}
4279          * @since 1.6
4280          */
4281         public void dispose() {
4282             if (backBuffers != null) {
4283                 for (int counter = backBuffers.length - 1; counter >= 0;
4284                      counter--) {
4285                     if (backBuffers[counter] != null) {
4286                         backBuffers[counter].flush();
4287                         backBuffers[counter] = null;
4288                     }
4289                 }
4290             }
4291             if (Component.this.bufferStrategy == this) {
4292                 Component.this.bufferStrategy = null;
4293             }
4294         }
4295 
4296         /**
4297          * Creates the back buffers
4298          */
4299         protected void createBackBuffers(int numBuffers) {
4300             if (numBuffers == 0) {
4301                 backBuffers = null;
4302             } else {
4303                 // save the current bounds
4304                 width = getWidth();
4305                 height = getHeight();
4306                 insets = getInsets_NoClientCode();
4307                 int iWidth = width - insets.left - insets.right;
4308                 int iHeight = height - insets.top - insets.bottom;
4309 
4310                 // It is possible for the component's width and/or height
4311                 // to be 0 here.  Force the size of the backbuffers to
4312                 // be > 0 so that creating the image won't fail.
4313                 iWidth = Math.max(1, iWidth);
4314                 iHeight = Math.max(1, iHeight);
4315                 if (backBuffers == null) {
4316                     backBuffers = new VolatileImage[numBuffers];
4317                 } else {
4318                     // flush any existing backbuffers
4319                     for (int i = 0; i < numBuffers; i++) {
4320                         if (backBuffers[i] != null) {
4321                             backBuffers[i].flush();
4322                             backBuffers[i] = null;
4323                         }
4324                     }
4325                 }
4326 
4327                 // create the backbuffers
4328                 for (int i = 0; i < numBuffers; i++) {
4329                     backBuffers[i] = createVolatileImage(iWidth, iHeight);
4330                 }
4331             }
4332         }
4333 
4334         /**
4335          * @return the buffering capabilities of this strategy
4336          */
4337         public BufferCapabilities getCapabilities() {
4338             return caps;
4339         }
4340 
4341         /**
4342          * @return the draw graphics
4343          */
4344         public Graphics getDrawGraphics() {
4345             revalidate();
4346             Image backBuffer = getBackBuffer();
4347             if (backBuffer == null) {
4348                 return getGraphics();
4349             }
4350             SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();
4351             g.constrain(-insets.left, -insets.top,
4352                         backBuffer.getWidth(null) + insets.left,
4353                         backBuffer.getHeight(null) + insets.top);
4354             return g;
4355         }
4356 
4357         /**
4358          * @return direct access to the back buffer, as an image.
4359          * If there is no back buffer, returns null.
4360          */
4361         Image getBackBuffer() {
4362             if (backBuffers != null) {
4363                 return backBuffers[backBuffers.length - 1];
4364             } else {
4365                 return null;
4366             }
4367         }
4368 
4369         /**
4370          * Makes the next available buffer visible.
4371          */
4372         public void show() {
4373             showSubRegion(insets.left, insets.top,
4374                           width - insets.right,
4375                           height - insets.bottom);
4376         }
4377 
4378         /**
4379          * Package-private method to present a specific rectangular area
4380          * of this buffer.  This class currently shows only the entire
4381          * buffer, by calling showSubRegion() with the full dimensions of
4382          * the buffer.  Subclasses (e.g., BltSubRegionBufferStrategy
4383          * and FlipSubRegionBufferStrategy) may have region-specific show
4384          * methods that call this method with actual sub regions of the
4385          * buffer.
4386          */
4387         void showSubRegion(int x1, int y1, int x2, int y2) {
4388             if (backBuffers == null) {
4389                 return;
4390             }
4391             // Adjust location to be relative to client area.
4392             x1 -= insets.left;
4393             x2 -= insets.left;
4394             y1 -= insets.top;
4395             y2 -= insets.top;
4396             Graphics g = getGraphics_NoClientCode();
4397             if (g == null) {
4398                 // Not showing, bail
4399                 return;
4400             }
4401             try {
4402                 // First image copy is in terms of Frame's coordinates, need
4403                 // to translate to client area.
4404                 g.translate(insets.left, insets.top);
4405                 for (int i = 0; i < backBuffers.length; i++) {
4406                     g.drawImage(backBuffers[i],
4407                                 x1, y1, x2, y2,
4408                                 x1, y1, x2, y2,
4409                                 null);
4410                     g.dispose();
4411                     g = null;
4412                     g = backBuffers[i].getGraphics();
4413                 }
4414             } finally {
4415                 if (g != null) {
4416                     g.dispose();
4417                 }
4418             }
4419         }
4420 
4421         /**
4422          * Restore the drawing buffer if it has been lost
4423          */
4424         protected void revalidate() {
4425             revalidate(true);
4426         }
4427 
4428         void revalidate(boolean checkSize) {
4429             validatedContents = false;
4430 
4431             if (backBuffers == null) {
4432                 return;
4433             }
4434 
4435             if (checkSize) {
4436                 Insets insets = getInsets_NoClientCode();
4437                 if (getWidth() != width || getHeight() != height ||
4438                     !insets.equals(this.insets)) {
4439                     // component has been resized; recreate the backbuffers
4440                     createBackBuffers(backBuffers.length);
4441                     validatedContents = true;
4442                 }
4443             }
4444 
4445             // now validate the backbuffer
4446             GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
4447             int returnCode =
4448                 backBuffers[backBuffers.length - 1].validate(gc);
4449             if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4450                 if (checkSize) {
4451                     createBackBuffers(backBuffers.length);
4452                     // backbuffers were recreated, so validate again
4453                     backBuffers[backBuffers.length - 1].validate(gc);
4454                 }
4455                 // else case means we're called from Swing on the toolkit
4456                 // thread, don't recreate buffers as that'll deadlock
4457                 // (creating VolatileImages invokes getting GraphicsConfig
4458                 // which grabs treelock).
4459                 validatedContents = true;
4460             } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4461                 validatedContents = true;
4462             }
4463         }
4464 
4465         /**
4466          * @return whether the drawing buffer was lost since the last call to
4467          * <code>getDrawGraphics</code>
4468          */
4469         public boolean contentsLost() {
4470             if (backBuffers == null) {
4471                 return false;
4472             } else {
4473                 return backBuffers[backBuffers.length - 1].contentsLost();
4474             }
4475         }
4476 
4477         /**
4478          * @return whether the drawing buffer was recently restored from a lost
4479          * state and reinitialized to the default background color (white)
4480          */
4481         public boolean contentsRestored() {
4482             return validatedContents;
4483         }
4484     } // Inner class BltBufferStrategy
4485 
4486     /**
4487      * Private class to perform sub-region flipping.
4488      */
4489     private class FlipSubRegionBufferStrategy extends FlipBufferStrategy
4490         implements SubRegionShowable
4491     {
4492 
4493         protected FlipSubRegionBufferStrategy(int numBuffers,
4494                                               BufferCapabilities caps)
4495             throws AWTException
4496         {
4497             super(numBuffers, caps);
4498         }
4499 
4500         public void show(int x1, int y1, int x2, int y2) {
4501             showSubRegion(x1, y1, x2, y2);
4502         }
4503 
4504         // This is invoked by Swing on the toolkit thread.
4505         public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4506             if (!contentsLost()) {
4507                 showSubRegion(x1, y1, x2, y2);
4508                 return !contentsLost();
4509             }
4510             return false;
4511         }
4512     }
4513 
4514     /**
4515      * Private class to perform sub-region blitting.  Swing will use
4516      * this subclass via the SubRegionShowable interface in order to
4517      * copy only the area changed during a repaint.
4518      * See javax.swing.BufferStrategyPaintManager.
4519      */
4520     private class BltSubRegionBufferStrategy extends BltBufferStrategy
4521         implements SubRegionShowable
4522     {
4523 
4524         protected BltSubRegionBufferStrategy(int numBuffers,
4525                                              BufferCapabilities caps)
4526         {
4527             super(numBuffers, caps);
4528         }
4529 
4530         public void show(int x1, int y1, int x2, int y2) {
4531             showSubRegion(x1, y1, x2, y2);
4532         }
4533 
4534         // This method is called by Swing on the toolkit thread.
4535         public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4536             if (!contentsLost()) {
4537                 showSubRegion(x1, y1, x2, y2);
4538                 return !contentsLost();
4539             }
4540             return false;
4541         }
4542     }
4543 
4544     /**
4545      * Inner class for flipping buffers on a component.  That component must
4546      * be a <code>Canvas</code> or <code>Window</code>.
4547      * @see Canvas
4548      * @see Window
4549      * @see java.awt.image.BufferStrategy
4550      * @author Michael Martak
4551      * @since 1.4
4552      */
4553     private class SingleBufferStrategy extends BufferStrategy {
4554 
4555         private BufferCapabilities caps;
4556 
4557         public SingleBufferStrategy(BufferCapabilities caps) {
4558             this.caps = caps;
4559         }
4560         public BufferCapabilities getCapabilities() {
4561             return caps;
4562         }
4563         public Graphics getDrawGraphics() {
4564             return getGraphics();
4565         }
4566         public boolean contentsLost() {
4567             return false;
4568         }
4569         public boolean contentsRestored() {
4570             return false;
4571         }
4572         public void show() {
4573             // Do nothing
4574         }
4575     } // Inner class SingleBufferStrategy
4576 
4577     /**
4578      * Sets whether or not paint messages received from the operating system
4579      * should be ignored.  This does not affect paint events generated in
4580      * software by the AWT, unless they are an immediate response to an
4581      * OS-level paint message.
4582      * <p>
4583      * This is useful, for example, if running under full-screen mode and
4584      * better performance is desired, or if page-flipping is used as the
4585      * buffer strategy.
4586      *
4587      * @since 1.4
4588      * @see #getIgnoreRepaint
4589      * @see Canvas#createBufferStrategy
4590      * @see Window#createBufferStrategy
4591      * @see java.awt.image.BufferStrategy
4592      * @see GraphicsDevice#setFullScreenWindow
4593      */
4594     public void setIgnoreRepaint(boolean ignoreRepaint) {
4595         this.ignoreRepaint = ignoreRepaint;
4596     }
4597 
4598     /**
4599      * @return whether or not paint messages received from the operating system
4600      * should be ignored.
4601      *
4602      * @since 1.4
4603      * @see #setIgnoreRepaint
4604      */
4605     public boolean getIgnoreRepaint() {
4606         return ignoreRepaint;
4607     }
4608 
4609     /**
4610      * Checks whether this component "contains" the specified point,
4611      * where <code>x</code> and <code>y</code> are defined to be
4612      * relative to the coordinate system of this component.
4613      * @param     x   the <i>x</i> coordinate of the point
4614      * @param     y   the <i>y</i> coordinate of the point
4615      * @see       #getComponentAt(int, int)
4616      * @since     JDK1.1
4617      */
4618     public boolean contains(int x, int y) {
4619         return inside(x, y);
4620     }
4621 
4622     /**
4623      * @deprecated As of JDK version 1.1,
4624      * replaced by contains(int, int).
4625      */
4626     @Deprecated
4627     public boolean inside(int x, int y) {
4628         return (x >= 0) && (x < width) && (y >= 0) && (y < height);
4629     }
4630 
4631     /**
4632      * Checks whether this component "contains" the specified point,
4633      * where the point's <i>x</i> and <i>y</i> coordinates are defined
4634      * to be relative to the coordinate system of this component.
4635      * @param     p     the point
4636      * @throws    NullPointerException if {@code p} is {@code null}
4637      * @see       #getComponentAt(Point)
4638      * @since     JDK1.1
4639      */
4640     public boolean contains(Point p) {
4641         return contains(p.x, p.y);
4642     }
4643 
4644     /**
4645      * Determines if this component or one of its immediate
4646      * subcomponents contains the (<i>x</i>,&nbsp;<i>y</i>) location,
4647      * and if so, returns the containing component. This method only
4648      * looks one level deep. If the point (<i>x</i>,&nbsp;<i>y</i>) is
4649      * inside a subcomponent that itself has subcomponents, it does not
4650      * go looking down the subcomponent tree.
4651      * <p>
4652      * The <code>locate</code> method of <code>Component</code> simply
4653      * returns the component itself if the (<i>x</i>,&nbsp;<i>y</i>)
4654      * coordinate location is inside its bounding box, and <code>null</code>
4655      * otherwise.
4656      * @param     x   the <i>x</i> coordinate
4657      * @param     y   the <i>y</i> coordinate
4658      * @return    the component or subcomponent that contains the
4659      *                (<i>x</i>,&nbsp;<i>y</i>) location;
4660      *                <code>null</code> if the location
4661      *                is outside this component
4662      * @see       #contains(int, int)
4663      * @since     JDK1.0
4664      */
4665     public Component getComponentAt(int x, int y) {
4666         return locate(x, y);
4667     }
4668 
4669     /**
4670      * @deprecated As of JDK version 1.1,
4671      * replaced by getComponentAt(int, int).
4672      */
4673     @Deprecated
4674     public Component locate(int x, int y) {
4675         return contains(x, y) ? this : null;
4676     }
4677 
4678     /**
4679      * Returns the component or subcomponent that contains the
4680      * specified point.
4681      * @param     p   the point
4682      * @see       java.awt.Component#contains
4683      * @since     JDK1.1
4684      */
4685     public Component getComponentAt(Point p) {
4686         return getComponentAt(p.x, p.y);
4687     }
4688 
4689     /**
4690      * @deprecated As of JDK version 1.1,
4691      * replaced by <code>dispatchEvent(AWTEvent e)</code>.
4692      */
4693     @Deprecated
4694     public void deliverEvent(Event e) {
4695         postEvent(e);
4696     }
4697 
4698     /**
4699      * Dispatches an event to this component or one of its sub components.
4700      * Calls <code>processEvent</code> before returning for 1.1-style
4701      * events which have been enabled for the <code>Component</code>.
4702      * @param e the event
4703      */
4704     public final void dispatchEvent(AWTEvent e) {
4705         dispatchEventImpl(e);
4706     }
4707 
4708     @SuppressWarnings("deprecation")
4709     void dispatchEventImpl(AWTEvent e) {
4710         int id = e.getID();
4711 
4712         // Check that this component belongs to this app-context
4713         AppContext compContext = appContext;
4714         if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
4715             if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
4716                 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");
4717             }
4718         }
4719 
4720         if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4721             eventLog.finest("{0}", e);
4722         }
4723 
4724         /*
4725          * 0. Set timestamp and modifiers of current event.
4726          */
4727         if (!(e instanceof KeyEvent)) {
4728             // Timestamp of a key event is set later in DKFM.preDispatchKeyEvent(KeyEvent).
4729             EventQueue.setCurrentEventAndMostRecentTime(e);
4730         }
4731 
4732         /*
4733          * 1. Pre-dispatchers. Do any necessary retargeting/reordering here
4734          *    before we notify AWTEventListeners.
4735          */
4736 
4737         if (e instanceof SunDropTargetEvent) {
4738             ((SunDropTargetEvent)e).dispatch();
4739             return;
4740         }
4741 
4742         if (!e.focusManagerIsDispatching) {
4743             // Invoke the private focus retargeting method which provides
4744             // lightweight Component support
4745             if (e.isPosted) {
4746                 e = KeyboardFocusManager.retargetFocusEvent(e);
4747                 e.isPosted = true;
4748             }
4749 
4750             // Now, with the event properly targeted to a lightweight
4751             // descendant if necessary, invoke the public focus retargeting
4752             // and dispatching function
4753             if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
4754                 dispatchEvent(e))
4755             {
4756                 return;
4757             }
4758         }
4759         if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
4760             focusLog.finest("" + e);
4761         }
4762         // MouseWheel may need to be retargeted here so that
4763         // AWTEventListener sees the event go to the correct
4764         // Component.  If the MouseWheelEvent needs to go to an ancestor,
4765         // the event is dispatched to the ancestor, and dispatching here
4766         // stops.
4767         if (id == MouseEvent.MOUSE_WHEEL &&
4768             (!eventTypeEnabled(id)) &&
4769             (peer != null && !peer.handlesWheelScrolling()) &&
4770             (dispatchMouseWheelToAncestor((MouseWheelEvent)e)))
4771         {
4772             return;
4773         }
4774 
4775         /*
4776          * 2. Allow the Toolkit to pass this to AWTEventListeners.
4777          */
4778         Toolkit toolkit = Toolkit.getDefaultToolkit();
4779         toolkit.notifyAWTEventListeners(e);
4780 
4781 
4782         /*
4783          * 3. If no one has consumed a key event, allow the
4784          *    KeyboardFocusManager to process it.
4785          */
4786         if (!e.isConsumed()) {
4787             if (e instanceof java.awt.event.KeyEvent) {
4788                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
4789                     processKeyEvent(this, (KeyEvent)e);
4790                 if (e.isConsumed()) {
4791                     return;
4792                 }
4793             }
4794         }
4795 
4796         /*
4797          * 4. Allow input methods to process the event
4798          */
4799         if (areInputMethodsEnabled()) {
4800             // We need to pass on InputMethodEvents since some host
4801             // input method adapters send them through the Java
4802             // event queue instead of directly to the component,
4803             // and the input context also handles the Java composition window
4804             if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea))
4805                ||
4806                // Otherwise, we only pass on input and focus events, because
4807                // a) input methods shouldn't know about semantic or component-level events
4808                // b) passing on the events takes time
4809                // c) isConsumed() is always true for semantic events.
4810                (e instanceof InputEvent) || (e instanceof FocusEvent)) {
4811                 InputContext inputContext = getInputContext();
4812 
4813 
4814                 if (inputContext != null) {
4815                     inputContext.dispatchEvent(e);
4816                     if (e.isConsumed()) {
4817                         if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
4818                             focusLog.finest("3579: Skipping " + e);
4819                         }
4820                         return;
4821                     }
4822                 }
4823             }
4824         } else {
4825             // When non-clients get focus, we need to explicitly disable the native
4826             // input method. The native input method is actually not disabled when
4827             // the active/passive/peered clients loose focus.
4828             if (id == FocusEvent.FOCUS_GAINED) {
4829                 InputContext inputContext = getInputContext();
4830                 if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) {
4831                     ((sun.awt.im.InputContext)inputContext).disableNativeIM();
4832                 }
4833             }
4834         }
4835 
4836 
4837         /*
4838          * 5. Pre-process any special events before delivery
4839          */
4840         switch(id) {
4841             // Handling of the PAINT and UPDATE events is now done in the
4842             // peer's handleEvent() method so the background can be cleared
4843             // selectively for non-native components on Windows only.
4844             // - Fred.Ecks@Eng.sun.com, 5-8-98
4845 
4846           case KeyEvent.KEY_PRESSED:
4847           case KeyEvent.KEY_RELEASED:
4848               Container p = (Container)((this instanceof Container) ? this : parent);
4849               if (p != null) {
4850                   p.preProcessKeyEvent((KeyEvent)e);
4851                   if (e.isConsumed()) {
4852                         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
4853                             focusLog.finest("Pre-process consumed event");
4854                         }
4855                       return;
4856                   }
4857               }
4858               break;
4859 
4860           case WindowEvent.WINDOW_CLOSING:
4861               if (toolkit instanceof WindowClosingListener) {
4862                   windowClosingException = ((WindowClosingListener)
4863                                             toolkit).windowClosingNotify((WindowEvent)e);
4864                   if (checkWindowClosingException()) {
4865                       return;
4866                   }
4867               }
4868               break;
4869 
4870           default:
4871               break;
4872         }
4873 
4874         /*
4875          * 6. Deliver event for normal processing
4876          */
4877         if (newEventsOnly) {
4878             // Filtering needs to really be moved to happen at a lower
4879             // level in order to get maximum performance gain;  it is
4880             // here temporarily to ensure the API spec is honored.
4881             //
4882             if (eventEnabled(e)) {
4883                 processEvent(e);
4884             }
4885         } else if (id == MouseEvent.MOUSE_WHEEL) {
4886             // newEventsOnly will be false for a listenerless ScrollPane, but
4887             // MouseWheelEvents still need to be dispatched to it so scrolling
4888             // can be done.
4889             autoProcessMouseWheel((MouseWheelEvent)e);
4890         } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) {
4891             //
4892             // backward compatibility
4893             //
4894             Event olde = e.convertToOld();
4895             if (olde != null) {
4896                 int key = olde.key;
4897                 int modifiers = olde.modifiers;
4898 
4899                 postEvent(olde);
4900                 if (olde.isConsumed()) {
4901                     e.consume();
4902                 }
4903                 // if target changed key or modifier values, copy them
4904                 // back to original event
4905                 //
4906                 switch(olde.id) {
4907                   case Event.KEY_PRESS:
4908                   case Event.KEY_RELEASE:
4909                   case Event.KEY_ACTION:
4910                   case Event.KEY_ACTION_RELEASE:
4911                       if (olde.key != key) {
4912                           ((KeyEvent)e).setKeyChar(olde.getKeyEventChar());
4913                       }
4914                       if (olde.modifiers != modifiers) {
4915                           ((KeyEvent)e).setModifiers(olde.modifiers);
4916                       }
4917                       break;
4918                   default:
4919                       break;
4920                 }
4921             }
4922         }
4923 
4924         /*
4925          * 8. Special handling for 4061116 : Hook for browser to close modal
4926          *    dialogs.
4927          */
4928         if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) {
4929             if (toolkit instanceof WindowClosingListener) {
4930                 windowClosingException =
4931                     ((WindowClosingListener)toolkit).
4932                     windowClosingDelivered((WindowEvent)e);
4933                 if (checkWindowClosingException()) {
4934                     return;
4935                 }
4936             }
4937         }
4938 
4939         /*
4940          * 9. Allow the peer to process the event.
4941          * Except KeyEvents, they will be processed by peer after
4942          * all KeyEventPostProcessors
4943          * (see DefaultKeyboardFocusManager.dispatchKeyEvent())
4944          */
4945         if (!(e instanceof KeyEvent)) {
4946             ComponentPeer tpeer = peer;
4947             if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) {
4948                 // if focus owner is lightweight then its native container
4949                 // processes event
4950                 Component source = (Component)e.getSource();
4951                 if (source != null) {
4952                     Container target = source.getNativeContainer();
4953                     if (target != null) {
4954                         tpeer = target.getPeer();
4955                     }
4956                 }
4957             }
4958             if (tpeer != null) {
4959                 tpeer.handleEvent(e);
4960             }
4961         }
4962     } // dispatchEventImpl()
4963 
4964     /*
4965      * If newEventsOnly is false, method is called so that ScrollPane can
4966      * override it and handle common-case mouse wheel scrolling.  NOP
4967      * for Component.
4968      */
4969     void autoProcessMouseWheel(MouseWheelEvent e) {}
4970 
4971     /*
4972      * Dispatch given MouseWheelEvent to the first ancestor for which
4973      * MouseWheelEvents are enabled.
4974      *
4975      * Returns whether or not event was dispatched to an ancestor
4976      */
4977     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
4978         int newX, newY;
4979         newX = e.getX() + getX(); // Coordinates take into account at least
4980         newY = e.getY() + getY(); // the cursor's position relative to this
4981                                   // Component (e.getX()), and this Component's
4982                                   // position relative to its parent.
4983         MouseWheelEvent newMWE;
4984 
4985         if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4986             eventLog.finest("dispatchMouseWheelToAncestor");
4987             eventLog.finest("orig event src is of " + e.getSource().getClass());
4988         }
4989 
4990         /* parent field for Window refers to the owning Window.
4991          * MouseWheelEvents should NOT be propagated into owning Windows
4992          */
4993         synchronized (getTreeLock()) {
4994             Container anc = getParent();
4995             while (anc != null && !anc.eventEnabled(e)) {
4996                 // fix coordinates to be relative to new event source
4997                 newX += anc.getX();
4998                 newY += anc.getY();
4999 
5000                 if (!(anc instanceof Window)) {
5001                     anc = anc.getParent();
5002                 }
5003                 else {
5004                     break;
5005                 }
5006             }
5007 
5008             if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
5009                 eventLog.finest("new event src is " + anc.getClass());
5010             }
5011 
5012             if (anc != null && anc.eventEnabled(e)) {
5013                 // Change event to be from new source, with new x,y
5014                 // For now, just create a new event - yucky
5015 
5016                 newMWE = new MouseWheelEvent(anc, // new source
5017                                              e.getID(),
5018                                              e.getWhen(),
5019                                              e.getModifiers(),
5020                                              newX, // x relative to new source
5021                                              newY, // y relative to new source
5022                                              e.getXOnScreen(),
5023                                              e.getYOnScreen(),
5024                                              e.getClickCount(),
5025                                              e.isPopupTrigger(),
5026                                              e.getScrollType(),
5027                                              e.getScrollAmount(),
5028                                              e.getWheelRotation(),
5029                                              e.getPreciseWheelRotation());
5030                 ((AWTEvent)e).copyPrivateDataInto(newMWE);
5031                 // When dispatching a wheel event to
5032                 // ancestor, there is no need trying to find descendant
5033                 // lightweights to dispatch event to.
5034                 // If we dispatch the event to toplevel ancestor,
5035                 // this could encolse the loop: 6480024.
5036                 anc.dispatchEventToSelf(newMWE);
5037                 if (newMWE.isConsumed()) {
5038                     e.consume();
5039                 }
5040                 return true;
5041             }
5042         }
5043         return false;
5044     }
5045 
5046     boolean checkWindowClosingException() {
5047         if (windowClosingException != null) {
5048             if (this instanceof Dialog) {
5049                 ((Dialog)this).interruptBlocking();
5050             } else {
5051                 windowClosingException.fillInStackTrace();
5052                 windowClosingException.printStackTrace();
5053                 windowClosingException = null;
5054             }
5055             return true;
5056         }
5057         return false;
5058     }
5059 
5060     boolean areInputMethodsEnabled() {
5061         // in 1.2, we assume input method support is required for all
5062         // components that handle key events, but components can turn off
5063         // input methods by calling enableInputMethods(false).
5064         return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) &&
5065             ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null);
5066     }
5067 
5068     // REMIND: remove when filtering is handled at lower level
5069     boolean eventEnabled(AWTEvent e) {
5070         return eventTypeEnabled(e.id);
5071     }
5072 
5073     boolean eventTypeEnabled(int type) {
5074         switch(type) {
5075           case ComponentEvent.COMPONENT_MOVED:
5076           case ComponentEvent.COMPONENT_RESIZED:
5077           case ComponentEvent.COMPONENT_SHOWN:
5078           case ComponentEvent.COMPONENT_HIDDEN:
5079               if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
5080                   componentListener != null) {
5081                   return true;
5082               }
5083               break;
5084           case FocusEvent.FOCUS_GAINED:
5085           case FocusEvent.FOCUS_LOST:
5086               if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 ||
5087                   focusListener != null) {
5088                   return true;
5089               }
5090               break;
5091           case KeyEvent.KEY_PRESSED:
5092           case KeyEvent.KEY_RELEASED:
5093           case KeyEvent.KEY_TYPED:
5094               if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 ||
5095                   keyListener != null) {
5096                   return true;
5097               }
5098               break;
5099           case MouseEvent.MOUSE_PRESSED:
5100           case MouseEvent.MOUSE_RELEASED:
5101           case MouseEvent.MOUSE_ENTERED:
5102           case MouseEvent.MOUSE_EXITED:
5103           case MouseEvent.MOUSE_CLICKED:
5104               if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 ||
5105                   mouseListener != null) {
5106                   return true;
5107               }
5108               break;
5109           case MouseEvent.MOUSE_MOVED:
5110           case MouseEvent.MOUSE_DRAGGED:
5111               if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 ||
5112                   mouseMotionListener != null) {
5113                   return true;
5114               }
5115               break;
5116           case MouseEvent.MOUSE_WHEEL:
5117               if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||
5118                   mouseWheelListener != null) {
5119                   return true;
5120               }
5121               break;
5122           case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
5123           case InputMethodEvent.CARET_POSITION_CHANGED:
5124               if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 ||
5125                   inputMethodListener != null) {
5126                   return true;
5127               }
5128               break;
5129           case HierarchyEvent.HIERARCHY_CHANGED:
5130               if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5131                   hierarchyListener != null) {
5132                   return true;
5133               }
5134               break;
5135           case HierarchyEvent.ANCESTOR_MOVED:
5136           case HierarchyEvent.ANCESTOR_RESIZED:
5137               if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5138                   hierarchyBoundsListener != null) {
5139                   return true;
5140               }
5141               break;
5142           case ActionEvent.ACTION_PERFORMED:
5143               if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) {
5144                   return true;
5145               }
5146               break;
5147           case TextEvent.TEXT_VALUE_CHANGED:
5148               if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) {
5149                   return true;
5150               }
5151               break;
5152           case ItemEvent.ITEM_STATE_CHANGED:
5153               if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) {
5154                   return true;
5155               }
5156               break;
5157           case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:
5158               if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) {
5159                   return true;
5160               }
5161               break;
5162           default:
5163               break;
5164         }
5165         //
5166         // Always pass on events defined by external programs.
5167         //
5168         if (type > AWTEvent.RESERVED_ID_MAX) {
5169             return true;
5170         }
5171         return false;
5172     }
5173 
5174     /**
5175      * @deprecated As of JDK version 1.1,
5176      * replaced by dispatchEvent(AWTEvent).
5177      */
5178     @Deprecated
5179     public boolean postEvent(Event e) {
5180         ComponentPeer peer = this.peer;
5181 
5182         if (handleEvent(e)) {
5183             e.consume();
5184             return true;
5185         }
5186 
5187         Component parent = this.parent;
5188         int eventx = e.x;
5189         int eventy = e.y;
5190         if (parent != null) {
5191             e.translate(x, y);
5192             if (parent.postEvent(e)) {
5193                 e.consume();
5194                 return true;
5195             }
5196             // restore coords
5197             e.x = eventx;
5198             e.y = eventy;
5199         }
5200         return false;
5201     }
5202 
5203     // Event source interfaces
5204 
5205     /**
5206      * Adds the specified component listener to receive component events from
5207      * this component.
5208      * If listener <code>l</code> is <code>null</code>,
5209      * no exception is thrown and no action is performed.
5210      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5211      * >AWT Threading Issues</a> for details on AWT's threading model.
5212      *
5213      * @param    l   the component listener
5214      * @see      java.awt.event.ComponentEvent
5215      * @see      java.awt.event.ComponentListener
5216      * @see      #removeComponentListener
5217      * @see      #getComponentListeners
5218      * @since    JDK1.1
5219      */
5220     public synchronized void addComponentListener(ComponentListener l) {
5221         if (l == null) {
5222             return;
5223         }
5224         componentListener = AWTEventMulticaster.add(componentListener, l);
5225         newEventsOnly = true;
5226     }
5227 
5228     /**
5229      * Removes the specified component listener so that it no longer
5230      * receives component events from this component. This method performs
5231      * no function, nor does it throw an exception, if the listener
5232      * specified by the argument was not previously added to this component.
5233      * If listener <code>l</code> is <code>null</code>,
5234      * no exception is thrown and no action is performed.
5235      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5236      * >AWT Threading Issues</a> for details on AWT's threading model.
5237      * @param    l   the component listener
5238      * @see      java.awt.event.ComponentEvent
5239      * @see      java.awt.event.ComponentListener
5240      * @see      #addComponentListener
5241      * @see      #getComponentListeners
5242      * @since    JDK1.1
5243      */
5244     public synchronized void removeComponentListener(ComponentListener l) {
5245         if (l == null) {
5246             return;
5247         }
5248         componentListener = AWTEventMulticaster.remove(componentListener, l);
5249     }
5250 
5251     /**
5252      * Returns an array of all the component listeners
5253      * registered on this component.
5254      *
5255      * @return all <code>ComponentListener</code>s of this component
5256      *         or an empty array if no component
5257      *         listeners are currently registered
5258      *
5259      * @see #addComponentListener
5260      * @see #removeComponentListener
5261      * @since 1.4
5262      */
5263     public synchronized ComponentListener[] getComponentListeners() {
5264         return getListeners(ComponentListener.class);
5265     }
5266 
5267     /**
5268      * Adds the specified focus listener to receive focus events from
5269      * this component when this component gains input focus.
5270      * If listener <code>l</code> is <code>null</code>,
5271      * no exception is thrown and no action is performed.
5272      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5273      * >AWT Threading Issues</a> for details on AWT's threading model.
5274      *
5275      * @param    l   the focus listener
5276      * @see      java.awt.event.FocusEvent
5277      * @see      java.awt.event.FocusListener
5278      * @see      #removeFocusListener
5279      * @see      #getFocusListeners
5280      * @since    JDK1.1
5281      */
5282     public synchronized void addFocusListener(FocusListener l) {
5283         if (l == null) {
5284             return;
5285         }
5286         focusListener = AWTEventMulticaster.add(focusListener, l);
5287         newEventsOnly = true;
5288 
5289         // if this is a lightweight component, enable focus events
5290         // in the native container.
5291         if (peer instanceof LightweightPeer) {
5292             parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5293         }
5294     }
5295 
5296     /**
5297      * Removes the specified focus listener so that it no longer
5298      * receives focus events from this component. This method performs
5299      * no function, nor does it throw an exception, if the listener
5300      * specified by the argument was not previously added to this component.
5301      * If listener <code>l</code> is <code>null</code>,
5302      * no exception is thrown and no action is performed.
5303      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5304      * >AWT Threading Issues</a> for details on AWT's threading model.
5305      *
5306      * @param    l   the focus listener
5307      * @see      java.awt.event.FocusEvent
5308      * @see      java.awt.event.FocusListener
5309      * @see      #addFocusListener
5310      * @see      #getFocusListeners
5311      * @since    JDK1.1
5312      */
5313     public synchronized void removeFocusListener(FocusListener l) {
5314         if (l == null) {
5315             return;
5316         }
5317         focusListener = AWTEventMulticaster.remove(focusListener, l);
5318     }
5319 
5320     /**
5321      * Returns an array of all the focus listeners
5322      * registered on this component.
5323      *
5324      * @return all of this component's <code>FocusListener</code>s
5325      *         or an empty array if no component
5326      *         listeners are currently registered
5327      *
5328      * @see #addFocusListener
5329      * @see #removeFocusListener
5330      * @since 1.4
5331      */
5332     public synchronized FocusListener[] getFocusListeners() {
5333         return getListeners(FocusListener.class);
5334     }
5335 
5336     /**
5337      * Adds the specified hierarchy listener to receive hierarchy changed
5338      * events from this component when the hierarchy to which this container
5339      * belongs changes.
5340      * If listener <code>l</code> is <code>null</code>,
5341      * no exception is thrown and no action is performed.
5342      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5343      * >AWT Threading Issues</a> for details on AWT's threading model.
5344      *
5345      * @param    l   the hierarchy listener
5346      * @see      java.awt.event.HierarchyEvent
5347      * @see      java.awt.event.HierarchyListener
5348      * @see      #removeHierarchyListener
5349      * @see      #getHierarchyListeners
5350      * @since    1.3
5351      */
5352     public void addHierarchyListener(HierarchyListener l) {
5353         if (l == null) {
5354             return;
5355         }
5356         boolean notifyAncestors;
5357         synchronized (this) {
5358             notifyAncestors =
5359                 (hierarchyListener == null &&
5360                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5361             hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5362             notifyAncestors = (notifyAncestors && hierarchyListener != null);
5363             newEventsOnly = true;
5364         }
5365         if (notifyAncestors) {
5366             synchronized (getTreeLock()) {
5367                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5368                                                 1);
5369             }
5370         }
5371     }
5372 
5373     /**
5374      * Removes the specified hierarchy listener so that it no longer
5375      * receives hierarchy changed events from this component. This method
5376      * performs no function, nor does it throw an exception, if the listener
5377      * specified by the argument was not previously added to this component.
5378      * If listener <code>l</code> is <code>null</code>,
5379      * no exception is thrown and no action is performed.
5380      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5381      * >AWT Threading Issues</a> for details on AWT's threading model.
5382      *
5383      * @param    l   the hierarchy listener
5384      * @see      java.awt.event.HierarchyEvent
5385      * @see      java.awt.event.HierarchyListener
5386      * @see      #addHierarchyListener
5387      * @see      #getHierarchyListeners
5388      * @since    1.3
5389      */
5390     public void removeHierarchyListener(HierarchyListener l) {
5391         if (l == null) {
5392             return;
5393         }
5394         boolean notifyAncestors;
5395         synchronized (this) {
5396             notifyAncestors =
5397                 (hierarchyListener != null &&
5398                  (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5399             hierarchyListener =
5400                 AWTEventMulticaster.remove(hierarchyListener, l);
5401             notifyAncestors = (notifyAncestors && hierarchyListener == null);
5402         }
5403         if (notifyAncestors) {
5404             synchronized (getTreeLock()) {
5405                 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5406                                                 -1);
5407             }
5408         }
5409     }
5410 
5411     /**
5412      * Returns an array of all the hierarchy listeners
5413      * registered on this component.
5414      *
5415      * @return all of this component's <code>HierarchyListener</code>s
5416      *         or an empty array if no hierarchy
5417      *         listeners are currently registered
5418      *
5419      * @see      #addHierarchyListener
5420      * @see      #removeHierarchyListener
5421      * @since    1.4
5422      */
5423     public synchronized HierarchyListener[] getHierarchyListeners() {
5424         return getListeners(HierarchyListener.class);
5425     }
5426 
5427     /**
5428      * Adds the specified hierarchy bounds listener to receive hierarchy
5429      * bounds events from this component when the hierarchy to which this
5430      * container belongs changes.
5431      * If listener <code>l</code> is <code>null</code>,
5432      * no exception is thrown and no action is performed.
5433      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5434      * >AWT Threading Issues</a> for details on AWT's threading model.
5435      *
5436      * @param    l   the hierarchy bounds listener
5437      * @see      java.awt.event.HierarchyEvent
5438      * @see      java.awt.event.HierarchyBoundsListener
5439      * @see      #removeHierarchyBoundsListener
5440      * @see      #getHierarchyBoundsListeners
5441      * @since    1.3
5442      */
5443     public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5444         if (l == null) {
5445             return;
5446         }
5447         boolean notifyAncestors;
5448         synchronized (this) {
5449             notifyAncestors =
5450                 (hierarchyBoundsListener == null &&
5451                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5452             hierarchyBoundsListener =
5453                 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5454             notifyAncestors = (notifyAncestors &&
5455                                hierarchyBoundsListener != null);
5456             newEventsOnly = true;
5457         }
5458         if (notifyAncestors) {
5459             synchronized (getTreeLock()) {
5460                 adjustListeningChildrenOnParent(
5461                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5462             }
5463         }
5464     }
5465 
5466     /**
5467      * Removes the specified hierarchy bounds listener so that it no longer
5468      * receives hierarchy bounds events from this component. This method
5469      * performs no function, nor does it throw an exception, if the listener
5470      * specified by the argument was not previously added to this component.
5471      * If listener <code>l</code> is <code>null</code>,
5472      * no exception is thrown and no action is performed.
5473      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5474      * >AWT Threading Issues</a> for details on AWT's threading model.
5475      *
5476      * @param    l   the hierarchy bounds listener
5477      * @see      java.awt.event.HierarchyEvent
5478      * @see      java.awt.event.HierarchyBoundsListener
5479      * @see      #addHierarchyBoundsListener
5480      * @see      #getHierarchyBoundsListeners
5481      * @since    1.3
5482      */
5483     public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5484         if (l == null) {
5485             return;
5486         }
5487         boolean notifyAncestors;
5488         synchronized (this) {
5489             notifyAncestors =
5490                 (hierarchyBoundsListener != null &&
5491                  (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5492             hierarchyBoundsListener =
5493                 AWTEventMulticaster.remove(hierarchyBoundsListener, l);
5494             notifyAncestors = (notifyAncestors &&
5495                                hierarchyBoundsListener == null);
5496         }
5497         if (notifyAncestors) {
5498             synchronized (getTreeLock()) {
5499                 adjustListeningChildrenOnParent(
5500                                                 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1);
5501             }
5502         }
5503     }
5504 
5505     // Should only be called while holding the tree lock
5506     int numListening(long mask) {
5507         // One mask or the other, but not neither or both.
5508         if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5509             if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&
5510                 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))
5511             {
5512                 eventLog.fine("Assertion failed");
5513             }
5514         }
5515         if ((mask == AWTEvent.HIERARCHY_EVENT_MASK &&
5516              (hierarchyListener != null ||
5517               (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) ||
5518             (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK &&
5519              (hierarchyBoundsListener != null ||
5520               (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) {
5521             return 1;
5522         } else {
5523             return 0;
5524         }
5525     }
5526 
5527     // Should only be called while holding tree lock
5528     int countHierarchyMembers() {
5529         return 1;
5530     }
5531     // Should only be called while holding the tree lock
5532     int createHierarchyEvents(int id, Component changed,
5533                               Container changedParent, long changeFlags,
5534                               boolean enabledOnToolkit) {
5535         switch (id) {
5536           case HierarchyEvent.HIERARCHY_CHANGED:
5537               if (hierarchyListener != null ||
5538                   (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
5539                   enabledOnToolkit) {
5540                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5541                                                         changedParent,
5542                                                         changeFlags);
5543                   dispatchEvent(e);
5544                   return 1;
5545               }
5546               break;
5547           case HierarchyEvent.ANCESTOR_MOVED:
5548           case HierarchyEvent.ANCESTOR_RESIZED:
5549               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5550                   if (changeFlags != 0) {
5551                       eventLog.fine("Assertion (changeFlags == 0) failed");
5552                   }
5553               }
5554               if (hierarchyBoundsListener != null ||
5555                   (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||
5556                   enabledOnToolkit) {
5557                   HierarchyEvent e = new HierarchyEvent(this, id, changed,
5558                                                         changedParent);
5559                   dispatchEvent(e);
5560                   return 1;
5561               }
5562               break;
5563           default:
5564               // assert false
5565               if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5566                   eventLog.fine("This code must never be reached");
5567               }
5568               break;
5569         }
5570         return 0;
5571     }
5572 
5573     /**
5574      * Returns an array of all the hierarchy bounds listeners
5575      * registered on this component.
5576      *
5577      * @return all of this component's <code>HierarchyBoundsListener</code>s
5578      *         or an empty array if no hierarchy bounds
5579      *         listeners are currently registered
5580      *
5581      * @see      #addHierarchyBoundsListener
5582      * @see      #removeHierarchyBoundsListener
5583      * @since    1.4
5584      */
5585     public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5586         return getListeners(HierarchyBoundsListener.class);
5587     }
5588 
5589     /*
5590      * Should only be called while holding the tree lock.
5591      * It's added only for overriding in java.awt.Window
5592      * because parent in Window is owner.
5593      */
5594     void adjustListeningChildrenOnParent(long mask, int num) {
5595         if (parent != null) {
5596             parent.adjustListeningChildren(mask, num);
5597         }
5598     }
5599 
5600     /**
5601      * Adds the specified key listener to receive key events from
5602      * this component.
5603      * If l is null, no exception is thrown and no action is performed.
5604      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5605      * >AWT Threading Issues</a> for details on AWT's threading model.
5606      *
5607      * @param    l   the key listener.
5608      * @see      java.awt.event.KeyEvent
5609      * @see      java.awt.event.KeyListener
5610      * @see      #removeKeyListener
5611      * @see      #getKeyListeners
5612      * @since    JDK1.1
5613      */
5614     public synchronized void addKeyListener(KeyListener l) {
5615         if (l == null) {
5616             return;
5617         }
5618         keyListener = AWTEventMulticaster.add(keyListener, l);
5619         newEventsOnly = true;
5620 
5621         // if this is a lightweight component, enable key events
5622         // in the native container.
5623         if (peer instanceof LightweightPeer) {
5624             parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5625         }
5626     }
5627 
5628     /**
5629      * Removes the specified key listener so that it no longer
5630      * receives key events from this component. This method performs
5631      * no function, nor does it throw an exception, if the listener
5632      * specified by the argument was not previously added to this component.
5633      * If listener <code>l</code> is <code>null</code>,
5634      * no exception is thrown and no action is performed.
5635      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5636      * >AWT Threading Issues</a> for details on AWT's threading model.
5637      *
5638      * @param    l   the key listener
5639      * @see      java.awt.event.KeyEvent
5640      * @see      java.awt.event.KeyListener
5641      * @see      #addKeyListener
5642      * @see      #getKeyListeners
5643      * @since    JDK1.1
5644      */
5645     public synchronized void removeKeyListener(KeyListener l) {
5646         if (l == null) {
5647             return;
5648         }
5649         keyListener = AWTEventMulticaster.remove(keyListener, l);
5650     }
5651 
5652     /**
5653      * Returns an array of all the key listeners
5654      * registered on this component.
5655      *
5656      * @return all of this component's <code>KeyListener</code>s
5657      *         or an empty array if no key
5658      *         listeners are currently registered
5659      *
5660      * @see      #addKeyListener
5661      * @see      #removeKeyListener
5662      * @since    1.4
5663      */
5664     public synchronized KeyListener[] getKeyListeners() {
5665         return getListeners(KeyListener.class);
5666     }
5667 
5668     /**
5669      * Adds the specified mouse listener to receive mouse events from
5670      * this component.
5671      * If listener <code>l</code> is <code>null</code>,
5672      * no exception is thrown and no action is performed.
5673      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5674      * >AWT Threading Issues</a> for details on AWT's threading model.
5675      *
5676      * @param    l   the mouse listener
5677      * @see      java.awt.event.MouseEvent
5678      * @see      java.awt.event.MouseListener
5679      * @see      #removeMouseListener
5680      * @see      #getMouseListeners
5681      * @since    JDK1.1
5682      */
5683     public synchronized void addMouseListener(MouseListener l) {
5684         if (l == null) {
5685             return;
5686         }
5687         mouseListener = AWTEventMulticaster.add(mouseListener,l);
5688         newEventsOnly = true;
5689 
5690         // if this is a lightweight component, enable mouse events
5691         // in the native container.
5692         if (peer instanceof LightweightPeer) {
5693             parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5694         }
5695     }
5696 
5697     /**
5698      * Removes the specified mouse listener so that it no longer
5699      * receives mouse events from this component. This method performs
5700      * no function, nor does it throw an exception, if the listener
5701      * specified by the argument was not previously added to this component.
5702      * If listener <code>l</code> is <code>null</code>,
5703      * no exception is thrown and no action is performed.
5704      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5705      * >AWT Threading Issues</a> for details on AWT's threading model.
5706      *
5707      * @param    l   the mouse listener
5708      * @see      java.awt.event.MouseEvent
5709      * @see      java.awt.event.MouseListener
5710      * @see      #addMouseListener
5711      * @see      #getMouseListeners
5712      * @since    JDK1.1
5713      */
5714     public synchronized void removeMouseListener(MouseListener l) {
5715         if (l == null) {
5716             return;
5717         }
5718         mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5719     }
5720 
5721     /**
5722      * Returns an array of all the mouse listeners
5723      * registered on this component.
5724      *
5725      * @return all of this component's <code>MouseListener</code>s
5726      *         or an empty array if no mouse
5727      *         listeners are currently registered
5728      *
5729      * @see      #addMouseListener
5730      * @see      #removeMouseListener
5731      * @since    1.4
5732      */
5733     public synchronized MouseListener[] getMouseListeners() {
5734         return getListeners(MouseListener.class);
5735     }
5736 
5737     /**
5738      * Adds the specified mouse motion listener to receive mouse motion
5739      * events from this component.
5740      * If listener <code>l</code> is <code>null</code>,
5741      * no exception is thrown and no action is performed.
5742      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5743      * >AWT Threading Issues</a> for details on AWT's threading model.
5744      *
5745      * @param    l   the mouse motion listener
5746      * @see      java.awt.event.MouseEvent
5747      * @see      java.awt.event.MouseMotionListener
5748      * @see      #removeMouseMotionListener
5749      * @see      #getMouseMotionListeners
5750      * @since    JDK1.1
5751      */
5752     public synchronized void addMouseMotionListener(MouseMotionListener l) {
5753         if (l == null) {
5754             return;
5755         }
5756         mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5757         newEventsOnly = true;
5758 
5759         // if this is a lightweight component, enable mouse events
5760         // in the native container.
5761         if (peer instanceof LightweightPeer) {
5762             parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5763         }
5764     }
5765 
5766     /**
5767      * Removes the specified mouse motion listener so that it no longer
5768      * receives mouse motion events from this component. This method performs
5769      * no function, nor does it throw an exception, if the listener
5770      * specified by the argument was not previously added to this component.
5771      * If listener <code>l</code> is <code>null</code>,
5772      * no exception is thrown and no action is performed.
5773      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5774      * >AWT Threading Issues</a> for details on AWT's threading model.
5775      *
5776      * @param    l   the mouse motion listener
5777      * @see      java.awt.event.MouseEvent
5778      * @see      java.awt.event.MouseMotionListener
5779      * @see      #addMouseMotionListener
5780      * @see      #getMouseMotionListeners
5781      * @since    JDK1.1
5782      */
5783     public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5784         if (l == null) {
5785             return;
5786         }
5787         mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5788     }
5789 
5790     /**
5791      * Returns an array of all the mouse motion listeners
5792      * registered on this component.
5793      *
5794      * @return all of this component's <code>MouseMotionListener</code>s
5795      *         or an empty array if no mouse motion
5796      *         listeners are currently registered
5797      *
5798      * @see      #addMouseMotionListener
5799      * @see      #removeMouseMotionListener
5800      * @since    1.4
5801      */
5802     public synchronized MouseMotionListener[] getMouseMotionListeners() {
5803         return getListeners(MouseMotionListener.class);
5804     }
5805 
5806     /**
5807      * Adds the specified mouse wheel listener to receive mouse wheel events
5808      * from this component.  Containers also receive mouse wheel events from
5809      * sub-components.
5810      * <p>
5811      * For information on how mouse wheel events are dispatched, see
5812      * the class description for {@link MouseWheelEvent}.
5813      * <p>
5814      * If l is <code>null</code>, no exception is thrown and no
5815      * action is performed.
5816      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5817      * >AWT Threading Issues</a> for details on AWT's threading model.
5818      *
5819      * @param    l   the mouse wheel listener
5820      * @see      java.awt.event.MouseWheelEvent
5821      * @see      java.awt.event.MouseWheelListener
5822      * @see      #removeMouseWheelListener
5823      * @see      #getMouseWheelListeners
5824      * @since    1.4
5825      */
5826     public synchronized void addMouseWheelListener(MouseWheelListener l) {
5827         if (l == null) {
5828             return;
5829         }
5830         mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5831         newEventsOnly = true;
5832 
5833         // if this is a lightweight component, enable mouse events
5834         // in the native container.
5835         if (peer instanceof LightweightPeer) {
5836             parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
5837         }
5838     }
5839 
5840     /**
5841      * Removes the specified mouse wheel listener so that it no longer
5842      * receives mouse wheel events from this component. This method performs
5843      * no function, nor does it throw an exception, if the listener
5844      * specified by the argument was not previously added to this component.
5845      * If l is null, no exception is thrown and no action is performed.
5846      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5847      * >AWT Threading Issues</a> for details on AWT's threading model.
5848      *
5849      * @param    l   the mouse wheel listener.
5850      * @see      java.awt.event.MouseWheelEvent
5851      * @see      java.awt.event.MouseWheelListener
5852      * @see      #addMouseWheelListener
5853      * @see      #getMouseWheelListeners
5854      * @since    1.4
5855      */
5856     public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5857         if (l == null) {
5858             return;
5859         }
5860         mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5861     }
5862 
5863     /**
5864      * Returns an array of all the mouse wheel listeners
5865      * registered on this component.
5866      *
5867      * @return all of this component's <code>MouseWheelListener</code>s
5868      *         or an empty array if no mouse wheel
5869      *         listeners are currently registered
5870      *
5871      * @see      #addMouseWheelListener
5872      * @see      #removeMouseWheelListener
5873      * @since    1.4
5874      */
5875     public synchronized MouseWheelListener[] getMouseWheelListeners() {
5876         return getListeners(MouseWheelListener.class);
5877     }
5878 
5879     /**
5880      * Adds the specified input method listener to receive
5881      * input method events from this component. A component will
5882      * only receive input method events from input methods
5883      * if it also overrides <code>getInputMethodRequests</code> to return an
5884      * <code>InputMethodRequests</code> instance.
5885      * If listener <code>l</code> is <code>null</code>,
5886      * no exception is thrown and no action is performed.
5887      * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
5888      * >AWT Threading Issues</a> for details on AWT's threading model.
5889      *
5890      * @param    l   the input method listener
5891      * @see      java.awt.event.InputMethodEvent
5892      * @see      java.awt.event.InputMethodListener
5893      * @see      #removeInputMethodListener
5894      * @see      #getInputMethodListeners
5895      * @see      #getInputMethodRequests
5896      * @since    1.2
5897      */
5898     public synchronized void addInputMethodListener(InputMethodListener l) {
5899         if (l == null) {
5900             return;
5901         }
5902         inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5903         newEventsOnly = true;
5904     }
5905 
5906     /**
5907      * Removes the specified input method listener so that it no longer
5908      * receives input method events from this component. This method performs
5909      * no function, nor does it throw an exception, if the listener
5910      * specified by the argument was not previously added to this component.
5911      * If listener <code>l</code> is <code>null</code>,
5912      * no exception is thrown and no action is performed.
5913      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5914      * >AWT Threading Issues</a> for details on AWT's threading model.
5915      *
5916      * @param    l   the input method listener
5917      * @see      java.awt.event.InputMethodEvent
5918      * @see      java.awt.event.InputMethodListener
5919      * @see      #addInputMethodListener
5920      * @see      #getInputMethodListeners
5921      * @since    1.2
5922      */
5923     public synchronized void removeInputMethodListener(InputMethodListener l) {
5924         if (l == null) {
5925             return;
5926         }
5927         inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
5928     }
5929 
5930     /**
5931      * Returns an array of all the input method listeners
5932      * registered on this component.
5933      *
5934      * @return all of this component's <code>InputMethodListener</code>s
5935      *         or an empty array if no input method
5936      *         listeners are currently registered
5937      *
5938      * @see      #addInputMethodListener
5939      * @see      #removeInputMethodListener
5940      * @since    1.4
5941      */
5942     public synchronized InputMethodListener[] getInputMethodListeners() {
5943         return getListeners(InputMethodListener.class);
5944     }
5945 
5946     /**
5947      * Returns an array of all the objects currently registered
5948      * as <code><em>Foo</em>Listener</code>s
5949      * upon this <code>Component</code>.
5950      * <code><em>Foo</em>Listener</code>s are registered using the
5951      * <code>add<em>Foo</em>Listener</code> method.
5952      *
5953      * <p>
5954      * You can specify the <code>listenerType</code> argument
5955      * with a class literal, such as
5956      * <code><em>Foo</em>Listener.class</code>.
5957      * For example, you can query a
5958      * <code>Component</code> <code>c</code>
5959      * for its mouse listeners with the following code:
5960      *
5961      * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
5962      *
5963      * If no such listeners exist, this method returns an empty array.
5964      *
5965      * @param listenerType the type of listeners requested; this parameter
5966      *          should specify an interface that descends from
5967      *          <code>java.util.EventListener</code>
5968      * @return an array of all objects registered as
5969      *          <code><em>Foo</em>Listener</code>s on this component,
5970      *          or an empty array if no such listeners have been added
5971      * @exception ClassCastException if <code>listenerType</code>
5972      *          doesn't specify a class or interface that implements
5973      *          <code>java.util.EventListener</code>
5974      * @throws NullPointerException if {@code listenerType} is {@code null}
5975      * @see #getComponentListeners
5976      * @see #getFocusListeners
5977      * @see #getHierarchyListeners
5978      * @see #getHierarchyBoundsListeners
5979      * @see #getKeyListeners
5980      * @see #getMouseListeners
5981      * @see #getMouseMotionListeners
5982      * @see #getMouseWheelListeners
5983      * @see #getInputMethodListeners
5984      * @see #getPropertyChangeListeners
5985      *
5986      * @since 1.3
5987      */
5988     @SuppressWarnings("unchecked")
5989     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
5990         EventListener l = null;
5991         if  (listenerType == ComponentListener.class) {
5992             l = componentListener;
5993         } else if (listenerType == FocusListener.class) {
5994             l = focusListener;
5995         } else if (listenerType == HierarchyListener.class) {
5996             l = hierarchyListener;
5997         } else if (listenerType == HierarchyBoundsListener.class) {
5998             l = hierarchyBoundsListener;
5999         } else if (listenerType == KeyListener.class) {
6000             l = keyListener;
6001         } else if (listenerType == MouseListener.class) {
6002             l = mouseListener;
6003         } else if (listenerType == MouseMotionListener.class) {
6004             l = mouseMotionListener;
6005         } else if (listenerType == MouseWheelListener.class) {
6006             l = mouseWheelListener;
6007         } else if (listenerType == InputMethodListener.class) {
6008             l = inputMethodListener;
6009         } else if (listenerType == PropertyChangeListener.class) {
6010             return (T[])getPropertyChangeListeners();
6011         }
6012         return AWTEventMulticaster.getListeners(l, listenerType);
6013     }
6014 
6015     /**
6016      * Gets the input method request handler which supports
6017      * requests from input methods for this component. A component
6018      * that supports on-the-spot text input must override this
6019      * method to return an <code>InputMethodRequests</code> instance.
6020      * At the same time, it also has to handle input method events.
6021      *
6022      * @return the input method request handler for this component,
6023      *          <code>null</code> by default
6024      * @see #addInputMethodListener
6025      * @since 1.2
6026      */
6027     public InputMethodRequests getInputMethodRequests() {
6028         return null;
6029     }
6030 
6031     /**
6032      * Gets the input context used by this component for handling
6033      * the communication with input methods when text is entered
6034      * in this component. By default, the input context used for
6035      * the parent component is returned. Components may
6036      * override this to return a private input context.
6037      *
6038      * @return the input context used by this component;
6039      *          <code>null</code> if no context can be determined
6040      * @since 1.2
6041      */
6042     public InputContext getInputContext() {
6043         Container parent = this.parent;
6044         if (parent == null) {
6045             return null;
6046         } else {
6047             return parent.getInputContext();
6048         }
6049     }
6050 
6051     /**
6052      * Enables the events defined by the specified event mask parameter
6053      * to be delivered to this component.
6054      * <p>
6055      * Event types are automatically enabled when a listener for
6056      * that event type is added to the component.
6057      * <p>
6058      * This method only needs to be invoked by subclasses of
6059      * <code>Component</code> which desire to have the specified event
6060      * types delivered to <code>processEvent</code> regardless of whether
6061      * or not a listener is registered.
6062      * @param      eventsToEnable   the event mask defining the event types
6063      * @see        #processEvent
6064      * @see        #disableEvents
6065      * @see        AWTEvent
6066      * @since      JDK1.1
6067      */
6068     protected final void enableEvents(long eventsToEnable) {
6069         long notifyAncestors = 0;
6070         synchronized (this) {
6071             if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6072                 hierarchyListener == null &&
6073                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
6074                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6075             }
6076             if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
6077                 hierarchyBoundsListener == null &&
6078                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
6079                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6080             }
6081             eventMask |= eventsToEnable;
6082             newEventsOnly = true;
6083         }
6084 
6085         // if this is a lightweight component, enable mouse events
6086         // in the native container.
6087         if (peer instanceof LightweightPeer) {
6088             parent.proxyEnableEvents(eventMask);
6089         }
6090         if (notifyAncestors != 0) {
6091             synchronized (getTreeLock()) {
6092                 adjustListeningChildrenOnParent(notifyAncestors, 1);
6093             }
6094         }
6095     }
6096 
6097     /**
6098      * Disables the events defined by the specified event mask parameter
6099      * from being delivered to this component.
6100      * @param      eventsToDisable   the event mask defining the event types
6101      * @see        #enableEvents
6102      * @since      JDK1.1
6103      */
6104     protected final void disableEvents(long eventsToDisable) {
6105         long notifyAncestors = 0;
6106         synchronized (this) {
6107             if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6108                 hierarchyListener == null &&
6109                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {
6110                 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6111             }
6112             if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 &&
6113                 hierarchyBoundsListener == null &&
6114                 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {
6115                 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6116             }
6117             eventMask &= ~eventsToDisable;
6118         }
6119         if (notifyAncestors != 0) {
6120             synchronized (getTreeLock()) {
6121                 adjustListeningChildrenOnParent(notifyAncestors, -1);
6122             }
6123         }
6124     }
6125 
6126     transient sun.awt.EventQueueItem[] eventCache;
6127 
6128     /**
6129      * @see #isCoalescingEnabled
6130      * @see #checkCoalescing
6131      */
6132     transient private boolean coalescingEnabled = checkCoalescing();
6133 
6134     /**
6135      * Weak map of known coalesceEvent overriders.
6136      * Value indicates whether overriden.
6137      * Bootstrap classes are not included.
6138      */
6139     private static final Map<Class<?>, Boolean> coalesceMap =
6140         new java.util.WeakHashMap<Class<?>, Boolean>();
6141 
6142     /**
6143      * Indicates whether this class overrides coalesceEvents.
6144      * It is assumed that all classes that are loaded from the bootstrap
6145      *   do not.
6146      * The boostrap class loader is assumed to be represented by null.
6147      * We do not check that the method really overrides
6148      *   (it might be static, private or package private).
6149      */
6150      private boolean checkCoalescing() {
6151          if (getClass().getClassLoader()==null) {
6152              return false;
6153          }
6154          final Class<? extends Component> clazz = getClass();
6155          synchronized (coalesceMap) {
6156              // Check cache.
6157              Boolean value = coalesceMap.get(clazz);
6158              if (value != null) {
6159                  return value;
6160              }
6161 
6162              // Need to check non-bootstraps.
6163              Boolean enabled = java.security.AccessController.doPrivileged(
6164                  new java.security.PrivilegedAction<Boolean>() {
6165                      public Boolean run() {
6166                          return isCoalesceEventsOverriden(clazz);
6167                      }
6168                  }
6169                  );
6170              coalesceMap.put(clazz, enabled);
6171              return enabled;
6172          }
6173      }
6174 
6175     /**
6176      * Parameter types of coalesceEvents(AWTEvent,AWTEVent).
6177      */
6178     private static final Class[] coalesceEventsParams = {
6179         AWTEvent.class, AWTEvent.class
6180     };
6181 
6182     /**
6183      * Indicates whether a class or its superclasses override coalesceEvents.
6184      * Must be called with lock on coalesceMap and privileged.
6185      * @see checkCoalsecing
6186      */
6187     private static boolean isCoalesceEventsOverriden(Class<?> clazz) {
6188         assert Thread.holdsLock(coalesceMap);
6189 
6190         // First check superclass - we may not need to bother ourselves.
6191         Class<?> superclass = clazz.getSuperclass();
6192         if (superclass == null) {
6193             // Only occurs on implementations that
6194             //   do not use null to represent the bootsrap class loader.
6195             return false;
6196         }
6197         if (superclass.getClassLoader() != null) {
6198             Boolean value = coalesceMap.get(superclass);
6199             if (value == null) {
6200                 // Not done already - recurse.
6201                 if (isCoalesceEventsOverriden(superclass)) {
6202                     coalesceMap.put(superclass, true);
6203                     return true;
6204                 }
6205             } else if (value) {
6206                 return true;
6207             }
6208         }
6209 
6210         try {
6211             // Throws if not overriden.
6212             clazz.getDeclaredMethod(
6213                 "coalesceEvents", coalesceEventsParams
6214                 );
6215             return true;
6216         } catch (NoSuchMethodException e) {
6217             // Not present in this class.
6218             return false;
6219         }
6220     }
6221 
6222     /**
6223      * Indicates whether coalesceEvents may do something.
6224      */
6225     final boolean isCoalescingEnabled() {
6226         return coalescingEnabled;
6227      }
6228 
6229 
6230     /**
6231      * Potentially coalesce an event being posted with an existing
6232      * event.  This method is called by <code>EventQueue.postEvent</code>
6233      * if an event with the same ID as the event to be posted is found in
6234      * the queue (both events must have this component as their source).
6235      * This method either returns a coalesced event which replaces
6236      * the existing event (and the new event is then discarded), or
6237      * <code>null</code> to indicate that no combining should be done
6238      * (add the second event to the end of the queue).  Either event
6239      * parameter may be modified and returned, as the other one is discarded
6240      * unless <code>null</code> is returned.
6241      * <p>
6242      * This implementation of <code>coalesceEvents</code> coalesces
6243      * two event types: mouse move (and drag) events,
6244      * and paint (and update) events.
6245      * For mouse move events the last event is always returned, causing
6246      * intermediate moves to be discarded.  For paint events, the new
6247      * event is coalesced into a complex <code>RepaintArea</code> in the peer.
6248      * The new <code>AWTEvent</code> is always returned.
6249      *
6250      * @param  existingEvent  the event already on the <code>EventQueue</code>
6251      * @param  newEvent       the event being posted to the
6252      *          <code>EventQueue</code>
6253      * @return a coalesced event, or <code>null</code> indicating that no
6254      *          coalescing was done
6255      */
6256     protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6257                                       AWTEvent newEvent) {
6258         return null;
6259     }
6260 
6261     /**
6262      * Processes events occurring on this component. By default this
6263      * method calls the appropriate
6264      * <code>process&lt;event&nbsp;type&gt;Event</code>
6265      * method for the given class of event.
6266      * <p>Note that if the event parameter is <code>null</code>
6267      * the behavior is unspecified and may result in an
6268      * exception.
6269      *
6270      * @param     e the event
6271      * @see       #processComponentEvent
6272      * @see       #processFocusEvent
6273      * @see       #processKeyEvent
6274      * @see       #processMouseEvent
6275      * @see       #processMouseMotionEvent
6276      * @see       #processInputMethodEvent
6277      * @see       #processHierarchyEvent
6278      * @see       #processMouseWheelEvent
6279      * @since     JDK1.1
6280      */
6281     protected void processEvent(AWTEvent e) {
6282         if (e instanceof FocusEvent) {
6283             processFocusEvent((FocusEvent)e);
6284 
6285         } else if (e instanceof MouseEvent) {
6286             switch(e.getID()) {
6287               case MouseEvent.MOUSE_PRESSED:
6288               case MouseEvent.MOUSE_RELEASED:
6289               case MouseEvent.MOUSE_CLICKED:
6290               case MouseEvent.MOUSE_ENTERED:
6291               case MouseEvent.MOUSE_EXITED:
6292                   processMouseEvent((MouseEvent)e);
6293                   break;
6294               case MouseEvent.MOUSE_MOVED:
6295               case MouseEvent.MOUSE_DRAGGED:
6296                   processMouseMotionEvent((MouseEvent)e);
6297                   break;
6298               case MouseEvent.MOUSE_WHEEL:
6299                   processMouseWheelEvent((MouseWheelEvent)e);
6300                   break;
6301             }
6302 
6303         } else if (e instanceof KeyEvent) {
6304             processKeyEvent((KeyEvent)e);
6305 
6306         } else if (e instanceof ComponentEvent) {
6307             processComponentEvent((ComponentEvent)e);
6308         } else if (e instanceof InputMethodEvent) {
6309             processInputMethodEvent((InputMethodEvent)e);
6310         } else if (e instanceof HierarchyEvent) {
6311             switch (e.getID()) {
6312               case HierarchyEvent.HIERARCHY_CHANGED:
6313                   processHierarchyEvent((HierarchyEvent)e);
6314                   break;
6315               case HierarchyEvent.ANCESTOR_MOVED:
6316               case HierarchyEvent.ANCESTOR_RESIZED:
6317                   processHierarchyBoundsEvent((HierarchyEvent)e);
6318                   break;
6319             }
6320         }
6321     }
6322 
6323     /**
6324      * Processes component events occurring on this component by
6325      * dispatching them to any registered
6326      * <code>ComponentListener</code> objects.
6327      * <p>
6328      * This method is not called unless component events are
6329      * enabled for this component. Component events are enabled
6330      * when one of the following occurs:
6331      * <ul>
6332      * <li>A <code>ComponentListener</code> object is registered
6333      * via <code>addComponentListener</code>.
6334      * <li>Component events are enabled via <code>enableEvents</code>.
6335      * </ul>
6336      * <p>Note that if the event parameter is <code>null</code>
6337      * the behavior is unspecified and may result in an
6338      * exception.
6339      *
6340      * @param       e the component event
6341      * @see         java.awt.event.ComponentEvent
6342      * @see         java.awt.event.ComponentListener
6343      * @see         #addComponentListener
6344      * @see         #enableEvents
6345      * @since       JDK1.1
6346      */
6347     protected void processComponentEvent(ComponentEvent e) {
6348         ComponentListener listener = componentListener;
6349         if (listener != null) {
6350             int id = e.getID();
6351             switch(id) {
6352               case ComponentEvent.COMPONENT_RESIZED:
6353                   listener.componentResized(e);
6354                   break;
6355               case ComponentEvent.COMPONENT_MOVED:
6356                   listener.componentMoved(e);
6357                   break;
6358               case ComponentEvent.COMPONENT_SHOWN:
6359                   listener.componentShown(e);
6360                   break;
6361               case ComponentEvent.COMPONENT_HIDDEN:
6362                   listener.componentHidden(e);
6363                   break;
6364             }
6365         }
6366     }
6367 
6368     /**
6369      * Processes focus events occurring on this component by
6370      * dispatching them to any registered
6371      * <code>FocusListener</code> objects.
6372      * <p>
6373      * This method is not called unless focus events are
6374      * enabled for this component. Focus events are enabled
6375      * when one of the following occurs:
6376      * <ul>
6377      * <li>A <code>FocusListener</code> object is registered
6378      * via <code>addFocusListener</code>.
6379      * <li>Focus events are enabled via <code>enableEvents</code>.
6380      * </ul>
6381      * <p>
6382      * If focus events are enabled for a <code>Component</code>,
6383      * the current <code>KeyboardFocusManager</code> determines
6384      * whether or not a focus event should be dispatched to
6385      * registered <code>FocusListener</code> objects.  If the
6386      * events are to be dispatched, the <code>KeyboardFocusManager</code>
6387      * calls the <code>Component</code>'s <code>dispatchEvent</code>
6388      * method, which results in a call to the <code>Component</code>'s
6389      * <code>processFocusEvent</code> method.
6390      * <p>
6391      * If focus events are enabled for a <code>Component</code>, calling
6392      * the <code>Component</code>'s <code>dispatchEvent</code> method
6393      * with a <code>FocusEvent</code> as the argument will result in a
6394      * call to the <code>Component</code>'s <code>processFocusEvent</code>
6395      * method regardless of the current <code>KeyboardFocusManager</code>.
6396      *
6397      * <p>Note that if the event parameter is <code>null</code>
6398      * the behavior is unspecified and may result in an
6399      * exception.
6400      *
6401      * @param       e the focus event
6402      * @see         java.awt.event.FocusEvent
6403      * @see         java.awt.event.FocusListener
6404      * @see         java.awt.KeyboardFocusManager
6405      * @see         #addFocusListener
6406      * @see         #enableEvents
6407      * @see         #dispatchEvent
6408      * @since       JDK1.1
6409      */
6410     protected void processFocusEvent(FocusEvent e) {
6411         FocusListener listener = focusListener;
6412         if (listener != null) {
6413             int id = e.getID();
6414             switch(id) {
6415               case FocusEvent.FOCUS_GAINED:
6416                   listener.focusGained(e);
6417                   break;
6418               case FocusEvent.FOCUS_LOST:
6419                   listener.focusLost(e);
6420                   break;
6421             }
6422         }
6423     }
6424 
6425     /**
6426      * Processes key events occurring on this component by
6427      * dispatching them to any registered
6428      * <code>KeyListener</code> objects.
6429      * <p>
6430      * This method is not called unless key events are
6431      * enabled for this component. Key events are enabled
6432      * when one of the following occurs:
6433      * <ul>
6434      * <li>A <code>KeyListener</code> object is registered
6435      * via <code>addKeyListener</code>.
6436      * <li>Key events are enabled via <code>enableEvents</code>.
6437      * </ul>
6438      *
6439      * <p>
6440      * If key events are enabled for a <code>Component</code>,
6441      * the current <code>KeyboardFocusManager</code> determines
6442      * whether or not a key event should be dispatched to
6443      * registered <code>KeyListener</code> objects.  The
6444      * <code>DefaultKeyboardFocusManager</code> will not dispatch
6445      * key events to a <code>Component</code> that is not the focus
6446      * owner or is not showing.
6447      * <p>
6448      * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to
6449      * the focus owner. Please see the
6450      * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6451      * for further information.
6452      * <p>
6453      * Calling a <code>Component</code>'s <code>dispatchEvent</code>
6454      * method with a <code>KeyEvent</code> as the argument will
6455      * result in a call to the <code>Component</code>'s
6456      * <code>processKeyEvent</code> method regardless of the
6457      * current <code>KeyboardFocusManager</code> as long as the
6458      * component is showing, focused, and enabled, and key events
6459      * are enabled on it.
6460      * <p>If the event parameter is <code>null</code>
6461      * the behavior is unspecified and may result in an
6462      * exception.
6463      *
6464      * @param       e the key event
6465      * @see         java.awt.event.KeyEvent
6466      * @see         java.awt.event.KeyListener
6467      * @see         java.awt.KeyboardFocusManager
6468      * @see         java.awt.DefaultKeyboardFocusManager
6469      * @see         #processEvent
6470      * @see         #dispatchEvent
6471      * @see         #addKeyListener
6472      * @see         #enableEvents
6473      * @see         #isShowing
6474      * @since       JDK1.1
6475      */
6476     protected void processKeyEvent(KeyEvent e) {
6477         KeyListener listener = keyListener;
6478         if (listener != null) {
6479             int id = e.getID();
6480             switch(id) {
6481               case KeyEvent.KEY_TYPED:
6482                   listener.keyTyped(e);
6483                   break;
6484               case KeyEvent.KEY_PRESSED:
6485                   listener.keyPressed(e);
6486                   break;
6487               case KeyEvent.KEY_RELEASED:
6488                   listener.keyReleased(e);
6489                   break;
6490             }
6491         }
6492     }
6493 
6494     /**
6495      * Processes mouse events occurring on this component by
6496      * dispatching them to any registered
6497      * <code>MouseListener</code> objects.
6498      * <p>
6499      * This method is not called unless mouse events are
6500      * enabled for this component. Mouse events are enabled
6501      * when one of the following occurs:
6502      * <ul>
6503      * <li>A <code>MouseListener</code> object is registered
6504      * via <code>addMouseListener</code>.
6505      * <li>Mouse events are enabled via <code>enableEvents</code>.
6506      * </ul>
6507      * <p>Note that if the event parameter is <code>null</code>
6508      * the behavior is unspecified and may result in an
6509      * exception.
6510      *
6511      * @param       e the mouse event
6512      * @see         java.awt.event.MouseEvent
6513      * @see         java.awt.event.MouseListener
6514      * @see         #addMouseListener
6515      * @see         #enableEvents
6516      * @since       JDK1.1
6517      */
6518     protected void processMouseEvent(MouseEvent e) {
6519         MouseListener listener = mouseListener;
6520         if (listener != null) {
6521             int id = e.getID();
6522             switch(id) {
6523               case MouseEvent.MOUSE_PRESSED:
6524                   listener.mousePressed(e);
6525                   break;
6526               case MouseEvent.MOUSE_RELEASED:
6527                   listener.mouseReleased(e);
6528                   break;
6529               case MouseEvent.MOUSE_CLICKED:
6530                   listener.mouseClicked(e);
6531                   break;
6532               case MouseEvent.MOUSE_EXITED:
6533                   listener.mouseExited(e);
6534                   break;
6535               case MouseEvent.MOUSE_ENTERED:
6536                   listener.mouseEntered(e);
6537                   break;
6538             }
6539         }
6540     }
6541 
6542     /**
6543      * Processes mouse motion events occurring on this component by
6544      * dispatching them to any registered
6545      * <code>MouseMotionListener</code> objects.
6546      * <p>
6547      * This method is not called unless mouse motion events are
6548      * enabled for this component. Mouse motion events are enabled
6549      * when one of the following occurs:
6550      * <ul>
6551      * <li>A <code>MouseMotionListener</code> object is registered
6552      * via <code>addMouseMotionListener</code>.
6553      * <li>Mouse motion events are enabled via <code>enableEvents</code>.
6554      * </ul>
6555      * <p>Note that if the event parameter is <code>null</code>
6556      * the behavior is unspecified and may result in an
6557      * exception.
6558      *
6559      * @param       e the mouse motion event
6560      * @see         java.awt.event.MouseEvent
6561      * @see         java.awt.event.MouseMotionListener
6562      * @see         #addMouseMotionListener
6563      * @see         #enableEvents
6564      * @since       JDK1.1
6565      */
6566     protected void processMouseMotionEvent(MouseEvent e) {
6567         MouseMotionListener listener = mouseMotionListener;
6568         if (listener != null) {
6569             int id = e.getID();
6570             switch(id) {
6571               case MouseEvent.MOUSE_MOVED:
6572                   listener.mouseMoved(e);
6573                   break;
6574               case MouseEvent.MOUSE_DRAGGED:
6575                   listener.mouseDragged(e);
6576                   break;
6577             }
6578         }
6579     }
6580 
6581     /**
6582      * Processes mouse wheel events occurring on this component by
6583      * dispatching them to any registered
6584      * <code>MouseWheelListener</code> objects.
6585      * <p>
6586      * This method is not called unless mouse wheel events are
6587      * enabled for this component. Mouse wheel events are enabled
6588      * when one of the following occurs:
6589      * <ul>
6590      * <li>A <code>MouseWheelListener</code> object is registered
6591      * via <code>addMouseWheelListener</code>.
6592      * <li>Mouse wheel events are enabled via <code>enableEvents</code>.
6593      * </ul>
6594      * <p>
6595      * For information on how mouse wheel events are dispatched, see
6596      * the class description for {@link MouseWheelEvent}.
6597      * <p>
6598      * Note that if the event parameter is <code>null</code>
6599      * the behavior is unspecified and may result in an
6600      * exception.
6601      *
6602      * @param       e the mouse wheel event
6603      * @see         java.awt.event.MouseWheelEvent
6604      * @see         java.awt.event.MouseWheelListener
6605      * @see         #addMouseWheelListener
6606      * @see         #enableEvents
6607      * @since       1.4
6608      */
6609     protected void processMouseWheelEvent(MouseWheelEvent e) {
6610         MouseWheelListener listener = mouseWheelListener;
6611         if (listener != null) {
6612             int id = e.getID();
6613             switch(id) {
6614               case MouseEvent.MOUSE_WHEEL:
6615                   listener.mouseWheelMoved(e);
6616                   break;
6617             }
6618         }
6619     }
6620 
6621     boolean postsOldMouseEvents() {
6622         return false;
6623     }
6624 
6625     /**
6626      * Processes input method events occurring on this component by
6627      * dispatching them to any registered
6628      * <code>InputMethodListener</code> objects.
6629      * <p>
6630      * This method is not called unless input method events
6631      * are enabled for this component. Input method events are enabled
6632      * when one of the following occurs:
6633      * <ul>
6634      * <li>An <code>InputMethodListener</code> object is registered
6635      * via <code>addInputMethodListener</code>.
6636      * <li>Input method events are enabled via <code>enableEvents</code>.
6637      * </ul>
6638      * <p>Note that if the event parameter is <code>null</code>
6639      * the behavior is unspecified and may result in an
6640      * exception.
6641      *
6642      * @param       e the input method event
6643      * @see         java.awt.event.InputMethodEvent
6644      * @see         java.awt.event.InputMethodListener
6645      * @see         #addInputMethodListener
6646      * @see         #enableEvents
6647      * @since       1.2
6648      */
6649     protected void processInputMethodEvent(InputMethodEvent e) {
6650         InputMethodListener listener = inputMethodListener;
6651         if (listener != null) {
6652             int id = e.getID();
6653             switch (id) {
6654               case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6655                   listener.inputMethodTextChanged(e);
6656                   break;
6657               case InputMethodEvent.CARET_POSITION_CHANGED:
6658                   listener.caretPositionChanged(e);
6659                   break;
6660             }
6661         }
6662     }
6663 
6664     /**
6665      * Processes hierarchy events occurring on this component by
6666      * dispatching them to any registered
6667      * <code>HierarchyListener</code> objects.
6668      * <p>
6669      * This method is not called unless hierarchy events
6670      * are enabled for this component. Hierarchy events are enabled
6671      * when one of the following occurs:
6672      * <ul>
6673      * <li>An <code>HierarchyListener</code> object is registered
6674      * via <code>addHierarchyListener</code>.
6675      * <li>Hierarchy events are enabled via <code>enableEvents</code>.
6676      * </ul>
6677      * <p>Note that if the event parameter is <code>null</code>
6678      * the behavior is unspecified and may result in an
6679      * exception.
6680      *
6681      * @param       e the hierarchy event
6682      * @see         java.awt.event.HierarchyEvent
6683      * @see         java.awt.event.HierarchyListener
6684      * @see         #addHierarchyListener
6685      * @see         #enableEvents
6686      * @since       1.3
6687      */
6688     protected void processHierarchyEvent(HierarchyEvent e) {
6689         HierarchyListener listener = hierarchyListener;
6690         if (listener != null) {
6691             int id = e.getID();
6692             switch (id) {
6693               case HierarchyEvent.HIERARCHY_CHANGED:
6694                   listener.hierarchyChanged(e);
6695                   break;
6696             }
6697         }
6698     }
6699 
6700     /**
6701      * Processes hierarchy bounds events occurring on this component by
6702      * dispatching them to any registered
6703      * <code>HierarchyBoundsListener</code> objects.
6704      * <p>
6705      * This method is not called unless hierarchy bounds events
6706      * are enabled for this component. Hierarchy bounds events are enabled
6707      * when one of the following occurs:
6708      * <ul>
6709      * <li>An <code>HierarchyBoundsListener</code> object is registered
6710      * via <code>addHierarchyBoundsListener</code>.
6711      * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>.
6712      * </ul>
6713      * <p>Note that if the event parameter is <code>null</code>
6714      * the behavior is unspecified and may result in an
6715      * exception.
6716      *
6717      * @param       e the hierarchy event
6718      * @see         java.awt.event.HierarchyEvent
6719      * @see         java.awt.event.HierarchyBoundsListener
6720      * @see         #addHierarchyBoundsListener
6721      * @see         #enableEvents
6722      * @since       1.3
6723      */
6724     protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6725         HierarchyBoundsListener listener = hierarchyBoundsListener;
6726         if (listener != null) {
6727             int id = e.getID();
6728             switch (id) {
6729               case HierarchyEvent.ANCESTOR_MOVED:
6730                   listener.ancestorMoved(e);
6731                   break;
6732               case HierarchyEvent.ANCESTOR_RESIZED:
6733                   listener.ancestorResized(e);
6734                   break;
6735             }
6736         }
6737     }
6738 
6739     /**
6740      * @deprecated As of JDK version 1.1
6741      * replaced by processEvent(AWTEvent).
6742      */
6743     @Deprecated
6744     public boolean handleEvent(Event evt) {
6745         switch (evt.id) {
6746           case Event.MOUSE_ENTER:
6747               return mouseEnter(evt, evt.x, evt.y);
6748 
6749           case Event.MOUSE_EXIT:
6750               return mouseExit(evt, evt.x, evt.y);
6751 
6752           case Event.MOUSE_MOVE:
6753               return mouseMove(evt, evt.x, evt.y);
6754 
6755           case Event.MOUSE_DOWN:
6756               return mouseDown(evt, evt.x, evt.y);
6757 
6758           case Event.MOUSE_DRAG:
6759               return mouseDrag(evt, evt.x, evt.y);
6760 
6761           case Event.MOUSE_UP:
6762               return mouseUp(evt, evt.x, evt.y);
6763 
6764           case Event.KEY_PRESS:
6765           case Event.KEY_ACTION:
6766               return keyDown(evt, evt.key);
6767 
6768           case Event.KEY_RELEASE:
6769           case Event.KEY_ACTION_RELEASE:
6770               return keyUp(evt, evt.key);
6771 
6772           case Event.ACTION_EVENT:
6773               return action(evt, evt.arg);
6774           case Event.GOT_FOCUS:
6775               return gotFocus(evt, evt.arg);
6776           case Event.LOST_FOCUS:
6777               return lostFocus(evt, evt.arg);
6778         }
6779         return false;
6780     }
6781 
6782     /**
6783      * @deprecated As of JDK version 1.1,
6784      * replaced by processMouseEvent(MouseEvent).
6785      */
6786     @Deprecated
6787     public boolean mouseDown(Event evt, int x, int y) {
6788         return false;
6789     }
6790 
6791     /**
6792      * @deprecated As of JDK version 1.1,
6793      * replaced by processMouseMotionEvent(MouseEvent).
6794      */
6795     @Deprecated
6796     public boolean mouseDrag(Event evt, int x, int y) {
6797         return false;
6798     }
6799 
6800     /**
6801      * @deprecated As of JDK version 1.1,
6802      * replaced by processMouseEvent(MouseEvent).
6803      */
6804     @Deprecated
6805     public boolean mouseUp(Event evt, int x, int y) {
6806         return false;
6807     }
6808 
6809     /**
6810      * @deprecated As of JDK version 1.1,
6811      * replaced by processMouseMotionEvent(MouseEvent).
6812      */
6813     @Deprecated
6814     public boolean mouseMove(Event evt, int x, int y) {
6815         return false;
6816     }
6817 
6818     /**
6819      * @deprecated As of JDK version 1.1,
6820      * replaced by processMouseEvent(MouseEvent).
6821      */
6822     @Deprecated
6823     public boolean mouseEnter(Event evt, int x, int y) {
6824         return false;
6825     }
6826 
6827     /**
6828      * @deprecated As of JDK version 1.1,
6829      * replaced by processMouseEvent(MouseEvent).
6830      */
6831     @Deprecated
6832     public boolean mouseExit(Event evt, int x, int y) {
6833         return false;
6834     }
6835 
6836     /**
6837      * @deprecated As of JDK version 1.1,
6838      * replaced by processKeyEvent(KeyEvent).
6839      */
6840     @Deprecated
6841     public boolean keyDown(Event evt, int key) {
6842         return false;
6843     }
6844 
6845     /**
6846      * @deprecated As of JDK version 1.1,
6847      * replaced by processKeyEvent(KeyEvent).
6848      */
6849     @Deprecated
6850     public boolean keyUp(Event evt, int key) {
6851         return false;
6852     }
6853 
6854     /**
6855      * @deprecated As of JDK version 1.1,
6856      * should register this component as ActionListener on component
6857      * which fires action events.
6858      */
6859     @Deprecated
6860     public boolean action(Event evt, Object what) {
6861         return false;
6862     }
6863 
6864     /**
6865      * Makes this <code>Component</code> displayable by connecting it to a
6866      * native screen resource.
6867      * This method is called internally by the toolkit and should
6868      * not be called directly by programs.
6869      * <p>
6870      * This method changes layout-related information, and therefore,
6871      * invalidates the component hierarchy.
6872      *
6873      * @see       #isDisplayable
6874      * @see       #removeNotify
6875      * @see #invalidate
6876      * @since JDK1.0
6877      */
6878     public void addNotify() {
6879         synchronized (getTreeLock()) {
6880             ComponentPeer peer = this.peer;
6881             if (peer == null || peer instanceof LightweightPeer){
6882                 if (peer == null) {
6883                     // Update both the Component's peer variable and the local
6884                     // variable we use for thread safety.
6885                     this.peer = peer = getToolkit().createComponent(this);
6886                 }
6887 
6888                 // This is a lightweight component which means it won't be
6889                 // able to get window-related events by itself.  If any
6890                 // have been enabled, then the nearest native container must
6891                 // be enabled.
6892                 if (parent != null) {
6893                     long mask = 0;
6894                     if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) {
6895                         mask |= AWTEvent.MOUSE_EVENT_MASK;
6896                     }
6897                     if ((mouseMotionListener != null) ||
6898                         ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) {
6899                         mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK;
6900                     }
6901                     if ((mouseWheelListener != null ) ||
6902                         ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) {
6903                         mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK;
6904                     }
6905                     if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) {
6906                         mask |= AWTEvent.FOCUS_EVENT_MASK;
6907                     }
6908                     if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) {
6909                         mask |= AWTEvent.KEY_EVENT_MASK;
6910                     }
6911                     if (mask != 0) {
6912                         parent.proxyEnableEvents(mask);
6913                     }
6914                 }
6915             } else {
6916                 // It's native. If the parent is lightweight it will need some
6917                 // help.
6918                 Container parent = getContainer();
6919                 if (parent != null && parent.isLightweight()) {
6920                     relocateComponent();
6921                     if (!parent.isRecursivelyVisibleUpToHeavyweightContainer())
6922                     {
6923                         peer.setVisible(false);
6924                     }
6925                 }
6926             }
6927             invalidate();
6928 
6929             int npopups = (popups != null? popups.size() : 0);
6930             for (int i = 0 ; i < npopups ; i++) {
6931                 PopupMenu popup = popups.elementAt(i);
6932                 popup.addNotify();
6933             }
6934 
6935             if (dropTarget != null) dropTarget.addNotify(peer);
6936 
6937             peerFont = getFont();
6938 
6939             if (getContainer() != null && !isAddNotifyComplete) {
6940                 getContainer().increaseComponentCount(this);
6941             }
6942 
6943 
6944             // Update stacking order
6945             updateZOrder();
6946 
6947             if (!isAddNotifyComplete) {
6948                 mixOnShowing();
6949             }
6950 
6951             isAddNotifyComplete = true;
6952 
6953             if (hierarchyListener != null ||
6954                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
6955                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
6956                 HierarchyEvent e =
6957                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
6958                                        this, parent,
6959                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
6960                                        ((isRecursivelyVisible())
6961                                         ? HierarchyEvent.SHOWING_CHANGED
6962                                         : 0));
6963                 dispatchEvent(e);
6964             }
6965         }
6966     }
6967 
6968     /**
6969      * Makes this <code>Component</code> undisplayable by destroying it native
6970      * screen resource.
6971      * <p>
6972      * This method is called by the toolkit internally and should
6973      * not be called directly by programs. Code overriding
6974      * this method should call <code>super.removeNotify</code> as
6975      * the first line of the overriding method.
6976      *
6977      * @see       #isDisplayable
6978      * @see       #addNotify
6979      * @since JDK1.0
6980      */
6981     public void removeNotify() {
6982         KeyboardFocusManager.clearMostRecentFocusOwner(this);
6983         if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
6984             getPermanentFocusOwner() == this)
6985         {
6986             KeyboardFocusManager.getCurrentKeyboardFocusManager().
6987                 setGlobalPermanentFocusOwner(null);
6988         }
6989 
6990         synchronized (getTreeLock()) {
6991             clearLightweightDispatcherOnRemove(this);
6992 
6993             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
6994                 transferFocus(true);
6995             }
6996 
6997             if (getContainer() != null && isAddNotifyComplete) {
6998                 getContainer().decreaseComponentCount(this);
6999             }
7000 
7001             int npopups = (popups != null? popups.size() : 0);
7002             for (int i = 0 ; i < npopups ; i++) {
7003                 PopupMenu popup = popups.elementAt(i);
7004                 popup.removeNotify();
7005             }
7006             // If there is any input context for this component, notify
7007             // that this component is being removed. (This has to be done
7008             // before hiding peer.)
7009             if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
7010                 InputContext inputContext = getInputContext();
7011                 if (inputContext != null) {
7012                     inputContext.removeNotify(this);
7013                 }
7014             }
7015 
7016             ComponentPeer p = peer;
7017             if (p != null) {
7018                 boolean isLightweight = isLightweight();
7019 
7020                 if (bufferStrategy instanceof FlipBufferStrategy) {
7021                     ((FlipBufferStrategy)bufferStrategy).destroyBuffers();
7022                 }
7023 
7024                 if (dropTarget != null) dropTarget.removeNotify(peer);
7025 
7026                 // Hide peer first to stop system events such as cursor moves.
7027                 if (visible) {
7028                     p.setVisible(false);
7029                 }
7030 
7031                 peer = null; // Stop peer updates.
7032                 peerFont = null;
7033 
7034                 Toolkit.getEventQueue().removeSourceEvents(this, false);
7035                 KeyboardFocusManager.getCurrentKeyboardFocusManager().
7036                     discardKeyEvents(this);
7037 
7038                 p.dispose();
7039 
7040                 mixOnHiding(isLightweight);
7041 
7042                 isAddNotifyComplete = false;
7043                 // Nullifying compoundShape means that the component has normal shape
7044                 // (or has no shape at all).
7045                 this.compoundShape = null;
7046             }
7047 
7048             if (hierarchyListener != null ||
7049                 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7050                 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7051                 HierarchyEvent e =
7052                     new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7053                                        this, parent,
7054                                        HierarchyEvent.DISPLAYABILITY_CHANGED |
7055                                        ((isRecursivelyVisible())
7056                                         ? HierarchyEvent.SHOWING_CHANGED
7057                                         : 0));
7058                 dispatchEvent(e);
7059             }
7060         }
7061     }
7062 
7063     /**
7064      * @deprecated As of JDK version 1.1,
7065      * replaced by processFocusEvent(FocusEvent).
7066      */
7067     @Deprecated
7068     public boolean gotFocus(Event evt, Object what) {
7069         return false;
7070     }
7071 
7072     /**
7073      * @deprecated As of JDK version 1.1,
7074      * replaced by processFocusEvent(FocusEvent).
7075      */
7076     @Deprecated
7077     public boolean lostFocus(Event evt, Object what) {
7078         return false;
7079     }
7080 
7081     /**
7082      * Returns whether this <code>Component</code> can become the focus
7083      * owner.
7084      *
7085      * @return <code>true</code> if this <code>Component</code> is
7086      * focusable; <code>false</code> otherwise
7087      * @see #setFocusable
7088      * @since JDK1.1
7089      * @deprecated As of 1.4, replaced by <code>isFocusable()</code>.
7090      */
7091     @Deprecated
7092     public boolean isFocusTraversable() {
7093         if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
7094             isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
7095         }
7096         return focusable;
7097     }
7098 
7099     /**
7100      * Returns whether this Component can be focused.
7101      *
7102      * @return <code>true</code> if this Component is focusable;
7103      *         <code>false</code> otherwise.
7104      * @see #setFocusable
7105      * @since 1.4
7106      */
7107     public boolean isFocusable() {
7108         return isFocusTraversable();
7109     }
7110 
7111     /**
7112      * Sets the focusable state of this Component to the specified value. This
7113      * value overrides the Component's default focusability.
7114      *
7115      * @param focusable indicates whether this Component is focusable
7116      * @see #isFocusable
7117      * @since 1.4
7118      * @beaninfo
7119      *       bound: true
7120      */
7121     public void setFocusable(boolean focusable) {
7122         boolean oldFocusable;
7123         synchronized (this) {
7124             oldFocusable = this.focusable;
7125             this.focusable = focusable;
7126         }
7127         isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET;
7128 
7129         firePropertyChange("focusable", oldFocusable, focusable);
7130         if (oldFocusable && !focusable) {
7131             if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
7132                 transferFocus(true);
7133             }
7134             KeyboardFocusManager.clearMostRecentFocusOwner(this);
7135         }
7136     }
7137 
7138     final boolean isFocusTraversableOverridden() {
7139         return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT);
7140     }
7141 
7142     /**
7143      * Sets the focus traversal keys for a given traversal operation for this
7144      * Component.
7145      * <p>
7146      * The default values for a Component's focus traversal keys are
7147      * implementation-dependent. Sun recommends that all implementations for a
7148      * particular native platform use the same default values. The
7149      * recommendations for Windows and Unix are listed below. These
7150      * recommendations are used in the Sun AWT implementations.
7151      *
7152      * <table border=1 summary="Recommended default values for a Component's focus traversal keys">
7153      * <tr>
7154      *    <th>Identifier</th>
7155      *    <th>Meaning</th>
7156      *    <th>Default</th>
7157      * </tr>
7158      * <tr>
7159      *    <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>
7160      *    <td>Normal forward keyboard traversal</td>
7161      *    <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>
7162      * </tr>
7163      * <tr>
7164      *    <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>
7165      *    <td>Normal reverse keyboard traversal</td>
7166      *    <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>
7167      * </tr>
7168      * <tr>
7169      *    <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>
7170      *    <td>Go up one focus traversal cycle</td>
7171      *    <td>none</td>
7172      * </tr>
7173      * </table>
7174      *
7175      * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is
7176      * recommended.
7177      * <p>
7178      * Using the AWTKeyStroke API, client code can specify on which of two
7179      * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal
7180      * operation will occur. Regardless of which KeyEvent is specified,
7181      * however, all KeyEvents related to the focus traversal key, including the
7182      * associated KEY_TYPED event, will be consumed, and will not be dispatched
7183      * to any Component. It is a runtime error to specify a KEY_TYPED event as
7184      * mapping to a focus traversal operation, or to map the same event to
7185      * multiple default focus traversal operations.
7186      * <p>
7187      * If a value of null is specified for the Set, this Component inherits the
7188      * Set from its parent. If all ancestors of this Component have null
7189      * specified for the Set, then the current KeyboardFocusManager's default
7190      * Set is used.
7191      * <p>
7192      * This method may throw a {@code ClassCastException} if any {@code Object}
7193      * in {@code keystrokes} is not an {@code AWTKeyStroke}.
7194      *
7195      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7196      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7197      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7198      * @param keystrokes the Set of AWTKeyStroke for the specified operation
7199      * @see #getFocusTraversalKeys
7200      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7201      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7202      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7203      * @throws IllegalArgumentException if id is not one of
7204      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7205      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7206      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes
7207      *         contains null, or if any keystroke represents a KEY_TYPED event,
7208      *         or if any keystroke already maps to another focus traversal
7209      *         operation for this Component
7210      * @since 1.4
7211      * @beaninfo
7212      *       bound: true
7213      */
7214     public void setFocusTraversalKeys(int id,
7215                                       Set<? extends AWTKeyStroke> keystrokes)
7216     {
7217         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7218             throw new IllegalArgumentException("invalid focus traversal key identifier");
7219         }
7220 
7221         setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7222     }
7223 
7224     /**
7225      * Returns the Set of focus traversal keys for a given traversal operation
7226      * for this Component. (See
7227      * <code>setFocusTraversalKeys</code> for a full description of each key.)
7228      * <p>
7229      * If a Set of traversal keys has not been explicitly defined for this
7230      * Component, then this Component's parent's Set is returned. If no Set
7231      * has been explicitly defined for any of this Component's ancestors, then
7232      * the current KeyboardFocusManager's default Set is returned.
7233      *
7234      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7235      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7236      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7237      * @return the Set of AWTKeyStrokes for the specified operation. The Set
7238      *         will be unmodifiable, and may be empty. null will never be
7239      *         returned.
7240      * @see #setFocusTraversalKeys
7241      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7242      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7243      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7244      * @throws IllegalArgumentException if id is not one of
7245      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7246      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7247      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7248      * @since 1.4
7249      */
7250     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
7251         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7252             throw new IllegalArgumentException("invalid focus traversal key identifier");
7253         }
7254 
7255         return getFocusTraversalKeys_NoIDCheck(id);
7256     }
7257 
7258     // We define these methods so that Container does not need to repeat this
7259     // code. Container cannot call super.<method> because Container allows
7260     // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method
7261     // would erroneously generate an IllegalArgumentException for
7262     // DOWN_CYCLE_TRAVERSAL_KEY.
7263     final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) {
7264         Set<AWTKeyStroke> oldKeys;
7265 
7266         synchronized (this) {
7267             if (focusTraversalKeys == null) {
7268                 initializeFocusTraversalKeys();
7269             }
7270 
7271             if (keystrokes != null) {
7272                 for (AWTKeyStroke keystroke : keystrokes ) {
7273 
7274                     if (keystroke == null) {
7275                         throw new IllegalArgumentException("cannot set null focus traversal key");
7276                     }
7277 
7278                     if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {
7279                         throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");
7280                     }
7281 
7282                     for (int i = 0; i < focusTraversalKeys.length; i++) {
7283                         if (i == id) {
7284                             continue;
7285                         }
7286 
7287                         if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke))
7288                         {
7289                             throw new IllegalArgumentException("focus traversal keys must be unique for a Component");
7290                         }
7291                     }
7292                 }
7293             }
7294 
7295             oldKeys = focusTraversalKeys[id];
7296             focusTraversalKeys[id] = (keystrokes != null)
7297                 ? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes))
7298                 : null;
7299         }
7300 
7301         firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys,
7302                            keystrokes);
7303     }
7304     final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) {
7305         // Okay to return Set directly because it is an unmodifiable view
7306         @SuppressWarnings("unchecked")
7307         Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)
7308             ? focusTraversalKeys[id]
7309             : null;
7310 
7311         if (keystrokes != null) {
7312             return keystrokes;
7313         } else {
7314             Container parent = this.parent;
7315             if (parent != null) {
7316                 return parent.getFocusTraversalKeys(id);
7317             } else {
7318                 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7319                     getDefaultFocusTraversalKeys(id);
7320             }
7321         }
7322     }
7323 
7324     /**
7325      * Returns whether the Set of focus traversal keys for the given focus
7326      * traversal operation has been explicitly defined for this Component. If
7327      * this method returns <code>false</code>, this Component is inheriting the
7328      * Set from an ancestor, or from the current KeyboardFocusManager.
7329      *
7330      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7331      *        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7332      *        KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7333      * @return <code>true</code> if the the Set of focus traversal keys for the
7334      *         given focus traversal operation has been explicitly defined for
7335      *         this Component; <code>false</code> otherwise.
7336      * @throws IllegalArgumentException if id is not one of
7337      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7338      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7339      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7340      * @since 1.4
7341      */
7342     public boolean areFocusTraversalKeysSet(int id) {
7343         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7344             throw new IllegalArgumentException("invalid focus traversal key identifier");
7345         }
7346 
7347         return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7348     }
7349 
7350     /**
7351      * Sets whether focus traversal keys are enabled for this Component.
7352      * Components for which focus traversal keys are disabled receive key
7353      * events for focus traversal keys. Components for which focus traversal
7354      * keys are enabled do not see these events; instead, the events are
7355      * automatically converted to traversal operations.
7356      *
7357      * @param focusTraversalKeysEnabled whether focus traversal keys are
7358      *        enabled for this Component
7359      * @see #getFocusTraversalKeysEnabled
7360      * @see #setFocusTraversalKeys
7361      * @see #getFocusTraversalKeys
7362      * @since 1.4
7363      * @beaninfo
7364      *       bound: true
7365      */
7366     public void setFocusTraversalKeysEnabled(boolean
7367                                              focusTraversalKeysEnabled) {
7368         boolean oldFocusTraversalKeysEnabled;
7369         synchronized (this) {
7370             oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled;
7371             this.focusTraversalKeysEnabled = focusTraversalKeysEnabled;
7372         }
7373         firePropertyChange("focusTraversalKeysEnabled",
7374                            oldFocusTraversalKeysEnabled,
7375                            focusTraversalKeysEnabled);
7376     }
7377 
7378     /**
7379      * Returns whether focus traversal keys are enabled for this Component.
7380      * Components for which focus traversal keys are disabled receive key
7381      * events for focus traversal keys. Components for which focus traversal
7382      * keys are enabled do not see these events; instead, the events are
7383      * automatically converted to traversal operations.
7384      *
7385      * @return whether focus traversal keys are enabled for this Component
7386      * @see #setFocusTraversalKeysEnabled
7387      * @see #setFocusTraversalKeys
7388      * @see #getFocusTraversalKeys
7389      * @since 1.4
7390      */
7391     public boolean getFocusTraversalKeysEnabled() {
7392         return focusTraversalKeysEnabled;
7393     }
7394 
7395     /**
7396      * Requests that this Component get the input focus, and that this
7397      * Component's top-level ancestor become the focused Window. This
7398      * component must be displayable, focusable, visible and all of
7399      * its ancestors (with the exception of the top-level Window) must
7400      * be visible for the request to be granted. Every effort will be
7401      * made to honor the request; however, in some cases it may be
7402      * impossible to do so. Developers must never assume that this
7403      * Component is the focus owner until this Component receives a
7404      * FOCUS_GAINED event. If this request is denied because this
7405      * Component's top-level Window cannot become the focused Window,
7406      * the request will be remembered and will be granted when the
7407      * Window is later focused by the user.
7408      * <p>
7409      * This method cannot be used to set the focus owner to no Component at
7410      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7411      * instead.
7412      * <p>
7413      * Because the focus behavior of this method is platform-dependent,
7414      * developers are strongly encouraged to use
7415      * <code>requestFocusInWindow</code> when possible.
7416      *
7417      * <p>Note: Not all focus transfers result from invoking this method. As
7418      * such, a component may receive focus without this or any of the other
7419      * {@code requestFocus} methods of {@code Component} being invoked.
7420      *
7421      * @see #requestFocusInWindow
7422      * @see java.awt.event.FocusEvent
7423      * @see #addFocusListener
7424      * @see #isFocusable
7425      * @see #isDisplayable
7426      * @see KeyboardFocusManager#clearGlobalFocusOwner
7427      * @since JDK1.0
7428      */
7429     public void requestFocus() {
7430         requestFocusHelper(false, true);
7431     }
7432 
7433     boolean requestFocus(CausedFocusEvent.Cause cause) {
7434         return requestFocusHelper(false, true, cause);
7435     }
7436 
7437     /**
7438      * Requests that this <code>Component</code> get the input focus,
7439      * and that this <code>Component</code>'s top-level ancestor
7440      * become the focused <code>Window</code>. This component must be
7441      * displayable, focusable, visible and all of its ancestors (with
7442      * the exception of the top-level Window) must be visible for the
7443      * request to be granted. Every effort will be made to honor the
7444      * request; however, in some cases it may be impossible to do
7445      * so. Developers must never assume that this component is the
7446      * focus owner until this component receives a FOCUS_GAINED
7447      * event. If this request is denied because this component's
7448      * top-level window cannot become the focused window, the request
7449      * will be remembered and will be granted when the window is later
7450      * focused by the user.
7451      * <p>
7452      * This method returns a boolean value. If <code>false</code> is returned,
7453      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7454      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7455      * extraordinary event, such as disposal of the component's peer, occurs
7456      * before the request can be granted by the native windowing system. Again,
7457      * while a return value of <code>true</code> indicates that the request is
7458      * likely to succeed, developers must never assume that this component is
7459      * the focus owner until this component receives a FOCUS_GAINED event.
7460      * <p>
7461      * This method cannot be used to set the focus owner to no component at
7462      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7463      * instead.
7464      * <p>
7465      * Because the focus behavior of this method is platform-dependent,
7466      * developers are strongly encouraged to use
7467      * <code>requestFocusInWindow</code> when possible.
7468      * <p>
7469      * Every effort will be made to ensure that <code>FocusEvent</code>s
7470      * generated as a
7471      * result of this request will have the specified temporary value. However,
7472      * because specifying an arbitrary temporary state may not be implementable
7473      * on all native windowing systems, correct behavior for this method can be
7474      * guaranteed only for lightweight <code>Component</code>s.
7475      * This method is not intended
7476      * for general use, but exists instead as a hook for lightweight component
7477      * libraries, such as Swing.
7478      *
7479      * <p>Note: Not all focus transfers result from invoking this method. As
7480      * such, a component may receive focus without this or any of the other
7481      * {@code requestFocus} methods of {@code Component} being invoked.
7482      *
7483      * @param temporary true if the focus change is temporary,
7484      *        such as when the window loses the focus; for
7485      *        more information on temporary focus changes see the
7486      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7487      * @return <code>false</code> if the focus change request is guaranteed to
7488      *         fail; <code>true</code> if it is likely to succeed
7489      * @see java.awt.event.FocusEvent
7490      * @see #addFocusListener
7491      * @see #isFocusable
7492      * @see #isDisplayable
7493      * @see KeyboardFocusManager#clearGlobalFocusOwner
7494      * @since 1.4
7495      */
7496     protected boolean requestFocus(boolean temporary) {
7497         return requestFocusHelper(temporary, true);
7498     }
7499 
7500     boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {
7501         return requestFocusHelper(temporary, true, cause);
7502     }
7503     /**
7504      * Requests that this Component get the input focus, if this
7505      * Component's top-level ancestor is already the focused
7506      * Window. This component must be displayable, focusable, visible
7507      * and all of its ancestors (with the exception of the top-level
7508      * Window) must be visible for the request to be granted. Every
7509      * effort will be made to honor the request; however, in some
7510      * cases it may be impossible to do so. Developers must never
7511      * assume that this Component is the focus owner until this
7512      * Component receives a FOCUS_GAINED event.
7513      * <p>
7514      * This method returns a boolean value. If <code>false</code> is returned,
7515      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7516      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7517      * extraordinary event, such as disposal of the Component's peer, occurs
7518      * before the request can be granted by the native windowing system. Again,
7519      * while a return value of <code>true</code> indicates that the request is
7520      * likely to succeed, developers must never assume that this Component is
7521      * the focus owner until this Component receives a FOCUS_GAINED event.
7522      * <p>
7523      * This method cannot be used to set the focus owner to no Component at
7524      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7525      * instead.
7526      * <p>
7527      * The focus behavior of this method can be implemented uniformly across
7528      * platforms, and thus developers are strongly encouraged to use this
7529      * method over <code>requestFocus</code> when possible. Code which relies
7530      * on <code>requestFocus</code> may exhibit different focus behavior on
7531      * different platforms.
7532      *
7533      * <p>Note: Not all focus transfers result from invoking this method. As
7534      * such, a component may receive focus without this or any of the other
7535      * {@code requestFocus} methods of {@code Component} being invoked.
7536      *
7537      * @return <code>false</code> if the focus change request is guaranteed to
7538      *         fail; <code>true</code> if it is likely to succeed
7539      * @see #requestFocus
7540      * @see java.awt.event.FocusEvent
7541      * @see #addFocusListener
7542      * @see #isFocusable
7543      * @see #isDisplayable
7544      * @see KeyboardFocusManager#clearGlobalFocusOwner
7545      * @since 1.4
7546      */
7547     public boolean requestFocusInWindow() {
7548         return requestFocusHelper(false, false);
7549     }
7550 
7551     boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {
7552         return requestFocusHelper(false, false, cause);
7553     }
7554 
7555     /**
7556      * Requests that this <code>Component</code> get the input focus,
7557      * if this <code>Component</code>'s top-level ancestor is already
7558      * the focused <code>Window</code>.  This component must be
7559      * displayable, focusable, visible and all of its ancestors (with
7560      * the exception of the top-level Window) must be visible for the
7561      * request to be granted. Every effort will be made to honor the
7562      * request; however, in some cases it may be impossible to do
7563      * so. Developers must never assume that this component is the
7564      * focus owner until this component receives a FOCUS_GAINED event.
7565      * <p>
7566      * This method returns a boolean value. If <code>false</code> is returned,
7567      * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7568      * returned, the request will succeed <b>unless</b> it is vetoed, or an
7569      * extraordinary event, such as disposal of the component's peer, occurs
7570      * before the request can be granted by the native windowing system. Again,
7571      * while a return value of <code>true</code> indicates that the request is
7572      * likely to succeed, developers must never assume that this component is
7573      * the focus owner until this component receives a FOCUS_GAINED event.
7574      * <p>
7575      * This method cannot be used to set the focus owner to no component at
7576      * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7577      * instead.
7578      * <p>
7579      * The focus behavior of this method can be implemented uniformly across
7580      * platforms, and thus developers are strongly encouraged to use this
7581      * method over <code>requestFocus</code> when possible. Code which relies
7582      * on <code>requestFocus</code> may exhibit different focus behavior on
7583      * different platforms.
7584      * <p>
7585      * Every effort will be made to ensure that <code>FocusEvent</code>s
7586      * generated as a
7587      * result of this request will have the specified temporary value. However,
7588      * because specifying an arbitrary temporary state may not be implementable
7589      * on all native windowing systems, correct behavior for this method can be
7590      * guaranteed only for lightweight components. This method is not intended
7591      * for general use, but exists instead as a hook for lightweight component
7592      * libraries, such as Swing.
7593      *
7594      * <p>Note: Not all focus transfers result from invoking this method. As
7595      * such, a component may receive focus without this or any of the other
7596      * {@code requestFocus} methods of {@code Component} being invoked.
7597      *
7598      * @param temporary true if the focus change is temporary,
7599      *        such as when the window loses the focus; for
7600      *        more information on temporary focus changes see the
7601      *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7602      * @return <code>false</code> if the focus change request is guaranteed to
7603      *         fail; <code>true</code> if it is likely to succeed
7604      * @see #requestFocus
7605      * @see java.awt.event.FocusEvent
7606      * @see #addFocusListener
7607      * @see #isFocusable
7608      * @see #isDisplayable
7609      * @see KeyboardFocusManager#clearGlobalFocusOwner
7610      * @since 1.4
7611      */
7612     protected boolean requestFocusInWindow(boolean temporary) {
7613         return requestFocusHelper(temporary, false);
7614     }
7615 
7616     boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {
7617         return requestFocusHelper(temporary, false, cause);
7618     }
7619 
7620     final boolean requestFocusHelper(boolean temporary,
7621                                      boolean focusedWindowChangeAllowed) {
7622         return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);
7623     }
7624 
7625     final boolean requestFocusHelper(boolean temporary,
7626                                      boolean focusedWindowChangeAllowed,
7627                                      CausedFocusEvent.Cause cause)
7628     {
7629         // 1) Check if the event being dispatched is a system-generated mouse event.
7630         AWTEvent currentEvent = EventQueue.getCurrentEvent();
7631         if (currentEvent instanceof MouseEvent &&
7632             SunToolkit.isSystemGenerated(currentEvent))
7633         {
7634             // 2) Sanity check: if the mouse event component source belongs to the same containing window.
7635             Component source = ((MouseEvent)currentEvent).getComponent();
7636             if (source == null || source.getContainingWindow() == getContainingWindow()) {
7637                 focusLog.finest("requesting focus by mouse event \"in window\"");
7638 
7639                 // If both the conditions are fulfilled the focus request should be strictly
7640                 // bounded by the toplevel window. It's assumed that the mouse event activates
7641                 // the window (if it wasn't active) and this makes it possible for a focus
7642                 // request with a strong in-window requirement to change focus in the bounds
7643                 // of the toplevel. If, by any means, due to asynchronous nature of the event
7644                 // dispatching mechanism, the window happens to be natively inactive by the time
7645                 // this focus request is eventually handled, it should not re-activate the
7646                 // toplevel. Otherwise the result may not meet user expectations. See 6981400.
7647                 focusedWindowChangeAllowed = false;
7648             }
7649         }
7650         if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {
7651             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7652                 focusLog.finest("requestFocus is not accepted");
7653             }
7654             return false;
7655         }
7656         // Update most-recent map
7657         KeyboardFocusManager.setMostRecentFocusOwner(this);
7658 
7659         Component window = this;
7660         while ( (window != null) && !(window instanceof Window)) {
7661             if (!window.isVisible()) {
7662                 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7663                     focusLog.finest("component is recurively invisible");
7664                 }
7665                 return false;
7666             }
7667             window = window.parent;
7668         }
7669 
7670         ComponentPeer peer = this.peer;
7671         Component heavyweight = (peer instanceof LightweightPeer)
7672             ? getNativeContainer() : this;
7673         if (heavyweight == null || !heavyweight.isVisible()) {
7674             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7675                 focusLog.finest("Component is not a part of visible hierarchy");
7676             }
7677             return false;
7678         }
7679         peer = heavyweight.peer;
7680         if (peer == null) {
7681             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7682                 focusLog.finest("Peer is null");
7683             }
7684             return false;
7685         }
7686 
7687         // Focus this Component
7688         long time = 0;
7689         if (EventQueue.isDispatchThread()) {
7690             time = Toolkit.getEventQueue().getMostRecentKeyEventTime();
7691         } else {
7692             // A focus request made from outside EDT should not be associated with any event
7693             // and so its time stamp is simply set to the current time.
7694             time = System.currentTimeMillis();
7695         }
7696 
7697         boolean success = peer.requestFocus
7698             (this, temporary, focusedWindowChangeAllowed, time, cause);
7699         if (!success) {
7700             KeyboardFocusManager.getCurrentKeyboardFocusManager
7701                 (appContext).dequeueKeyEvents(time, this);
7702             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7703                 focusLog.finest("Peer request failed");
7704             }
7705         } else {
7706             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7707                 focusLog.finest("Pass for " + this);
7708             }
7709         }
7710         return success;
7711     }
7712 
7713     private boolean isRequestFocusAccepted(boolean temporary,
7714                                            boolean focusedWindowChangeAllowed,
7715                                            CausedFocusEvent.Cause cause)
7716     {
7717         if (!isFocusable() || !isVisible()) {
7718             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7719                 focusLog.finest("Not focusable or not visible");
7720             }
7721             return false;
7722         }
7723 
7724         ComponentPeer peer = this.peer;
7725         if (peer == null) {
7726             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7727                 focusLog.finest("peer is null");
7728             }
7729             return false;
7730         }
7731 
7732         Window window = getContainingWindow();
7733         if (window == null || !window.isFocusableWindow()) {
7734             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7735                 focusLog.finest("Component doesn't have toplevel");
7736             }
7737             return false;
7738         }
7739 
7740         // We have passed all regular checks for focus request,
7741         // now let's call RequestFocusController and see what it says.
7742         Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window);
7743         if (focusOwner == null) {
7744             // sometimes most recent focus owner may be null, but focus owner is not
7745             // e.g. we reset most recent focus owner if user removes focus owner
7746             focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
7747             if (focusOwner != null && focusOwner.getContainingWindow() != window) {
7748                 focusOwner = null;
7749             }
7750         }
7751 
7752         if (focusOwner == this || focusOwner == null) {
7753             // Controller is supposed to verify focus transfers and for this it
7754             // should know both from and to components.  And it shouldn't verify
7755             // transfers from when these components are equal.
7756             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7757                 focusLog.finest("focus owner is null or this");
7758             }
7759             return true;
7760         }
7761 
7762         if (CausedFocusEvent.Cause.ACTIVATION == cause) {
7763             // we shouldn't call RequestFocusController in case we are
7764             // in activation.  We do request focus on component which
7765             // has got temporary focus lost and then on component which is
7766             // most recent focus owner.  But most recent focus owner can be
7767             // changed by requestFocsuXXX() call only, so this transfer has
7768             // been already approved.
7769             if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7770                 focusLog.finest("cause is activation");
7771             }
7772             return true;
7773         }
7774 
7775         boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner,
7776                                                                           this,
7777                                                                           temporary,
7778                                                                           focusedWindowChangeAllowed,
7779                                                                           cause);
7780         if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {
7781             focusLog.finest("RequestFocusController returns {0}", ret);
7782         }
7783 
7784         return ret;
7785     }
7786 
7787     private static RequestFocusController requestFocusController = new DummyRequestFocu