1 /*
   2  * Copyright (c) 1995, 2019, 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 
  26 package java.awt;
  27 
  28 import java.awt.event.ComponentEvent;
  29 import java.awt.event.FocusEvent;
  30 import java.awt.event.KeyEvent;
  31 import java.awt.event.MouseWheelEvent;
  32 import java.awt.event.WindowEvent;
  33 import java.awt.event.WindowFocusListener;
  34 import java.awt.event.WindowListener;
  35 import java.awt.event.WindowStateListener;
  36 import java.awt.geom.Path2D;
  37 import java.awt.geom.Point2D;
  38 import java.awt.im.InputContext;
  39 import java.awt.image.BufferStrategy;
  40 import java.awt.peer.ComponentPeer;
  41 import java.awt.peer.WindowPeer;
  42 import java.beans.PropertyChangeListener;
  43 import java.io.IOException;
  44 import java.io.ObjectInputStream;
  45 import java.io.ObjectOutputStream;
  46 import java.io.OptionalDataException;
  47 import java.io.Serializable;
  48 import java.lang.ref.WeakReference;
  49 import java.lang.reflect.InvocationTargetException;
  50 import java.security.AccessController;
  51 import java.util.ArrayList;
  52 import java.util.Arrays;
  53 import java.util.EventListener;
  54 import java.util.Locale;
  55 import java.util.ResourceBundle;
  56 import java.util.Set;
  57 import java.util.Vector;
  58 import java.util.concurrent.atomic.AtomicBoolean;
  59 
  60 import javax.accessibility.Accessible;
  61 import javax.accessibility.AccessibleContext;
  62 import javax.accessibility.AccessibleRole;
  63 import javax.accessibility.AccessibleState;
  64 import javax.accessibility.AccessibleStateSet;
  65 
  66 import sun.awt.AWTAccessor;
  67 import sun.awt.AWTPermissions;
  68 import sun.awt.AppContext;
  69 import sun.awt.DebugSettings;
  70 import sun.awt.SunToolkit;
  71 import sun.awt.util.IdentityArrayList;
  72 import sun.java2d.pipe.Region;
  73 import sun.security.action.GetPropertyAction;
  74 import sun.util.logging.PlatformLogger;
  75 
  76 /**
  77  * A {@code Window} object is a top-level window with no borders and no
  78  * menubar.
  79  * The default layout for a window is {@code BorderLayout}.
  80  * <p>
  81  * A window must have either a frame, dialog, or another window defined as its
  82  * owner when it's constructed.
  83  * <p>
  84  * In a multi-screen environment, you can create a {@code Window}
  85  * on a different screen device by constructing the {@code Window}
  86  * with {@link #Window(Window, GraphicsConfiguration)}.  The
  87  * {@code GraphicsConfiguration} object is one of the
  88  * {@code GraphicsConfiguration} objects of the target screen device.
  89  * <p>
  90  * In a virtual device multi-screen environment in which the desktop
  91  * area could span multiple physical screen devices, the bounds of all
  92  * configurations are relative to the virtual device coordinate system.
  93  * The origin of the virtual-coordinate system is at the upper left-hand
  94  * corner of the primary physical screen.  Depending on the location of
  95  * the primary screen in the virtual device, negative coordinates are
  96  * possible, as shown in the following figure.
  97  * <p>
  98  * <img src="doc-files/MultiScreen.gif"
  99  * alt="Diagram shows virtual device containing 4 physical screens. Primary
 100  * physical screen shows coords (0,0), other screen shows (-80,-100)."
 101  * style="margin: 7px 10px;">
 102  * <p>
 103  * In such an environment, when calling {@code setLocation},
 104  * you must pass a virtual coordinate to this method.  Similarly,
 105  * calling {@code getLocationOnScreen} on a {@code Window} returns
 106  * virtual device coordinates.  Call the {@code getBounds} method
 107  * of a {@code GraphicsConfiguration} to find its origin in the virtual
 108  * coordinate system.
 109  * <p>
 110  * The following code sets the location of a {@code Window}
 111  * at (10, 10) relative to the origin of the physical screen
 112  * of the corresponding {@code GraphicsConfiguration}.  If the
 113  * bounds of the {@code GraphicsConfiguration} is not taken
 114  * into account, the {@code Window} location would be set
 115  * at (10, 10) relative to the virtual-coordinate system and would appear
 116  * on the primary physical screen, which might be different from the
 117  * physical screen of the specified {@code GraphicsConfiguration}.
 118  *
 119  * <pre>
 120  *      Window w = new Window(Window owner, GraphicsConfiguration gc);
 121  *      Rectangle bounds = gc.getBounds();
 122  *      w.setLocation(10 + bounds.x, 10 + bounds.y);
 123  * </pre>
 124  *
 125  * <p>
 126  * Note: the location and size of top-level windows (including
 127  * {@code Window}s, {@code Frame}s, and {@code Dialog}s)
 128  * are under the control of the desktop's window management system.
 129  * Calls to {@code setLocation}, {@code setSize}, and
 130  * {@code setBounds} are requests (not directives) which are
 131  * forwarded to the window management system.  Every effort will be
 132  * made to honor such requests.  However, in some cases the window
 133  * management system may ignore such requests, or modify the requested
 134  * geometry in order to place and size the {@code Window} in a way
 135  * that more closely matches the desktop settings.
 136  * <p>
 137  * The visual appearance and behavior of top-level windows (including
 138  * normal/shaped/translucent/undecorated {@code Window}s, {@code Frame}s,
 139  * {@code Dialog}s) are under the control of the desktop's window management
 140  * system. The visual effects as shadows, motion effects, animations,
 141  * and others may not be controlled by the applications but work according to
 142  * the desktop settings.
 143  * <p>
 144  * Due to the asynchronous nature of native event handling, the results
 145  * returned by {@code getBounds}, {@code getLocation},
 146  * {@code getLocationOnScreen}, and {@code getSize} might not
 147  * reflect the actual geometry of the Window on screen until the last
 148  * request has been processed.  During the processing of subsequent
 149  * requests these values might change accordingly while the window
 150  * management system fulfills the requests.
 151  * <p>
 152  * An application may set the size and location of an invisible
 153  * {@code Window} arbitrarily, but the window management system may
 154  * subsequently change its size and/or location when the
 155  * {@code Window} is made visible. One or more {@code ComponentEvent}s
 156  * will be generated to indicate the new geometry.
 157  * <p>
 158  * Windows are capable of generating the following WindowEvents:
 159  * WindowOpened, WindowClosed, WindowGainedFocus, WindowLostFocus.
 160  *
 161  * @author      Sami Shaio
 162  * @author      Arthur van Hoff
 163  * @see WindowEvent
 164  * @see #addWindowListener
 165  * @see java.awt.BorderLayout
 166  * @since       1.0
 167  */
 168 public class Window extends Container implements Accessible {
 169 
 170     /**
 171      * Enumeration of available <i>window types</i>.
 172      *
 173      * A window type defines the generic visual appearance and behavior of a
 174      * top-level window. For example, the type may affect the kind of
 175      * decorations of a decorated {@code Frame} or {@code Dialog} instance.
 176      * <p>
 177      * Some platforms may not fully support a certain window type. Depending on
 178      * the level of support, some properties of the window type may be
 179      * disobeyed.
 180      *
 181      * @see   #getType
 182      * @see   #setType
 183      * @since 1.7
 184      */
 185     public static enum Type {
 186         /**
 187          * Represents a <i>normal</i> window.
 188          *
 189          * This is the default type for objects of the {@code Window} class or
 190          * its descendants. Use this type for regular top-level windows.
 191          */
 192         NORMAL,
 193 
 194         /**
 195          * Represents a <i>utility</i> window.
 196          *
 197          * A utility window is usually a small window such as a toolbar or a
 198          * palette. The native system may render the window with smaller
 199          * title-bar if the window is either a {@code Frame} or a {@code
 200          * Dialog} object, and if it has its decorations enabled.
 201          */
 202         UTILITY,
 203 
 204         /**
 205          * Represents a <i>popup</i> window.
 206          *
 207          * A popup window is a temporary window such as a drop-down menu or a
 208          * tooltip. On some platforms, windows of that type may be forcibly
 209          * made undecorated even if they are instances of the {@code Frame} or
 210          * {@code Dialog} class, and have decorations enabled.
 211          */
 212         POPUP
 213     }
 214 
 215     /**
 216      * This represents the warning message that is
 217      * to be displayed in a non secure window. ie :
 218      * a window that has a security manager installed that denies
 219      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 220      * This message can be displayed anywhere in the window.
 221      *
 222      * @serial
 223      * @see #getWarningString
 224      */
 225     String      warningString;
 226 
 227     /**
 228      * {@code icons} is the graphical way we can
 229      * represent the frames and dialogs.
 230      * {@code Window} can't display icon but it's
 231      * being inherited by owned {@code Dialog}s.
 232      *
 233      * @serial
 234      * @see #getIconImages
 235      * @see #setIconImages
 236      */
 237     transient java.util.List<Image> icons;
 238 
 239     /**
 240      * Holds the reference to the component which last had focus in this window
 241      * before it lost focus.
 242      */
 243     private transient Component temporaryLostComponent;
 244 
 245     static boolean systemSyncLWRequests = false;
 246     boolean     syncLWRequests = false;
 247     transient boolean beforeFirstShow = true;
 248     private transient boolean disposing = false;
 249     transient WindowDisposerRecord disposerRecord = null;
 250 
 251     static final int OPENED = 0x01;
 252 
 253     /**
 254      * An Integer value representing the Window State.
 255      *
 256      * @serial
 257      * @since 1.2
 258      * @see #show
 259      */
 260     int state;
 261 
 262     /**
 263      * A boolean value representing Window always-on-top state
 264      * @since 1.5
 265      * @serial
 266      * @see #setAlwaysOnTop
 267      * @see #isAlwaysOnTop
 268      */
 269     private boolean alwaysOnTop;
 270 
 271     /**
 272      * Contains all the windows that have a peer object associated,
 273      * i. e. between addNotify() and removeNotify() calls. The list
 274      * of all Window instances can be obtained from AppContext object.
 275      *
 276      * @since 1.6
 277      */
 278     private static final IdentityArrayList<Window> allWindows = new IdentityArrayList<Window>();
 279 
 280     /**
 281      * A vector containing all the windows this
 282      * window currently owns.
 283      * @since 1.2
 284      * @see #getOwnedWindows
 285      */
 286     transient Vector<WeakReference<Window>> ownedWindowList =
 287                                             new Vector<WeakReference<Window>>();
 288 
 289     /*
 290      * We insert a weak reference into the Vector of all Windows in AppContext
 291      * instead of 'this' so that garbage collection can still take place
 292      * correctly.
 293      */
 294     private transient WeakReference<Window> weakThis;
 295 
 296     transient boolean showWithParent;
 297 
 298     /**
 299      * Contains the modal dialog that blocks this window, or null
 300      * if the window is unblocked.
 301      *
 302      * @since 1.6
 303      */
 304     transient Dialog modalBlocker;
 305 
 306     /**
 307      * @serial
 308      *
 309      * @see java.awt.Dialog.ModalExclusionType
 310      * @see #getModalExclusionType
 311      * @see #setModalExclusionType
 312      *
 313      * @since 1.6
 314      */
 315     Dialog.ModalExclusionType modalExclusionType;
 316 
 317     transient WindowListener windowListener;
 318     transient WindowStateListener windowStateListener;
 319     transient WindowFocusListener windowFocusListener;
 320 
 321     transient InputContext inputContext;
 322     private transient Object inputContextLock = new Object();
 323 
 324     /**
 325      * Unused. Maintained for serialization backward-compatibility.
 326      *
 327      * @serial
 328      * @since 1.2
 329      */
 330     private FocusManager focusMgr;
 331 
 332     /**
 333      * Indicates whether this Window can become the focused Window.
 334      *
 335      * @serial
 336      * @see #getFocusableWindowState
 337      * @see #setFocusableWindowState
 338      * @since 1.4
 339      */
 340     private boolean focusableWindowState = true;
 341 
 342     /**
 343      * Indicates whether this window should receive focus on
 344      * subsequently being shown (with a call to {@code setVisible(true)}), or
 345      * being moved to the front (with a call to {@code toFront()}).
 346      *
 347      * @serial
 348      * @see #setAutoRequestFocus
 349      * @see #isAutoRequestFocus
 350      * @since 1.7
 351      */
 352     private volatile boolean autoRequestFocus = true;
 353 
 354     /*
 355      * Indicates that this window is being shown. This flag is set to true at
 356      * the beginning of show() and to false at the end of show().
 357      *
 358      * @see #show()
 359      * @see Dialog#shouldBlock
 360      */
 361     transient boolean isInShow = false;
 362 
 363     /**
 364      * The opacity level of the window
 365      *
 366      * @serial
 367      * @see #setOpacity(float)
 368      * @see #getOpacity()
 369      * @since 1.7
 370      */
 371     private volatile float opacity = 1.0f;
 372 
 373     /**
 374      * The shape assigned to this window. This field is set to {@code null} if
 375      * no shape is set (rectangular window).
 376      *
 377      * @serial
 378      * @see #getShape()
 379      * @see #setShape(Shape)
 380      * @since 1.7
 381      */
 382     @SuppressWarnings("serial") // Not statically typed as Serializable
 383     private Shape shape = null;
 384 
 385     private static final String base = "win";
 386     private static int nameCounter = 0;
 387 
 388     /*
 389      * JDK 1.1 serialVersionUID
 390      */
 391     private static final long serialVersionUID = 4497834738069338734L;
 392 
 393     private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Window");
 394 
 395     private static final boolean locationByPlatformProp;
 396 
 397     transient boolean isTrayIconWindow = false;
 398 
 399     /**
 400      * These fields are initialized in the native peer code
 401      * or via AWTAccessor's WindowAccessor.
 402      */
 403     private transient volatile int securityWarningWidth = 0;
 404     private transient volatile int securityWarningHeight = 0;
 405 
 406     static {
 407         /* ensure that the necessary native libraries are loaded */
 408         Toolkit.loadLibraries();
 409         if (!GraphicsEnvironment.isHeadless()) {
 410             initIDs();
 411         }
 412 
 413         String s = java.security.AccessController.doPrivileged(
 414             new GetPropertyAction("java.awt.syncLWRequests"));
 415         systemSyncLWRequests = (s != null && s.equals("true"));
 416         s = java.security.AccessController.doPrivileged(
 417             new GetPropertyAction("java.awt.Window.locationByPlatform"));
 418         locationByPlatformProp = (s != null && s.equals("true"));
 419     }
 420 
 421     /**
 422      * Initialize JNI field and method IDs for fields that may be
 423        accessed from C.
 424      */
 425     private static native void initIDs();
 426 
 427     /**
 428      * Constructs a new, initially invisible window in default size with the
 429      * specified {@code GraphicsConfiguration}.
 430      * <p>
 431      * If there is a security manager, then it is invoked to check
 432      * {@code AWTPermission("showWindowWithoutWarningBanner")}
 433      * to determine whether or not the window must be displayed with
 434      * a warning banner.
 435      *
 436      * @param gc the {@code GraphicsConfiguration} of the target screen
 437      *     device. If {@code gc} is {@code null}, the system default
 438      *     {@code GraphicsConfiguration} is assumed
 439      * @exception IllegalArgumentException if {@code gc}
 440      *    is not from a screen device
 441      * @exception HeadlessException when
 442      *     {@code GraphicsEnvironment.isHeadless()} returns {@code true}
 443      *
 444      * @see java.awt.GraphicsEnvironment#isHeadless
 445      */
 446     Window(GraphicsConfiguration gc) {
 447         init(gc);
 448     }
 449 
 450     transient Object anchor = new Object();
 451     static class WindowDisposerRecord implements sun.java2d.DisposerRecord {
 452         WeakReference<Window> owner;
 453         final WeakReference<Window> weakThis;
 454         final WeakReference<AppContext> context;
 455 
 456         WindowDisposerRecord(AppContext context, Window victim) {
 457             weakThis = victim.weakThis;
 458             this.context = new WeakReference<AppContext>(context);
 459         }
 460 
 461         public void updateOwner() {
 462             Window victim = weakThis.get();
 463             owner = (victim == null)
 464                     ? null
 465                     : new WeakReference<Window>(victim.getOwner());
 466         }
 467 
 468         public void dispose() {
 469             if (owner != null) {
 470                 Window parent = owner.get();
 471                 if (parent != null) {
 472                     parent.removeOwnedWindow(weakThis);
 473                 }
 474             }
 475             AppContext ac = context.get();
 476             if (null != ac) {
 477                 Window.removeFromWindowList(ac, weakThis);
 478             }
 479         }
 480     }
 481 
 482     private GraphicsConfiguration initGC(GraphicsConfiguration gc) {
 483         GraphicsEnvironment.checkHeadless();
 484 
 485         if (gc == null) {
 486             gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
 487                 getDefaultScreenDevice().getDefaultConfiguration();
 488         }
 489         setGraphicsConfiguration(gc);
 490 
 491         return gc;
 492     }
 493 
 494     private void init(GraphicsConfiguration gc) {
 495         GraphicsEnvironment.checkHeadless();
 496 
 497         syncLWRequests = systemSyncLWRequests;
 498 
 499         weakThis = new WeakReference<Window>(this);
 500         addToWindowList();
 501 
 502         setWarningString();
 503         this.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
 504         this.visible = false;
 505 
 506         gc = initGC(gc);
 507 
 508         if (gc.getDevice().getType() !=
 509             GraphicsDevice.TYPE_RASTER_SCREEN) {
 510             throw new IllegalArgumentException("not a screen device");
 511         }
 512         setLayout(new BorderLayout());
 513 
 514         /* offset the initial location with the original of the screen */
 515         /* and any insets                                              */
 516         Rectangle screenBounds = gc.getBounds();
 517         Insets screenInsets = getToolkit().getScreenInsets(gc);
 518         int x = getX() + screenBounds.x + screenInsets.left;
 519         int y = getY() + screenBounds.y + screenInsets.top;
 520         if (x != this.x || y != this.y) {
 521             setLocation(x, y);
 522             /* reset after setLocation */
 523             setLocationByPlatform(locationByPlatformProp);
 524         }
 525 
 526         modalExclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
 527         disposerRecord = new WindowDisposerRecord(appContext, this);
 528         sun.java2d.Disposer.addRecord(anchor, disposerRecord);
 529 
 530         SunToolkit.checkAndSetPolicy(this);
 531     }
 532 
 533     /**
 534      * Constructs a new, initially invisible window in the default size.
 535      * <p>
 536      * If there is a security manager set, it is invoked to check
 537      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 538      * If that check fails with a {@code SecurityException} then a warning
 539      * banner is created.
 540      *
 541      * @exception HeadlessException when
 542      *     {@code GraphicsEnvironment.isHeadless()} returns {@code true}
 543      *
 544      * @see java.awt.GraphicsEnvironment#isHeadless
 545      */
 546     Window() throws HeadlessException {
 547         GraphicsEnvironment.checkHeadless();
 548         init((GraphicsConfiguration)null);
 549     }
 550 
 551     /**
 552      * Constructs a new, initially invisible window with the specified
 553      * {@code Frame} as its owner. The window will not be focusable
 554      * unless its owner is showing on the screen.
 555      * <p>
 556      * If there is a security manager set, it is invoked to check
 557      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 558      * If that check fails with a {@code SecurityException} then a warning
 559      * banner is created.
 560      *
 561      * @param owner the {@code Frame} to act as owner or {@code null}
 562      *    if this window has no owner
 563      * @exception IllegalArgumentException if the {@code owner}'s
 564      *    {@code GraphicsConfiguration} is not from a screen device
 565      * @exception HeadlessException when
 566      *    {@code GraphicsEnvironment.isHeadless} returns {@code true}
 567      *
 568      * @see java.awt.GraphicsEnvironment#isHeadless
 569      * @see #isShowing
 570      */
 571     public Window(Frame owner) {
 572         this(owner == null ? (GraphicsConfiguration)null :
 573             owner.getGraphicsConfiguration());
 574         ownedInit(owner);
 575     }
 576 
 577     /**
 578      * Constructs a new, initially invisible window with the specified
 579      * {@code Window} as its owner. This window will not be focusable
 580      * unless its nearest owning {@code Frame} or {@code Dialog}
 581      * is showing on the screen.
 582      * <p>
 583      * If there is a security manager set, it is invoked to check
 584      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
 585      * If that check fails with a {@code SecurityException} then a
 586      * warning banner is created.
 587      *
 588      * @param owner the {@code Window} to act as owner or
 589      *     {@code null} if this window has no owner
 590      * @exception IllegalArgumentException if the {@code owner}'s
 591      *     {@code GraphicsConfiguration} is not from a screen device
 592      * @exception HeadlessException when
 593      *     {@code GraphicsEnvironment.isHeadless()} returns
 594      *     {@code true}
 595      *
 596      * @see       java.awt.GraphicsEnvironment#isHeadless
 597      * @see       #isShowing
 598      *
 599      * @since     1.2
 600      */
 601     public Window(Window owner) {
 602         this(owner == null ? (GraphicsConfiguration)null :
 603             owner.getGraphicsConfiguration());
 604         ownedInit(owner);
 605     }
 606 
 607     /**
 608      * Constructs a new, initially invisible window with the specified owner
 609      * {@code Window} and a {@code GraphicsConfiguration}
 610      * of a screen device. The Window will not be focusable unless
 611      * its nearest owning {@code Frame} or {@code Dialog}
 612      * is showing on the screen.
 613      * <p>
 614      * If there is a security manager set, it is invoked to check
 615      * {@code AWTPermission("showWindowWithoutWarningBanner")}. If that
 616      * check fails with a {@code SecurityException} then a warning banner
 617      * is created.
 618      *
 619      * @param owner the window to act as owner or {@code null}
 620      *     if this window has no owner
 621      * @param gc the {@code GraphicsConfiguration} of the target
 622      *     screen device; if {@code gc} is {@code null},
 623      *     the system default {@code GraphicsConfiguration} is assumed
 624      * @exception IllegalArgumentException if {@code gc}
 625      *     is not from a screen device
 626      * @exception HeadlessException when
 627      *     {@code GraphicsEnvironment.isHeadless()} returns
 628      *     {@code true}
 629      *
 630      * @see       java.awt.GraphicsEnvironment#isHeadless
 631      * @see       GraphicsConfiguration#getBounds
 632      * @see       #isShowing
 633      * @since     1.3
 634      */
 635     public Window(Window owner, GraphicsConfiguration gc) {
 636         this(gc);
 637         ownedInit(owner);
 638     }
 639 
 640     private void ownedInit(Window owner) {
 641         this.parent = owner;
 642         if (owner != null) {
 643             owner.addOwnedWindow(weakThis);
 644             if (owner.isAlwaysOnTop()) {
 645                 try {
 646                     setAlwaysOnTop(true);
 647                 } catch (SecurityException ignore) {
 648                 }
 649             }
 650         }
 651 
 652         // WindowDisposerRecord requires a proper value of parent field.
 653         disposerRecord.updateOwner();
 654     }
 655 
 656     /**
 657      * Construct a name for this component.  Called by getName() when the
 658      * name is null.
 659      */
 660     String constructComponentName() {
 661         synchronized (Window.class) {
 662             return base + nameCounter++;
 663         }
 664     }
 665 
 666     /**
 667      * Returns the sequence of images to be displayed as the icon for this window.
 668      * <p>
 669      * This method returns a copy of the internally stored list, so all operations
 670      * on the returned object will not affect the window's behavior.
 671      *
 672      * @return    the copy of icon images' list for this window, or
 673      *            empty list if this window doesn't have icon images.
 674      * @see       #setIconImages
 675      * @see       #setIconImage(Image)
 676      * @since     1.6
 677      */
 678     public java.util.List<Image> getIconImages() {
 679         java.util.List<Image> icons = this.icons;
 680         if (icons == null || icons.size() == 0) {
 681             return new ArrayList<Image>();
 682         }
 683         return new ArrayList<Image>(icons);
 684     }
 685 
 686     /**
 687      * Sets the sequence of images to be displayed as the icon
 688      * for this window. Subsequent calls to {@code getIconImages} will
 689      * always return a copy of the {@code icons} list.
 690      * <p>
 691      * Depending on the platform capabilities one or several images
 692      * of different dimensions will be used as the window's icon.
 693      * <p>
 694      * The {@code icons} list can contain {@code MultiResolutionImage} images also.
 695      * Suitable image depending on screen resolution is extracted from
 696      * base {@code MultiResolutionImage} image and added to the icons list
 697      * while base resolution image is removed from list.
 698      * The {@code icons} list is scanned for the images of most
 699      * appropriate dimensions from the beginning. If the list contains
 700      * several images of the same size, the first will be used.
 701      * <p>
 702      * Ownerless windows with no icon specified use platform-default icon.
 703      * The icon of an owned window may be inherited from the owner
 704      * unless explicitly overridden.
 705      * Setting the icon to {@code null} or empty list restores
 706      * the default behavior.
 707      * <p>
 708      * Note : Native windowing systems may use different images of differing
 709      * dimensions to represent a window, depending on the context (e.g.
 710      * window decoration, window list, taskbar, etc.). They could also use
 711      * just a single image for all contexts or no image at all.
 712      *
 713      * @param     icons the list of icon images to be displayed.
 714      * @see       #getIconImages()
 715      * @see       #setIconImage(Image)
 716      * @since     1.6
 717      */
 718     public synchronized void setIconImages(java.util.List<? extends Image> icons) {
 719         this.icons = (icons == null) ? new ArrayList<Image>() :
 720             new ArrayList<Image>(icons);
 721         WindowPeer peer = (WindowPeer)this.peer;
 722         if (peer != null) {
 723             peer.updateIconImages();
 724         }
 725         // Always send a property change event
 726         firePropertyChange("iconImage", null, null);
 727     }
 728 
 729     /**
 730      * Sets the image to be displayed as the icon for this window.
 731      * <p>
 732      * This method can be used instead of {@link #setIconImages setIconImages()}
 733      * to specify a single image as a window's icon.
 734      * <p>
 735      * The following statement:
 736      * <pre>
 737      *     setIconImage(image);
 738      * </pre>
 739      * is equivalent to:
 740      * <pre>
 741      *     ArrayList&lt;Image&gt; imageList = new ArrayList&lt;Image&gt;();
 742      *     imageList.add(image);
 743      *     setIconImages(imageList);
 744      * </pre>
 745      * <p>
 746      * Note : Native windowing systems may use different images of differing
 747      * dimensions to represent a window, depending on the context (e.g.
 748      * window decoration, window list, taskbar, etc.). They could also use
 749      * just a single image for all contexts or no image at all.
 750      *
 751      * @param     image the icon image to be displayed.
 752      * @see       #setIconImages
 753      * @see       #getIconImages()
 754      * @since     1.6
 755      */
 756     public void setIconImage(Image image) {
 757         ArrayList<Image> imageList = new ArrayList<Image>();
 758         if (image != null) {
 759             imageList.add(image);
 760         }
 761         setIconImages(imageList);
 762     }
 763 
 764     /**
 765      * Makes this Window displayable by creating the connection to its
 766      * native screen resource.
 767      * This method is called internally by the toolkit and should
 768      * not be called directly by programs.
 769      * @see Component#isDisplayable
 770      * @see Container#removeNotify
 771      * @since 1.0
 772      */
 773     public void addNotify() {
 774         synchronized (getTreeLock()) {
 775             Container parent = this.parent;
 776             if (parent != null && parent.peer == null) {
 777                 parent.addNotify();
 778             }
 779             if (peer == null) {
 780                 peer = getComponentFactory().createWindow(this);
 781             }
 782             synchronized (allWindows) {
 783                 allWindows.add(this);
 784             }
 785             super.addNotify();
 786         }
 787     }
 788 
 789     /**
 790      * {@inheritDoc}
 791      */
 792     public void removeNotify() {
 793         synchronized (getTreeLock()) {
 794             synchronized (allWindows) {
 795                 allWindows.remove(this);
 796             }
 797             super.removeNotify();
 798         }
 799     }
 800 
 801     /**
 802      * Causes this Window to be sized to fit the preferred size
 803      * and layouts of its subcomponents. The resulting width and
 804      * height of the window are automatically enlarged if either
 805      * of dimensions is less than the minimum size as specified
 806      * by the previous call to the {@code setMinimumSize} method.
 807      * <p>
 808      * If the window and/or its owner are not displayable yet,
 809      * both of them are made displayable before calculating
 810      * the preferred size. The Window is validated after its
 811      * size is being calculated.
 812      *
 813      * @see Component#isDisplayable
 814      * @see #setMinimumSize
 815      */
 816     @SuppressWarnings("deprecation")
 817     public void pack() {
 818         Container parent = this.parent;
 819         if (parent != null && parent.peer == null) {
 820             parent.addNotify();
 821         }
 822         if (peer == null) {
 823             addNotify();
 824         }
 825         Dimension newSize = getPreferredSize();
 826         if (peer != null) {
 827             setClientSize(newSize.width, newSize.height);
 828         }
 829 
 830         if(beforeFirstShow) {
 831             isPacked = true;
 832         }
 833 
 834         validateUnconditionally();
 835     }
 836 
 837     /**
 838      * Sets the minimum size of this window to a constant
 839      * value.  Subsequent calls to {@code getMinimumSize}
 840      * will always return this value. If current window's
 841      * size is less than {@code minimumSize} the size of the
 842      * window is automatically enlarged to honor the minimum size.
 843      * <p>
 844      * If the {@code setSize} or {@code setBounds} methods
 845      * are called afterwards with a width or height less than
 846      * that was specified by the {@code setMinimumSize} method
 847      * the window is automatically enlarged to meet
 848      * the {@code minimumSize} value. The {@code minimumSize}
 849      * value also affects the behaviour of the {@code pack} method.
 850      * <p>
 851      * The default behavior is restored by setting the minimum size
 852      * parameter to the {@code null} value.
 853      * <p>
 854      * Resizing operation may be restricted if the user tries
 855      * to resize window below the {@code minimumSize} value.
 856      * This behaviour is platform-dependent.
 857      *
 858      * @param minimumSize the new minimum size of this window
 859      * @see Component#setMinimumSize
 860      * @see #getMinimumSize
 861      * @see #isMinimumSizeSet
 862      * @see #setSize(Dimension)
 863      * @see #pack
 864      * @since 1.6
 865      */
 866     public void setMinimumSize(Dimension minimumSize) {
 867         synchronized (getTreeLock()) {
 868             super.setMinimumSize(minimumSize);
 869             Dimension size = getSize();
 870             if (isMinimumSizeSet()) {
 871                 if (size.width < minimumSize.width || size.height < minimumSize.height) {
 872                     int nw = Math.max(width, minimumSize.width);
 873                     int nh = Math.max(height, minimumSize.height);
 874                     setSize(nw, nh);
 875                 }
 876             }
 877             if (peer != null) {
 878                 ((WindowPeer)peer).updateMinimumSize();
 879             }
 880         }
 881     }
 882 
 883     /**
 884      * {@inheritDoc}
 885      * <p>
 886      * The {@code d.width} and {@code d.height} values
 887      * are automatically enlarged if either is less than
 888      * the minimum size as specified by previous call to
 889      * {@code setMinimumSize}.
 890      * <p>
 891      * The method changes the geometry-related data. Therefore,
 892      * the native windowing system may ignore such requests, or it may modify
 893      * the requested data, so that the {@code Window} object is placed and sized
 894      * in a way that corresponds closely to the desktop settings.
 895      *
 896      * @see #getSize
 897      * @see #setBounds
 898      * @see #setMinimumSize
 899      * @since 1.6
 900      */
 901     public void setSize(Dimension d) {
 902         super.setSize(d);
 903     }
 904 
 905     /**
 906      * {@inheritDoc}
 907      * <p>
 908      * The {@code width} and {@code height} values
 909      * are automatically enlarged if either is less than
 910      * the minimum size as specified by previous call to
 911      * {@code setMinimumSize}.
 912      * <p>
 913      * The method changes the geometry-related data. Therefore,
 914      * the native windowing system may ignore such requests, or it may modify
 915      * the requested data, so that the {@code Window} object is placed and sized
 916      * in a way that corresponds closely to the desktop settings.
 917      *
 918      * @see #getSize
 919      * @see #setBounds
 920      * @see #setMinimumSize
 921      * @since 1.6
 922      */
 923     public void setSize(int width, int height) {
 924         super.setSize(width, height);
 925     }
 926 
 927     /**
 928      * {@inheritDoc}
 929      * <p>
 930      * The method changes the geometry-related data. Therefore,
 931      * the native windowing system may ignore such requests, or it may modify
 932      * the requested data, so that the {@code Window} object is placed and sized
 933      * in a way that corresponds closely to the desktop settings.
 934      */
 935     @Override
 936     public void setLocation(int x, int y) {
 937         super.setLocation(x, y);
 938     }
 939 
 940     /**
 941      * {@inheritDoc}
 942      * <p>
 943      * The method changes the geometry-related data. Therefore,
 944      * the native windowing system may ignore such requests, or it may modify
 945      * the requested data, so that the {@code Window} object is placed and sized
 946      * in a way that corresponds closely to the desktop settings.
 947      */
 948     @Override
 949     public void setLocation(Point p) {
 950         super.setLocation(p);
 951     }
 952 
 953     /**
 954      * @deprecated As of JDK version 1.1,
 955      * replaced by {@code setBounds(int, int, int, int)}.
 956      */
 957     @Deprecated
 958     public void reshape(int x, int y, int width, int height) {
 959         if (isMinimumSizeSet()) {
 960             Dimension minSize = getMinimumSize();
 961             if (width < minSize.width) {
 962                 width = minSize.width;
 963             }
 964             if (height < minSize.height) {
 965                 height = minSize.height;
 966             }
 967         }
 968         super.reshape(x, y, width, height);
 969     }
 970 
 971     void setClientSize(int w, int h) {
 972         synchronized (getTreeLock()) {
 973             setBoundsOp(ComponentPeer.SET_CLIENT_SIZE);
 974             setBounds(x, y, w, h);
 975         }
 976     }
 977 
 978     private static final AtomicBoolean
 979         beforeFirstWindowShown = new AtomicBoolean(true);
 980 
 981     final void closeSplashScreen() {
 982         if (isTrayIconWindow) {
 983             return;
 984         }
 985         if (beforeFirstWindowShown.getAndSet(false)) {
 986             // We don't use SplashScreen.getSplashScreen() to avoid instantiating
 987             // the object if it hasn't been requested by user code explicitly
 988             SunToolkit.closeSplashScreen();
 989             SplashScreen.markClosed();
 990         }
 991     }
 992 
 993     /**
 994      * Shows or hides this {@code Window} depending on the value of parameter
 995      * {@code b}.
 996      * <p>
 997      * If the method shows the window then the window is also made
 998      * focused under the following conditions:
 999      * <ul>
1000      * <li> The {@code Window} meets the requirements outlined in the
1001      *      {@link #isFocusableWindow} method.
1002      * <li> The {@code Window}'s {@code autoRequestFocus} property is of the {@code true} value.
1003      * <li> Native windowing system allows the {@code Window} to get focused.
1004      * </ul>
1005      * There is an exception for the second condition (the value of the
1006      * {@code autoRequestFocus} property). The property is not taken into account if the
1007      * window is a modal dialog, which blocks the currently focused window.
1008      * <p>
1009      * Developers must never assume that the window is the focused or active window
1010      * until it receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED event.
1011      * @param b  if {@code true}, makes the {@code Window} visible,
1012      * otherwise hides the {@code Window}.
1013      * If the {@code Window} and/or its owner
1014      * are not yet displayable, both are made displayable.  The
1015      * {@code Window} will be validated prior to being made visible.
1016      * If the {@code Window} is already visible, this will bring the
1017      * {@code Window} to the front.<p>
1018      * If {@code false}, hides this {@code Window}, its subcomponents, and all
1019      * of its owned children.
1020      * The {@code Window} and its subcomponents can be made visible again
1021      * with a call to {@code #setVisible(true)}.
1022      * @see java.awt.Component#isDisplayable
1023      * @see java.awt.Component#setVisible
1024      * @see java.awt.Window#toFront
1025      * @see java.awt.Window#dispose
1026      * @see java.awt.Window#setAutoRequestFocus
1027      * @see java.awt.Window#isFocusableWindow
1028      */
1029     public void setVisible(boolean b) {
1030         super.setVisible(b);
1031     }
1032 
1033     /**
1034      * Makes the Window visible. If the Window and/or its owner
1035      * are not yet displayable, both are made displayable.  The
1036      * Window will be validated prior to being made visible.
1037      * If the Window is already visible, this will bring the Window
1038      * to the front.
1039      * @see       Component#isDisplayable
1040      * @see       #toFront
1041      * @deprecated As of JDK version 1.5, replaced by
1042      * {@link #setVisible(boolean)}.
1043      */
1044     @Deprecated
1045     public void show() {
1046         if (peer == null) {
1047             addNotify();
1048         }
1049         validateUnconditionally();
1050 
1051         isInShow = true;
1052         if (visible) {
1053             toFront();
1054         } else {
1055             beforeFirstShow = false;
1056             closeSplashScreen();
1057             Dialog.checkShouldBeBlocked(this);
1058             super.show();
1059             locationByPlatform = false;
1060             for (int i = 0; i < ownedWindowList.size(); i++) {
1061                 Window child = ownedWindowList.elementAt(i).get();
1062                 if ((child != null) && child.showWithParent) {
1063                     child.show();
1064                     child.showWithParent = false;
1065                 }       // endif
1066             }   // endfor
1067             if (!isModalBlocked()) {
1068                 updateChildrenBlocking();
1069             } else {
1070                 // fix for 6532736: after this window is shown, its blocker
1071                 // should be raised to front
1072                 modalBlocker.toFront_NoClientCode();
1073             }
1074             if (this instanceof Frame || this instanceof Dialog) {
1075                 updateChildFocusableWindowState(this);
1076             }
1077         }
1078         isInShow = false;
1079 
1080         // If first time shown, generate WindowOpened event
1081         if ((state & OPENED) == 0) {
1082             postWindowEvent(WindowEvent.WINDOW_OPENED);
1083             state |= OPENED;
1084         }
1085     }
1086 
1087     static void updateChildFocusableWindowState(Window w) {
1088         if (w.peer != null && w.isShowing()) {
1089             ((WindowPeer)w.peer).updateFocusableWindowState();
1090         }
1091         for (int i = 0; i < w.ownedWindowList.size(); i++) {
1092             Window child = w.ownedWindowList.elementAt(i).get();
1093             if (child != null) {
1094                 updateChildFocusableWindowState(child);
1095             }
1096         }
1097     }
1098 
1099     synchronized void postWindowEvent(int id) {
1100         if (windowListener != null
1101             || (eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0
1102             ||  Toolkit.enabledOnToolkit(AWTEvent.WINDOW_EVENT_MASK)) {
1103             WindowEvent e = new WindowEvent(this, id);
1104             Toolkit.getEventQueue().postEvent(e);
1105         }
1106     }
1107 
1108     /**
1109      * Hide this Window, its subcomponents, and all of its owned children.
1110      * The Window and its subcomponents can be made visible again
1111      * with a call to {@code show}.
1112      * @see #show
1113      * @see #dispose
1114      * @deprecated As of JDK version 1.5, replaced by
1115      * {@link #setVisible(boolean)}.
1116      */
1117     @Deprecated
1118     public void hide() {
1119         synchronized(ownedWindowList) {
1120             for (int i = 0; i < ownedWindowList.size(); i++) {
1121                 Window child = ownedWindowList.elementAt(i).get();
1122                 if ((child != null) && child.visible) {
1123                     child.hide();
1124                     child.showWithParent = true;
1125                 }
1126             }
1127         }
1128         if (isModalBlocked()) {
1129             modalBlocker.unblockWindow(this);
1130         }
1131         super.hide();
1132         locationByPlatform = false;
1133     }
1134 
1135     final void clearMostRecentFocusOwnerOnHide() {
1136         /* do nothing */
1137     }
1138 
1139     /**
1140      * Releases all of the native screen resources used by this
1141      * {@code Window}, its subcomponents, and all of its owned
1142      * children. That is, the resources for these {@code Component}s
1143      * will be destroyed, any memory they consume will be returned to the
1144      * OS, and they will be marked as undisplayable.
1145      * <p>
1146      * The {@code Window} and its subcomponents can be made displayable
1147      * again by rebuilding the native resources with a subsequent call to
1148      * {@code pack} or {@code show}. The states of the recreated
1149      * {@code Window} and its subcomponents will be identical to the
1150      * states of these objects at the point where the {@code Window}
1151      * was disposed (not accounting for additional modifications between
1152      * those actions).
1153      * <p>
1154      * <b>Note</b>: When the last displayable window
1155      * within the Java virtual machine (VM) is disposed of, the VM may
1156      * terminate.  See <a href="doc-files/AWTThreadIssues.html#Autoshutdown">
1157      * AWT Threading Issues</a> for more information.
1158      * @see Component#isDisplayable
1159      * @see #pack
1160      * @see #show
1161      */
1162     public void dispose() {
1163         doDispose();
1164     }
1165 
1166     /*
1167      * Fix for 4872170.
1168      * If dispose() is called on parent then its children have to be disposed as well
1169      * as reported in javadoc. So we need to implement this functionality even if a
1170      * child overrides dispose() in a wrong way without calling super.dispose().
1171      */
1172     void disposeImpl() {
1173         dispose();
1174         if (peer != null) {
1175             doDispose();
1176         }
1177     }
1178 
1179     void doDispose() {
1180     class DisposeAction implements Runnable {
1181         public void run() {
1182             disposing = true;
1183             try {
1184                 // Check if this window is the fullscreen window for the
1185                 // device. Exit the fullscreen mode prior to disposing
1186                 // of the window if that's the case.
1187                 GraphicsDevice gd = getGraphicsConfiguration().getDevice();
1188                 if (gd.getFullScreenWindow() == Window.this) {
1189                     gd.setFullScreenWindow(null);
1190                 }
1191 
1192                 Object[] ownedWindowArray;
1193                 synchronized(ownedWindowList) {
1194                     ownedWindowArray = new Object[ownedWindowList.size()];
1195                     ownedWindowList.copyInto(ownedWindowArray);
1196                 }
1197                 for (int i = 0; i < ownedWindowArray.length; i++) {
1198                     Window child = (Window) (((WeakReference)
1199                                    (ownedWindowArray[i])).get());
1200                     if (child != null) {
1201                         child.disposeImpl();
1202                     }
1203                 }
1204                 hide();
1205                 beforeFirstShow = true;
1206                 removeNotify();
1207                 synchronized (inputContextLock) {
1208                     if (inputContext != null) {
1209                         inputContext.dispose();
1210                         inputContext = null;
1211                     }
1212                 }
1213                 clearCurrentFocusCycleRootOnHide();
1214             } finally {
1215                 disposing = false;
1216             }
1217         }
1218     }
1219         boolean fireWindowClosedEvent = isDisplayable();
1220         DisposeAction action = new DisposeAction();
1221         if (EventQueue.isDispatchThread()) {
1222             action.run();
1223         }
1224         else {
1225             try {
1226                 EventQueue.invokeAndWait(this, action);
1227             }
1228             catch (InterruptedException e) {
1229                 System.err.println("Disposal was interrupted:");
1230                 e.printStackTrace();
1231             }
1232             catch (InvocationTargetException e) {
1233                 System.err.println("Exception during disposal:");
1234                 e.printStackTrace();
1235             }
1236         }
1237         // Execute outside the Runnable because postWindowEvent is
1238         // synchronized on (this). We don't need to synchronize the call
1239         // on the EventQueue anyways.
1240         if (fireWindowClosedEvent) {
1241             postWindowEvent(WindowEvent.WINDOW_CLOSED);
1242         }
1243     }
1244 
1245     /*
1246      * Should only be called while holding the tree lock.
1247      * It's overridden here because parent == owner in Window,
1248      * and we shouldn't adjust counter on owner
1249      */
1250     void adjustListeningChildrenOnParent(long mask, int num) {
1251     }
1252 
1253     // Should only be called while holding tree lock
1254     void adjustDescendantsOnParent(int num) {
1255         // do nothing since parent == owner and we shouldn't
1256         // adjust counter on owner
1257     }
1258 
1259     /**
1260      * If this Window is visible, brings this Window to the front and may make
1261      * it the focused Window.
1262      * <p>
1263      * Places this Window at the top of the stacking order and shows it in
1264      * front of any other Windows in this VM. No action will take place if this
1265      * Window is not visible. Some platforms do not allow Windows which own
1266      * other Windows to appear on top of those owned Windows. Some platforms
1267      * may not permit this VM to place its Windows above windows of native
1268      * applications, or Windows of other VMs. This permission may depend on
1269      * whether a Window in this VM is already focused. Every attempt will be
1270      * made to move this Window as high as possible in the stacking order;
1271      * however, developers should not assume that this method will move this
1272      * Window above all other windows in every situation.
1273      * <p>
1274      * Developers must never assume that this Window is the focused or active
1275      * Window until this Window receives a WINDOW_GAINED_FOCUS or WINDOW_ACTIVATED
1276      * event. On platforms where the top-most window is the focused window, this
1277      * method will <b>probably</b> focus this Window (if it is not already focused)
1278      * under the following conditions:
1279      * <ul>
1280      * <li> The window meets the requirements outlined in the
1281      *      {@link #isFocusableWindow} method.
1282      * <li> The window's property {@code autoRequestFocus} is of the
1283      *      {@code true} value.
1284      * <li> Native windowing system allows the window to get focused.
1285      * </ul>
1286      * On platforms where the stacking order does not typically affect the focused
1287      * window, this method will <b>probably</b> leave the focused and active
1288      * Windows unchanged.
1289      * <p>
1290      * If this method causes this Window to be focused, and this Window is a
1291      * Frame or a Dialog, it will also become activated. If this Window is
1292      * focused, but it is not a Frame or a Dialog, then the first Frame or
1293      * Dialog that is an owner of this Window will be activated.
1294      * <p>
1295      * If this window is blocked by modal dialog, then the blocking dialog
1296      * is brought to the front and remains above the blocked window.
1297      *
1298      * @see       #toBack
1299      * @see       #setAutoRequestFocus
1300      * @see       #isFocusableWindow
1301      */
1302     public void toFront() {
1303         toFront_NoClientCode();
1304     }
1305 
1306     // This functionality is implemented in a final package-private method
1307     // to insure that it cannot be overridden by client subclasses.
1308     final void toFront_NoClientCode() {
1309         if (visible) {
1310             WindowPeer peer = (WindowPeer)this.peer;
1311             if (peer != null) {
1312                 peer.toFront();
1313             }
1314             if (isModalBlocked()) {
1315                 modalBlocker.toFront_NoClientCode();
1316             }
1317         }
1318     }
1319 
1320     /**
1321      * If this Window is visible, sends this Window to the back and may cause
1322      * it to lose focus or activation if it is the focused or active Window.
1323      * <p>
1324      * Places this Window at the bottom of the stacking order and shows it
1325      * behind any other Windows in this VM. No action will take place is this
1326      * Window is not visible. Some platforms do not allow Windows which are
1327      * owned by other Windows to appear below their owners. Every attempt will
1328      * be made to move this Window as low as possible in the stacking order;
1329      * however, developers should not assume that this method will move this
1330      * Window below all other windows in every situation.
1331      * <p>
1332      * Because of variations in native windowing systems, no guarantees about
1333      * changes to the focused and active Windows can be made. Developers must
1334      * never assume that this Window is no longer the focused or active Window
1335      * until this Window receives a WINDOW_LOST_FOCUS or WINDOW_DEACTIVATED
1336      * event. On platforms where the top-most window is the focused window,
1337      * this method will <b>probably</b> cause this Window to lose focus. In
1338      * that case, the next highest, focusable Window in this VM will receive
1339      * focus. On platforms where the stacking order does not typically affect
1340      * the focused window, this method will <b>probably</b> leave the focused
1341      * and active Windows unchanged.
1342      *
1343      * @see       #toFront
1344      */
1345     public void toBack() {
1346         toBack_NoClientCode();
1347     }
1348 
1349     // This functionality is implemented in a final package-private method
1350     // to insure that it cannot be overridden by client subclasses.
1351     final void toBack_NoClientCode() {
1352         if(isAlwaysOnTop()) {
1353             try {
1354                 setAlwaysOnTop(false);
1355             }catch(SecurityException e) {
1356             }
1357         }
1358         if (visible) {
1359             WindowPeer peer = (WindowPeer)this.peer;
1360             if (peer != null) {
1361                 peer.toBack();
1362             }
1363         }
1364     }
1365 
1366     /**
1367      * Returns the toolkit of this frame.
1368      * @return    the toolkit of this window.
1369      * @see       Toolkit
1370      * @see       Toolkit#getDefaultToolkit
1371      * @see       Component#getToolkit
1372      */
1373     public Toolkit getToolkit() {
1374         return Toolkit.getDefaultToolkit();
1375     }
1376 
1377     /**
1378      * Gets the warning string that is displayed with this window.
1379      * If this window is insecure, the warning string is displayed
1380      * somewhere in the visible area of the window. A window is
1381      * insecure if there is a security manager and the security
1382      * manager denies
1383      * {@code AWTPermission("showWindowWithoutWarningBanner")}.
1384      * <p>
1385      * If the window is secure, then {@code getWarningString}
1386      * returns {@code null}. If the window is insecure, this
1387      * method checks for the system property
1388      * {@code awt.appletWarning}
1389      * and returns the string value of that property.
1390      * @return    the warning string for this window.
1391      */
1392     public final String getWarningString() {
1393         return warningString;
1394     }
1395 
1396     private void setWarningString() {
1397         warningString = null;
1398         SecurityManager sm = System.getSecurityManager();
1399         if (sm != null) {
1400             try {
1401                 sm.checkPermission(AWTPermissions.TOPLEVEL_WINDOW_PERMISSION);
1402             } catch (SecurityException se) {
1403                 // make sure the privileged action is only
1404                 // for getting the property! We don't want the
1405                 // above checkPermission call to always succeed!
1406                 warningString = AccessController.doPrivileged(
1407                       new GetPropertyAction("awt.appletWarning",
1408                                             "Java Applet Window"));
1409             }
1410         }
1411     }
1412 
1413     /**
1414      * Gets the {@code Locale} object that is associated
1415      * with this window, if the locale has been set.
1416      * If no locale has been set, then the default locale
1417      * is returned.
1418      * @return    the locale that is set for this window.
1419      * @see       java.util.Locale
1420      * @since     1.1
1421      */
1422     public Locale getLocale() {
1423       if (this.locale == null) {
1424         return Locale.getDefault();
1425       }
1426       return this.locale;
1427     }
1428 
1429     /**
1430      * Gets the input context for this window. A window always has an input context,
1431      * which is shared by subcomponents unless they create and set their own.
1432      * @see Component#getInputContext
1433      * @since 1.2
1434      */
1435     public InputContext getInputContext() {
1436         synchronized (inputContextLock) {
1437             if (inputContext == null) {
1438                 inputContext = InputContext.getInstance();
1439             }
1440         }
1441         return inputContext;
1442     }
1443 
1444     /**
1445      * Set the cursor image to a specified cursor.
1446      * <p>
1447      * The method may have no visual effect if the Java platform
1448      * implementation and/or the native system do not support
1449      * changing the mouse cursor shape.
1450      * @param     cursor One of the constants defined
1451      *            by the {@code Cursor} class. If this parameter is null
1452      *            then the cursor for this window will be set to the type
1453      *            Cursor.DEFAULT_CURSOR.
1454      * @see       Component#getCursor
1455      * @see       Cursor
1456      * @since     1.1
1457      */
1458     public void setCursor(Cursor cursor) {
1459         if (cursor == null) {
1460             cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
1461         }
1462         super.setCursor(cursor);
1463     }
1464 
1465     /**
1466      * Returns the owner of this window.
1467      *
1468      * @return the owner of this window
1469      * @since 1.2
1470      */
1471     public Window getOwner() {
1472         return getOwner_NoClientCode();
1473     }
1474     final Window getOwner_NoClientCode() {
1475         return (Window)parent;
1476     }
1477 
1478     /**
1479      * Return an array containing all the windows this
1480      * window currently owns.
1481      *
1482      * @return the array of all the owned windows
1483      * @since 1.2
1484      */
1485     public Window[] getOwnedWindows() {
1486         return getOwnedWindows_NoClientCode();
1487     }
1488     final Window[] getOwnedWindows_NoClientCode() {
1489         Window[] realCopy;
1490 
1491         synchronized(ownedWindowList) {
1492             // Recall that ownedWindowList is actually a Vector of
1493             // WeakReferences and calling get() on one of these references
1494             // may return null. Make two arrays-- one the size of the
1495             // Vector (fullCopy with size fullSize), and one the size of
1496             // all non-null get()s (realCopy with size realSize).
1497             int fullSize = ownedWindowList.size();
1498             int realSize = 0;
1499             Window[] fullCopy = new Window[fullSize];
1500 
1501             for (int i = 0; i < fullSize; i++) {
1502                 fullCopy[realSize] = ownedWindowList.elementAt(i).get();
1503 
1504                 if (fullCopy[realSize] != null) {
1505                     realSize++;
1506                 }
1507             }
1508 
1509             if (fullSize != realSize) {
1510                 realCopy = Arrays.copyOf(fullCopy, realSize);
1511             } else {
1512                 realCopy = fullCopy;
1513             }
1514         }
1515 
1516         return realCopy;
1517     }
1518 
1519     boolean isModalBlocked() {
1520         return modalBlocker != null;
1521     }
1522 
1523     void setModalBlocked(Dialog blocker, boolean blocked, boolean peerCall) {
1524         this.modalBlocker = blocked ? blocker : null;
1525         if (peerCall) {
1526             WindowPeer peer = (WindowPeer)this.peer;
1527             if (peer != null) {
1528                 peer.setModalBlocked(blocker, blocked);
1529             }
1530         }
1531     }
1532 
1533     Dialog getModalBlocker() {
1534         return modalBlocker;
1535     }
1536 
1537     /*
1538      * Returns a list of all displayable Windows, i. e. all the
1539      * Windows which peer is not null.
1540      *
1541      * @see #addNotify
1542      * @see #removeNotify
1543      */
1544     static IdentityArrayList<Window> getAllWindows() {
1545         synchronized (allWindows) {
1546             IdentityArrayList<Window> v = new IdentityArrayList<Window>();
1547             v.addAll(allWindows);
1548             return v;
1549         }
1550     }
1551 
1552     static IdentityArrayList<Window> getAllUnblockedWindows() {
1553         synchronized (allWindows) {
1554             IdentityArrayList<Window> unblocked = new IdentityArrayList<Window>();
1555             for (int i = 0; i < allWindows.size(); i++) {
1556                 Window w = allWindows.get(i);
1557                 if (!w.isModalBlocked()) {
1558                     unblocked.add(w);
1559                 }
1560             }
1561             return unblocked;
1562         }
1563     }
1564 
1565     private static Window[] getWindows(AppContext appContext) {
1566         synchronized (Window.class) {
1567             Window[] realCopy;
1568             @SuppressWarnings("unchecked")
1569             Vector<WeakReference<Window>> windowList =
1570                 (Vector<WeakReference<Window>>)appContext.get(Window.class);
1571             if (windowList != null) {
1572                 int fullSize = windowList.size();
1573                 int realSize = 0;
1574                 Window[] fullCopy = new Window[fullSize];
1575                 for (int i = 0; i < fullSize; i++) {
1576                     Window w = windowList.get(i).get();
1577                     if (w != null) {
1578                         fullCopy[realSize++] = w;
1579                     }
1580                 }
1581                 if (fullSize != realSize) {
1582                     realCopy = Arrays.copyOf(fullCopy, realSize);
1583                 } else {
1584                     realCopy = fullCopy;
1585                 }
1586             } else {
1587                 realCopy = new Window[0];
1588             }
1589             return realCopy;
1590         }
1591     }
1592 
1593     /**
1594      * Returns an array of all {@code Window}s, both owned and ownerless,
1595      * created by this application.
1596      * If called from an applet, the array includes only the {@code Window}s
1597      * accessible by that applet.
1598      * <p>
1599      * <b>Warning:</b> this method may return system created windows, such
1600      * as a print dialog. Applications should not assume the existence of
1601      * these dialogs, nor should an application assume anything about these
1602      * dialogs such as component positions, {@code LayoutManager}s
1603      * or serialization.
1604      *
1605      * @return the array of all the {@code Window}s created by the application
1606      * @see Frame#getFrames
1607      * @see Window#getOwnerlessWindows
1608      *
1609      * @since 1.6
1610      */
1611     public static Window[] getWindows() {
1612         return getWindows(AppContext.getAppContext());
1613     }
1614 
1615     /**
1616      * Returns an array of all {@code Window}s created by this application
1617      * that have no owner. They include {@code Frame}s and ownerless
1618      * {@code Dialog}s and {@code Window}s.
1619      * If called from an applet, the array includes only the {@code Window}s
1620      * accessible by that applet.
1621      * <p>
1622      * <b>Warning:</b> this method may return system created windows, such
1623      * as a print dialog. Applications should not assume the existence of
1624      * these dialogs, nor should an application assume anything about these
1625      * dialogs such as component positions, {@code LayoutManager}s
1626      * or serialization.
1627      *
1628      * @return the array of all the ownerless {@code Window}s
1629      *         created by this application
1630      * @see Frame#getFrames
1631      * @see Window#getWindows()
1632      *
1633      * @since 1.6
1634      */
1635     public static Window[] getOwnerlessWindows() {
1636         Window[] allWindows = Window.getWindows();
1637 
1638         int ownerlessCount = 0;
1639         for (Window w : allWindows) {
1640             if (w.getOwner() == null) {
1641                 ownerlessCount++;
1642             }
1643         }
1644 
1645         Window[] ownerless = new Window[ownerlessCount];
1646         int c = 0;
1647         for (Window w : allWindows) {
1648             if (w.getOwner() == null) {
1649                 ownerless[c++] = w;
1650             }
1651         }
1652 
1653         return ownerless;
1654     }
1655 
1656     Window getDocumentRoot() {
1657         synchronized (getTreeLock()) {
1658             Window w = this;
1659             while (w.getOwner() != null) {
1660                 w = w.getOwner();
1661             }
1662             return w;
1663         }
1664     }
1665 
1666     /**
1667      * Specifies the modal exclusion type for this window. If a window is modal
1668      * excluded, it is not blocked by some modal dialogs. See {@link
1669      * java.awt.Dialog.ModalExclusionType Dialog.ModalExclusionType} for
1670      * possible modal exclusion types.
1671      * <p>
1672      * If the given type is not supported, {@code NO_EXCLUDE} is used.
1673      * <p>
1674      * Note: changing the modal exclusion type for a visible window may have no
1675      * effect until it is hidden and then shown again.
1676      *
1677      * @param exclusionType the modal exclusion type for this window; a {@code null}
1678      *     value is equivalent to {@link Dialog.ModalExclusionType#NO_EXCLUDE
1679      *     NO_EXCLUDE}
1680      * @throws SecurityException if the calling thread does not have permission
1681      *     to set the modal exclusion property to the window with the given
1682      *     {@code exclusionType}
1683      * @see java.awt.Dialog.ModalExclusionType
1684      * @see java.awt.Window#getModalExclusionType
1685      * @see java.awt.Toolkit#isModalExclusionTypeSupported
1686      *
1687      * @since 1.6
1688      */
1689     public void setModalExclusionType(Dialog.ModalExclusionType exclusionType) {
1690         if (exclusionType == null) {
1691             exclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
1692         }
1693         if (!Toolkit.getDefaultToolkit().isModalExclusionTypeSupported(exclusionType)) {
1694             exclusionType = Dialog.ModalExclusionType.NO_EXCLUDE;
1695         }
1696         if (modalExclusionType == exclusionType) {
1697             return;
1698         }
1699         if (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE) {
1700             SecurityManager sm = System.getSecurityManager();
1701             if (sm != null) {
1702                 sm.checkPermission(AWTPermissions.TOOLKIT_MODALITY_PERMISSION);
1703             }
1704         }
1705         modalExclusionType = exclusionType;
1706 
1707         // if we want on-fly changes, we need to uncomment the lines below
1708         //   and override the method in Dialog to use modalShow() instead
1709         //   of updateChildrenBlocking()
1710  /*
1711         if (isModalBlocked()) {
1712             modalBlocker.unblockWindow(this);
1713         }
1714         Dialog.checkShouldBeBlocked(this);
1715         updateChildrenBlocking();
1716  */
1717     }
1718 
1719     /**
1720      * Returns the modal exclusion type of this window.
1721      *
1722      * @return the modal exclusion type of this window
1723      *
1724      * @see java.awt.Dialog.ModalExclusionType
1725      * @see java.awt.Window#setModalExclusionType
1726      *
1727      * @since 1.6
1728      */
1729     public Dialog.ModalExclusionType getModalExclusionType() {
1730         return modalExclusionType;
1731     }
1732 
1733     boolean isModalExcluded(Dialog.ModalExclusionType exclusionType) {
1734         if ((modalExclusionType != null) &&
1735             modalExclusionType.compareTo(exclusionType) >= 0)
1736         {
1737             return true;
1738         }
1739         Window owner = getOwner_NoClientCode();
1740         return (owner != null) && owner.isModalExcluded(exclusionType);
1741     }
1742 
1743     void updateChildrenBlocking() {
1744         Vector<Window> childHierarchy = new Vector<Window>();
1745         Window[] ownedWindows = getOwnedWindows();
1746         for (int i = 0; i < ownedWindows.length; i++) {
1747             childHierarchy.add(ownedWindows[i]);
1748         }
1749         int k = 0;
1750         while (k < childHierarchy.size()) {
1751             Window w = childHierarchy.get(k);
1752             if (w.isVisible()) {
1753                 if (w.isModalBlocked()) {
1754                     Dialog blocker = w.getModalBlocker();
1755                     blocker.unblockWindow(w);
1756                 }
1757                 Dialog.checkShouldBeBlocked(w);
1758                 Window[] wOwned = w.getOwnedWindows();
1759                 for (int j = 0; j < wOwned.length; j++) {
1760                     childHierarchy.add(wOwned[j]);
1761                 }
1762             }
1763             k++;
1764         }
1765     }
1766 
1767     /**
1768      * Adds the specified window listener to receive window events from
1769      * this window.
1770      * If l is null, no exception is thrown and no action is performed.
1771      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1772      * >AWT Threading Issues</a> for details on AWT's threading model.
1773      *
1774      * @param   l the window listener
1775      * @see #removeWindowListener
1776      * @see #getWindowListeners
1777      */
1778     public synchronized void addWindowListener(WindowListener l) {
1779         if (l == null) {
1780             return;
1781         }
1782         newEventsOnly = true;
1783         windowListener = AWTEventMulticaster.add(windowListener, l);
1784     }
1785 
1786     /**
1787      * Adds the specified window state listener to receive window
1788      * events from this window.  If {@code l} is {@code null},
1789      * no exception is thrown and no action is performed.
1790      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1791      * >AWT Threading Issues</a> for details on AWT's threading model.
1792      *
1793      * @param   l the window state listener
1794      * @see #removeWindowStateListener
1795      * @see #getWindowStateListeners
1796      * @since 1.4
1797      */
1798     public synchronized void addWindowStateListener(WindowStateListener l) {
1799         if (l == null) {
1800             return;
1801         }
1802         windowStateListener = AWTEventMulticaster.add(windowStateListener, l);
1803         newEventsOnly = true;
1804     }
1805 
1806     /**
1807      * Adds the specified window focus listener to receive window events
1808      * from this window.
1809      * If l is null, no exception is thrown and no action is performed.
1810      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1811      * >AWT Threading Issues</a> for details on AWT's threading model.
1812      *
1813      * @param   l the window focus listener
1814      * @see #removeWindowFocusListener
1815      * @see #getWindowFocusListeners
1816      * @since 1.4
1817      */
1818     public synchronized void addWindowFocusListener(WindowFocusListener l) {
1819         if (l == null) {
1820             return;
1821         }
1822         windowFocusListener = AWTEventMulticaster.add(windowFocusListener, l);
1823         newEventsOnly = true;
1824     }
1825 
1826     /**
1827      * Removes the specified window listener so that it no longer
1828      * receives window events from this window.
1829      * If l is null, no exception is thrown and no action is performed.
1830      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1831      * >AWT Threading Issues</a> for details on AWT's threading model.
1832      *
1833      * @param   l the window listener
1834      * @see #addWindowListener
1835      * @see #getWindowListeners
1836      */
1837     public synchronized void removeWindowListener(WindowListener l) {
1838         if (l == null) {
1839             return;
1840         }
1841         windowListener = AWTEventMulticaster.remove(windowListener, l);
1842     }
1843 
1844     /**
1845      * Removes the specified window state listener so that it no
1846      * longer receives window events from this window.  If
1847      * {@code l} is {@code null}, no exception is thrown and
1848      * no action is performed.
1849      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1850      * >AWT Threading Issues</a> for details on AWT's threading model.
1851      *
1852      * @param   l the window state listener
1853      * @see #addWindowStateListener
1854      * @see #getWindowStateListeners
1855      * @since 1.4
1856      */
1857     public synchronized void removeWindowStateListener(WindowStateListener l) {
1858         if (l == null) {
1859             return;
1860         }
1861         windowStateListener = AWTEventMulticaster.remove(windowStateListener, l);
1862     }
1863 
1864     /**
1865      * Removes the specified window focus listener so that it no longer
1866      * receives window events from this window.
1867      * If l is null, no exception is thrown and no action is performed.
1868      * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
1869      * >AWT Threading Issues</a> for details on AWT's threading model.
1870      *
1871      * @param   l the window focus listener
1872      * @see #addWindowFocusListener
1873      * @see #getWindowFocusListeners
1874      * @since 1.4
1875      */
1876     public synchronized void removeWindowFocusListener(WindowFocusListener l) {
1877         if (l == null) {
1878             return;
1879         }
1880         windowFocusListener = AWTEventMulticaster.remove(windowFocusListener, l);
1881     }
1882 
1883     /**
1884      * Returns an array of all the window listeners
1885      * registered on this window.
1886      *
1887      * @return all of this window's {@code WindowListener}s
1888      *         or an empty array if no window
1889      *         listeners are currently registered
1890      *
1891      * @see #addWindowListener
1892      * @see #removeWindowListener
1893      * @since 1.4
1894      */
1895     public synchronized WindowListener[] getWindowListeners() {
1896         return getListeners(WindowListener.class);
1897     }
1898 
1899     /**
1900      * Returns an array of all the window focus listeners
1901      * registered on this window.
1902      *
1903      * @return all of this window's {@code WindowFocusListener}s
1904      *         or an empty array if no window focus
1905      *         listeners are currently registered
1906      *
1907      * @see #addWindowFocusListener
1908      * @see #removeWindowFocusListener
1909      * @since 1.4
1910      */
1911     public synchronized WindowFocusListener[] getWindowFocusListeners() {
1912         return getListeners(WindowFocusListener.class);
1913     }
1914 
1915     /**
1916      * Returns an array of all the window state listeners
1917      * registered on this window.
1918      *
1919      * @return all of this window's {@code WindowStateListener}s
1920      *         or an empty array if no window state
1921      *         listeners are currently registered
1922      *
1923      * @see #addWindowStateListener
1924      * @see #removeWindowStateListener
1925      * @since 1.4
1926      */
1927     public synchronized WindowStateListener[] getWindowStateListeners() {
1928         return getListeners(WindowStateListener.class);
1929     }
1930 
1931 
1932     /**
1933      * Returns an array of all the objects currently registered
1934      * as <code><em>Foo</em>Listener</code>s
1935      * upon this {@code Window}.
1936      * <code><em>Foo</em>Listener</code>s are registered using the
1937      * <code>add<em>Foo</em>Listener</code> method.
1938      *
1939      * <p>
1940      *
1941      * You can specify the {@code listenerType} argument
1942      * with a class literal, such as
1943      * <code><em>Foo</em>Listener.class</code>.
1944      * For example, you can query a
1945      * {@code Window w}
1946      * for its window listeners with the following code:
1947      *
1948      * <pre>WindowListener[] wls = (WindowListener[])(w.getListeners(WindowListener.class));</pre>
1949      *
1950      * If no such listeners exist, this method returns an empty array.
1951      *
1952      * @param listenerType the type of listeners requested; this parameter
1953      *          should specify an interface that descends from
1954      *          {@code java.util.EventListener}
1955      * @return an array of all objects registered as
1956      *          <code><em>Foo</em>Listener</code>s on this window,
1957      *          or an empty array if no such
1958      *          listeners have been added
1959      * @exception ClassCastException if {@code listenerType}
1960      *          doesn't specify a class or interface that implements
1961      *          {@code java.util.EventListener}
1962      * @exception NullPointerException if {@code listenerType} is {@code null}
1963      *
1964      * @see #getWindowListeners
1965      * @since 1.3
1966      */
1967     public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
1968         EventListener l = null;
1969         if (listenerType == WindowFocusListener.class) {
1970             l = windowFocusListener;
1971         } else if (listenerType == WindowStateListener.class) {
1972             l = windowStateListener;
1973         } else if (listenerType == WindowListener.class) {
1974             l = windowListener;
1975         } else {
1976             return super.getListeners(listenerType);
1977         }
1978         return AWTEventMulticaster.getListeners(l, listenerType);
1979     }
1980 
1981     // REMIND: remove when filtering is handled at lower level
1982     boolean eventEnabled(AWTEvent e) {
1983         switch(e.id) {
1984           case WindowEvent.WINDOW_OPENED:
1985           case WindowEvent.WINDOW_CLOSING:
1986           case WindowEvent.WINDOW_CLOSED:
1987           case WindowEvent.WINDOW_ICONIFIED:
1988           case WindowEvent.WINDOW_DEICONIFIED:
1989           case WindowEvent.WINDOW_ACTIVATED:
1990           case WindowEvent.WINDOW_DEACTIVATED:
1991             if ((eventMask & AWTEvent.WINDOW_EVENT_MASK) != 0 ||
1992                 windowListener != null) {
1993                 return true;
1994             }
1995             return false;
1996           case WindowEvent.WINDOW_GAINED_FOCUS:
1997           case WindowEvent.WINDOW_LOST_FOCUS:
1998             if ((eventMask & AWTEvent.WINDOW_FOCUS_EVENT_MASK) != 0 ||
1999                 windowFocusListener != null) {
2000                 return true;
2001             }
2002             return false;
2003           case WindowEvent.WINDOW_STATE_CHANGED:
2004             if ((eventMask & AWTEvent.WINDOW_STATE_EVENT_MASK) != 0 ||
2005                 windowStateListener != null) {
2006                 return true;
2007             }
2008             return false;
2009           default:
2010             break;
2011         }
2012         return super.eventEnabled(e);
2013     }
2014 
2015     /**
2016      * Processes events on this window. If the event is an
2017      * {@code WindowEvent}, it invokes the
2018      * {@code processWindowEvent} method, else it invokes its
2019      * superclass's {@code processEvent}.
2020      * <p>Note that if the event parameter is {@code null}
2021      * the behavior is unspecified and may result in an
2022      * exception.
2023      *
2024      * @param e the event
2025      */
2026     protected void processEvent(AWTEvent e) {
2027         if (e instanceof WindowEvent) {
2028             switch (e.getID()) {
2029                 case WindowEvent.WINDOW_OPENED:
2030                 case WindowEvent.WINDOW_CLOSING:
2031                 case WindowEvent.WINDOW_CLOSED:
2032                 case WindowEvent.WINDOW_ICONIFIED:
2033                 case WindowEvent.WINDOW_DEICONIFIED:
2034                 case WindowEvent.WINDOW_ACTIVATED:
2035                 case WindowEvent.WINDOW_DEACTIVATED:
2036                     processWindowEvent((WindowEvent)e);
2037                     break;
2038                 case WindowEvent.WINDOW_GAINED_FOCUS:
2039                 case WindowEvent.WINDOW_LOST_FOCUS:
2040                     processWindowFocusEvent((WindowEvent)e);
2041                     break;
2042                 case WindowEvent.WINDOW_STATE_CHANGED:
2043                     processWindowStateEvent((WindowEvent)e);
2044                     break;
2045             }
2046             return;
2047         }
2048         super.processEvent(e);
2049     }
2050 
2051     /**
2052      * Processes window events occurring on this window by
2053      * dispatching them to any registered WindowListener objects.
2054      * NOTE: This method will not be called unless window events
2055      * are enabled for this component; this happens when one of the
2056      * following occurs:
2057      * <ul>
2058      * <li>A WindowListener object is registered via
2059      *     {@code addWindowListener}
2060      * <li>Window events are enabled via {@code enableEvents}
2061      * </ul>
2062      * <p>Note that if the event parameter is {@code null}
2063      * the behavior is unspecified and may result in an
2064      * exception.
2065      *
2066      * @param e the window event
2067      * @see Component#enableEvents
2068      */
2069     protected void processWindowEvent(WindowEvent e) {
2070         WindowListener listener = windowListener;
2071         if (listener != null) {
2072             switch(e.getID()) {
2073                 case WindowEvent.WINDOW_OPENED:
2074                     listener.windowOpened(e);
2075                     break;
2076                 case WindowEvent.WINDOW_CLOSING:
2077                     listener.windowClosing(e);
2078                     break;
2079                 case WindowEvent.WINDOW_CLOSED:
2080                     listener.windowClosed(e);
2081                     break;
2082                 case WindowEvent.WINDOW_ICONIFIED:
2083                     listener.windowIconified(e);
2084                     break;
2085                 case WindowEvent.WINDOW_DEICONIFIED:
2086                     listener.windowDeiconified(e);
2087                     break;
2088                 case WindowEvent.WINDOW_ACTIVATED:
2089                     listener.windowActivated(e);
2090                     break;
2091                 case WindowEvent.WINDOW_DEACTIVATED:
2092                     listener.windowDeactivated(e);
2093                     break;
2094                 default:
2095                     break;
2096             }
2097         }
2098     }
2099 
2100     /**
2101      * Processes window focus event occurring on this window by
2102      * dispatching them to any registered WindowFocusListener objects.
2103      * NOTE: this method will not be called unless window focus events
2104      * are enabled for this window. This happens when one of the
2105      * following occurs:
2106      * <ul>
2107      * <li>a WindowFocusListener is registered via
2108      *     {@code addWindowFocusListener}
2109      * <li>Window focus events are enabled via {@code enableEvents}
2110      * </ul>
2111      * <p>Note that if the event parameter is {@code null}
2112      * the behavior is unspecified and may result in an
2113      * exception.
2114      *
2115      * @param e the window focus event
2116      * @see Component#enableEvents
2117      * @since 1.4
2118      */
2119     protected void processWindowFocusEvent(WindowEvent e) {
2120         WindowFocusListener listener = windowFocusListener;
2121         if (listener != null) {
2122             switch (e.getID()) {
2123                 case WindowEvent.WINDOW_GAINED_FOCUS:
2124                     listener.windowGainedFocus(e);
2125                     break;
2126                 case WindowEvent.WINDOW_LOST_FOCUS:
2127                     listener.windowLostFocus(e);
2128                     break;
2129                 default:
2130                     break;
2131             }
2132         }
2133     }
2134 
2135     /**
2136      * Processes window state event occurring on this window by
2137      * dispatching them to any registered {@code WindowStateListener}
2138      * objects.
2139      * NOTE: this method will not be called unless window state events
2140      * are enabled for this window.  This happens when one of the
2141      * following occurs:
2142      * <ul>
2143      * <li>a {@code WindowStateListener} is registered via
2144      *    {@code addWindowStateListener}
2145      * <li>window state events are enabled via {@code enableEvents}
2146      * </ul>
2147      * <p>Note that if the event parameter is {@code null}
2148      * the behavior is unspecified and may result in an
2149      * exception.
2150      *
2151      * @param e the window state event
2152      * @see java.awt.Component#enableEvents
2153      * @since 1.4
2154      */
2155     protected void processWindowStateEvent(WindowEvent e) {
2156         WindowStateListener listener = windowStateListener;
2157         if (listener != null) {
2158             switch (e.getID()) {
2159                 case WindowEvent.WINDOW_STATE_CHANGED:
2160                     listener.windowStateChanged(e);
2161                     break;
2162                 default:
2163                     break;
2164             }
2165         }
2166     }
2167 
2168     /**
2169      * Implements a debugging hook -- checks to see if
2170      * the user has typed <i>control-shift-F1</i>.  If so,
2171      * the list of child windows is dumped to {@code System.out}.
2172      * @param e  the keyboard event
2173      */
2174     void preProcessKeyEvent(KeyEvent e) {
2175         // Dump the list of child windows to System.out if debug is enabled.
2176         if (DebugSettings.getInstance().getBoolean("on", false)) {
2177             if (e.isActionKey() && e.getKeyCode() == KeyEvent.VK_F1 &&
2178                     e.isControlDown() && e.isShiftDown() &&
2179                     e.getID() == KeyEvent.KEY_PRESSED) {
2180                 list(System.out, 0);
2181             }
2182         }
2183     }
2184 
2185     void postProcessKeyEvent(KeyEvent e) {
2186         // Do nothing
2187     }
2188 
2189 
2190     /**
2191      * Sets whether this window should always be above other windows.  If
2192      * there are multiple always-on-top windows, their relative order is
2193      * unspecified and platform dependent.
2194      * <p>
2195      * If some other window is already always-on-top then the
2196      * relative order between these windows is unspecified (depends on
2197      * platform).  No window can be brought to be over the always-on-top
2198      * window except maybe another always-on-top window.
2199      * <p>
2200      * All windows owned by an always-on-top window inherit this state and
2201      * automatically become always-on-top.  If a window ceases to be
2202      * always-on-top, the windows that it owns will no longer be
2203      * always-on-top.  When an always-on-top window is sent {@link #toBack
2204      * toBack}, its always-on-top state is set to {@code false}.
2205      *
2206      * <p> When this method is called on a window with a value of
2207      * {@code true}, and the window is visible and the platform
2208      * supports always-on-top for this window, the window is immediately
2209      * brought forward, "sticking" it in the top-most position. If the
2210      * window isn`t currently visible, this method sets the always-on-top
2211      * state to {@code true} but does not bring the window forward.
2212      * When the window is later shown, it will be always-on-top.
2213      *
2214      * <p> When this method is called on a window with a value of
2215      * {@code false} the always-on-top state is set to normal. It may also
2216      * cause an unspecified, platform-dependent change in the z-order of
2217      * top-level windows, but other always-on-top windows will remain in
2218      * top-most position. Calling this method with a value of {@code false}
2219      * on a window that has a normal state has no effect.
2220      *
2221      * <p><b>Note</b>: some platforms might not support always-on-top
2222      * windows.  To detect if always-on-top windows are supported by the
2223      * current platform, use {@link Toolkit#isAlwaysOnTopSupported()} and
2224      * {@link Window#isAlwaysOnTopSupported()}.  If always-on-top mode
2225      * isn't supported for this window or this window's toolkit does not
2226      * support always-on-top windows, calling this method has no effect.
2227      * <p>
2228      * If a SecurityManager is installed, the calling thread must be
2229      * granted the AWTPermission "setWindowAlwaysOnTop" in
2230      * order to set the value of this property. If this
2231      * permission is not granted, this method will throw a
2232      * SecurityException, and the current value of the property will
2233      * be left unchanged.
2234      *
2235      * @param alwaysOnTop true if the window should always be above other
2236      *        windows
2237      * @throws SecurityException if the calling thread does not have
2238      *         permission to set the value of always-on-top property
2239      *
2240      * @see #isAlwaysOnTop
2241      * @see #toFront
2242      * @see #toBack
2243      * @see AWTPermission
2244      * @see #isAlwaysOnTopSupported
2245      * @see #getToolkit
2246      * @see Toolkit#isAlwaysOnTopSupported
2247      * @since 1.5
2248      */
2249     public final void setAlwaysOnTop(boolean alwaysOnTop) throws SecurityException {
2250         SecurityManager security = System.getSecurityManager();
2251         if (security != null) {
2252             security.checkPermission(AWTPermissions.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION);
2253         }
2254 
2255         boolean oldAlwaysOnTop;
2256         synchronized(this) {
2257             oldAlwaysOnTop = this.alwaysOnTop;
2258             this.alwaysOnTop = alwaysOnTop;
2259         }
2260         if (oldAlwaysOnTop != alwaysOnTop ) {
2261             if (isAlwaysOnTopSupported()) {
2262                 WindowPeer peer = (WindowPeer)this.peer;
2263                 synchronized(getTreeLock()) {
2264                     if (peer != null) {
2265                         peer.updateAlwaysOnTopState();
2266                     }
2267                 }
2268             }
2269             firePropertyChange("alwaysOnTop", oldAlwaysOnTop, alwaysOnTop);
2270         }
2271         setOwnedWindowsAlwaysOnTop(alwaysOnTop);
2272     }
2273 
2274     @SuppressWarnings({"rawtypes", "unchecked"})
2275     private void setOwnedWindowsAlwaysOnTop(boolean alwaysOnTop) {
2276         WeakReference<Window>[] ownedWindowArray;
2277         synchronized (ownedWindowList) {
2278             ownedWindowArray = new WeakReference[ownedWindowList.size()];
2279             ownedWindowList.copyInto(ownedWindowArray);
2280         }
2281 
2282         for (WeakReference<Window> ref : ownedWindowArray) {
2283             Window window = ref.get();
2284             if (window != null) {
2285                 try {
2286                     window.setAlwaysOnTop(alwaysOnTop);
2287                 } catch (SecurityException ignore) {
2288                 }
2289             }
2290         }
2291     }
2292 
2293     /**
2294      * Returns whether the always-on-top mode is supported for this
2295      * window. Some platforms may not support always-on-top windows, some
2296      * may support only some kinds of top-level windows; for example,
2297      * a platform may not support always-on-top modal dialogs.
2298      *
2299      * @return {@code true}, if the always-on-top mode is supported for
2300      *         this window and this window's toolkit supports always-on-top windows,
2301      *         {@code false} otherwise
2302      *
2303      * @see #setAlwaysOnTop(boolean)
2304      * @see #getToolkit
2305      * @see Toolkit#isAlwaysOnTopSupported
2306      * @since 1.6
2307      */
2308     public boolean isAlwaysOnTopSupported() {
2309         return Toolkit.getDefaultToolkit().isAlwaysOnTopSupported();
2310     }
2311 
2312 
2313     /**
2314      * Returns whether this window is an always-on-top window.
2315      * @return {@code true}, if the window is in always-on-top state,
2316      *         {@code false} otherwise
2317      * @see #setAlwaysOnTop
2318      * @since 1.5
2319      */
2320     public final boolean isAlwaysOnTop() {
2321         return alwaysOnTop;
2322     }
2323 
2324 
2325     /**
2326      * Returns the child Component of this Window that has focus if this Window
2327      * is focused; returns null otherwise.
2328      *
2329      * @return the child Component with focus, or null if this Window is not
2330      *         focused
2331      * @see #getMostRecentFocusOwner
2332      * @see #isFocused
2333      */
2334     public Component getFocusOwner() {
2335         return (isFocused())
2336             ? KeyboardFocusManager.getCurrentKeyboardFocusManager().
2337                   getFocusOwner()
2338             : null;
2339     }
2340 
2341     /**
2342      * Returns the child Component of this Window that will receive the focus
2343      * when this Window is focused. If this Window is currently focused, this
2344      * method returns the same Component as {@code getFocusOwner()}. If
2345      * this Window is not focused, then the child Component that most recently
2346      * requested focus will be returned. If no child Component has ever
2347      * requested focus, and this is a focusable Window, then this Window's
2348      * initial focusable Component is returned. If no child Component has ever
2349      * requested focus, and this is a non-focusable Window, null is returned.
2350      *
2351      * @return the child Component that will receive focus when this Window is
2352      *         focused
2353      * @see #getFocusOwner
2354      * @see #isFocused
2355      * @see #isFocusableWindow
2356      * @since 1.4
2357      */
2358     public Component getMostRecentFocusOwner() {
2359         if (isFocused()) {
2360             return getFocusOwner();
2361         } else {
2362             Component mostRecent =
2363                 KeyboardFocusManager.getMostRecentFocusOwner(this);
2364             if (mostRecent != null) {
2365                 return mostRecent;
2366             } else {
2367                 return (isFocusableWindow())
2368                     ? getFocusTraversalPolicy().getInitialComponent(this)
2369                     : null;
2370             }
2371         }
2372     }
2373 
2374     /**
2375      * Returns whether this Window is active. Only a Frame or a Dialog may be
2376      * active. The native windowing system may denote the active Window or its
2377      * children with special decorations, such as a highlighted title bar. The
2378      * active Window is always either the focused Window, or the first Frame or
2379      * Dialog that is an owner of the focused Window.
2380      *
2381      * @return whether this is the active Window.
2382      * @see #isFocused
2383      * @since 1.4
2384      */
2385     public boolean isActive() {
2386         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
2387                 getActiveWindow() == this);
2388     }
2389 
2390     /**
2391      * Returns whether this Window is focused. If there exists a focus owner,
2392      * the focused Window is the Window that is, or contains, that focus owner.
2393      * If there is no focus owner, then no Window is focused.
2394      * <p>
2395      * If the focused Window is a Frame or a Dialog it is also the active
2396      * Window. Otherwise, the active Window is the first Frame or Dialog that
2397      * is an owner of the focused Window.
2398      *
2399      * @return whether this is the focused Window.
2400      * @see #isActive
2401      * @since 1.4
2402      */
2403     public boolean isFocused() {
2404         return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
2405                 getGlobalFocusedWindow() == this);
2406     }
2407 
2408     /**
2409      * Gets a focus traversal key for this Window. (See {@code
2410      * setFocusTraversalKeys} for a full description of each key.)
2411      * <p>
2412      * If the traversal key has not been explicitly set for this Window,
2413      * then this Window's parent's traversal key is returned. If the
2414      * traversal key has not been explicitly set for any of this Window's
2415      * ancestors, then the current KeyboardFocusManager's default traversal key
2416      * is returned.
2417      *
2418      * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
2419      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
2420      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
2421      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
2422      * @return the AWTKeyStroke for the specified key
2423      * @see Container#setFocusTraversalKeys
2424      * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
2425      * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
2426      * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
2427      * @see KeyboardFocusManager#DOWN_CYCLE_TRAVERSAL_KEYS
2428      * @throws IllegalArgumentException if id is not one of
2429      *         KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
2430      *         KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
2431      *         KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or
2432      *         KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS
2433      * @since 1.4
2434      */
2435     @SuppressWarnings("unchecked")
2436     public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {
2437         if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH) {
2438             throw new IllegalArgumentException("invalid focus traversal key identifier");
2439         }
2440 
2441         // Okay to return Set directly because it is an unmodifiable view
2442         @SuppressWarnings("rawtypes")
2443         Set keystrokes = (focusTraversalKeys != null)
2444             ? focusTraversalKeys[id]
2445             : null;
2446 
2447         if (keystrokes != null) {
2448             return keystrokes;
2449         } else {
2450             return KeyboardFocusManager.getCurrentKeyboardFocusManager().
2451                 getDefaultFocusTraversalKeys(id);
2452         }
2453     }
2454 
2455     /**
2456      * Does nothing because Windows must always be roots of a focus traversal
2457      * cycle. The passed-in value is ignored.
2458      *
2459      * @param focusCycleRoot this value is ignored
2460      * @see #isFocusCycleRoot
2461      * @see Container#setFocusTraversalPolicy
2462      * @see Container#getFocusTraversalPolicy
2463      * @since 1.4
2464      */
2465     public final void setFocusCycleRoot(boolean focusCycleRoot) {
2466     }
2467 
2468     /**
2469      * Always returns {@code true} because all Windows must be roots of a
2470      * focus traversal cycle.
2471      *
2472      * @return {@code true}
2473      * @see #setFocusCycleRoot
2474      * @see Container#setFocusTraversalPolicy
2475      * @see Container#getFocusTraversalPolicy
2476      * @since 1.4
2477      */
2478     public final boolean isFocusCycleRoot() {
2479         return true;
2480     }
2481 
2482     /**
2483      * Always returns {@code null} because Windows have no ancestors; they
2484      * represent the top of the Component hierarchy.
2485      *
2486      * @return {@code null}
2487      * @see Container#isFocusCycleRoot()
2488      * @since 1.4
2489      */
2490     public final Container getFocusCycleRootAncestor() {
2491         return null;
2492     }
2493 
2494     /**
2495      * Returns whether this Window can become the focused Window, that is,
2496      * whether this Window or any of its subcomponents can become the focus
2497      * owner. For a Frame or Dialog to be focusable, its focusable Window state
2498      * must be set to {@code true}. For a Window which is not a Frame or
2499      * Dialog to be focusable, its focusable Window state must be set to
2500      * {@code true}, its nearest owning Frame or Dialog must be
2501      * showing on the screen, and it must contain at least one Component in
2502      * its focus traversal cycle. If any of these conditions is not met, then
2503      * neither this Window nor any of its subcomponents can become the focus
2504      * owner.
2505      *
2506      * @return {@code true} if this Window can be the focused Window;
2507      *         {@code false} otherwise
2508      * @see #getFocusableWindowState
2509      * @see #setFocusableWindowState
2510      * @see #isShowing
2511      * @see Component#isFocusable
2512      * @since 1.4
2513      */
2514     public final boolean isFocusableWindow() {
2515         // If a Window/Frame/Dialog was made non-focusable, then it is always
2516         // non-focusable.
2517         if (!getFocusableWindowState()) {
2518             return false;
2519         }
2520 
2521         // All other tests apply only to Windows.
2522         if (this instanceof Frame || this instanceof Dialog) {
2523             return true;
2524         }
2525 
2526         // A Window must have at least one Component in its root focus
2527         // traversal cycle to be focusable.
2528         if (getFocusTraversalPolicy().getDefaultComponent(this) == null) {
2529             return false;
2530         }
2531 
2532         // A Window's nearest owning Frame or Dialog must be showing on the
2533         // screen.
2534         for (Window owner = getOwner(); owner != null;
2535              owner = owner.getOwner())
2536         {
2537             if (owner instanceof Frame || owner instanceof Dialog) {
2538                 return owner.isShowing();
2539             }
2540         }
2541 
2542         return false;
2543     }
2544 
2545     /**
2546      * Returns whether this Window can become the focused Window if it meets
2547      * the other requirements outlined in {@code isFocusableWindow}. If
2548      * this method returns {@code false}, then
2549      * {@code isFocusableWindow} will return {@code false} as well.
2550      * If this method returns {@code true}, then
2551      * {@code isFocusableWindow} may return {@code true} or
2552      * {@code false} depending upon the other requirements which must be
2553      * met in order for a Window to be focusable.
2554      * <p>
2555      * By default, all Windows have a focusable Window state of
2556      * {@code true}.
2557      *
2558      * @return whether this Window can be the focused Window
2559      * @see #isFocusableWindow
2560      * @see #setFocusableWindowState
2561      * @see #isShowing
2562      * @see Component#setFocusable
2563      * @since 1.4
2564      */
2565     public boolean getFocusableWindowState() {
2566         return focusableWindowState;
2567     }
2568 
2569     /**
2570      * Sets whether this Window can become the focused Window if it meets
2571      * the other requirements outlined in {@code isFocusableWindow}. If
2572      * this Window's focusable Window state is set to {@code false}, then
2573      * {@code isFocusableWindow} will return {@code false}. If this
2574      * Window's focusable Window state is set to {@code true}, then
2575      * {@code isFocusableWindow} may return {@code true} or
2576      * {@code false} depending upon the other requirements which must be
2577      * met in order for a Window to be focusable.
2578      * <p>
2579      * Setting a Window's focusability state to {@code false} is the
2580      * standard mechanism for an application to identify to the AWT a Window
2581      * which will be used as a floating palette or toolbar, and thus should be
2582      * a non-focusable Window.
2583      *
2584      * Setting the focusability state on a visible {@code Window}
2585      * can have a delayed effect on some platforms — the actual
2586      * change may happen only when the {@code Window} becomes
2587      * hidden and then visible again.  To ensure consistent behavior
2588      * across platforms, set the {@code Window}'s focusable state
2589      * when the {@code Window} is invisible and then show it.
2590      *
2591      * @param focusableWindowState whether this Window can be the focused
2592      *        Window
2593      * @see #isFocusableWindow
2594      * @see #getFocusableWindowState
2595      * @see #isShowing
2596      * @see Component#setFocusable
2597      * @since 1.4
2598      */
2599     public void setFocusableWindowState(boolean focusableWindowState) {
2600         boolean oldFocusableWindowState;
2601         synchronized (this) {
2602             oldFocusableWindowState = this.focusableWindowState;
2603             this.focusableWindowState = focusableWindowState;
2604         }
2605         WindowPeer peer = (WindowPeer)this.peer;
2606         if (peer != null) {
2607             peer.updateFocusableWindowState();
2608         }
2609         firePropertyChange("focusableWindowState", oldFocusableWindowState,
2610                            focusableWindowState);
2611         if (oldFocusableWindowState && !focusableWindowState && isFocused()) {
2612             for (Window owner = getOwner();
2613                  owner != null;
2614                  owner = owner.getOwner())
2615                 {
2616                     Component toFocus =
2617                         KeyboardFocusManager.getMostRecentFocusOwner(owner);
2618                     if (toFocus != null && toFocus.requestFocus(false, FocusEvent.Cause.ACTIVATION)) {
2619                         return;
2620                     }
2621                 }
2622             KeyboardFocusManager.getCurrentKeyboardFocusManager().
2623                 clearGlobalFocusOwnerPriv();
2624         }
2625     }
2626 
2627     /**
2628      * Sets whether this window should receive focus on
2629      * subsequently being shown (with a call to {@link #setVisible setVisible(true)}),
2630      * or being moved to the front (with a call to {@link #toFront}).
2631      * <p>
2632      * Note that {@link #setVisible setVisible(true)} may be called indirectly
2633      * (e.g. when showing an owner of the window makes the window to be shown).
2634      * {@link #toFront} may also be called indirectly (e.g. when
2635      * {@link #setVisible setVisible(true)} is called on already visible window).
2636      * In all such cases this property takes effect as well.
2637      * <p>
2638      * The value of the property is not inherited by owned windows.
2639      *
2640      * @param autoRequestFocus whether this window should be focused on
2641      *        subsequently being shown or being moved to the front
2642      * @see #isAutoRequestFocus
2643      * @see #isFocusableWindow
2644      * @see #setVisible
2645      * @see #toFront
2646      * @since 1.7
2647      */
2648     public void setAutoRequestFocus(boolean autoRequestFocus) {
2649         this.autoRequestFocus = autoRequestFocus;
2650     }
2651 
2652     /**
2653      * Returns whether this window should receive focus on subsequently being shown
2654      * (with a call to {@link #setVisible setVisible(true)}), or being moved to the front
2655      * (with a call to {@link #toFront}).
2656      * <p>
2657      * By default, the window has {@code autoRequestFocus} value of {@code true}.
2658      *
2659      * @return {@code autoRequestFocus} value
2660      * @see #setAutoRequestFocus
2661      * @since 1.7
2662      */
2663     public boolean isAutoRequestFocus() {
2664         return autoRequestFocus;
2665     }
2666 
2667     /**
2668      * Adds a PropertyChangeListener to the listener list. The listener is
2669      * registered for all bound properties of this class, including the
2670      * following:
2671      * <ul>
2672      *    <li>this Window's font ("font")</li>
2673      *    <li>this Window's background color ("background")</li>
2674      *    <li>this Window's foreground color ("foreground")</li>
2675      *    <li>this Window's focusability ("focusable")</li>
2676      *    <li>this Window's focus traversal keys enabled state
2677      *        ("focusTraversalKeysEnabled")</li>
2678      *    <li>this Window's Set of FORWARD_TRAVERSAL_KEYS
2679      *        ("forwardFocusTraversalKeys")</li>
2680      *    <li>this Window's Set of BACKWARD_TRAVERSAL_KEYS
2681      *        ("backwardFocusTraversalKeys")</li>
2682      *    <li>this Window's Set of UP_CYCLE_TRAVERSAL_KEYS
2683      *        ("upCycleFocusTraversalKeys")</li>
2684      *    <li>this Window's Set of DOWN_CYCLE_TRAVERSAL_KEYS
2685      *        ("downCycleFocusTraversalKeys")</li>
2686      *    <li>this Window's focus traversal policy ("focusTraversalPolicy")
2687      *        </li>
2688      *    <li>this Window's focusable Window state ("focusableWindowState")
2689      *        </li>
2690      *    <li>this Window's always-on-top state("alwaysOnTop")</li>
2691      * </ul>
2692      * Note that if this Window is inheriting a bound property, then no
2693      * event will be fired in response to a change in the inherited property.
2694      * <p>
2695      * If listener is null, no exception is thrown and no action is performed.
2696      *
2697      * @param    listener  the PropertyChangeListener to be added
2698      *
2699      * @see Component#removePropertyChangeListener
2700      * @see #addPropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
2701      */
2702     public void addPropertyChangeListener(PropertyChangeListener listener) {
2703         super.addPropertyChangeListener(listener);
2704     }
2705 
2706     /**
2707      * Adds a PropertyChangeListener to the listener list for a specific
2708      * property. The specified property may be user-defined, or one of the
2709      * following:
2710      * <ul>
2711      *    <li>this Window's font ("font")</li>
2712      *    <li>this Window's background color ("background")</li>
2713      *    <li>this Window's foreground color ("foreground")</li>
2714      *    <li>this Window's focusability ("focusable")</li>
2715      *    <li>this Window's focus traversal keys enabled state
2716      *        ("focusTraversalKeysEnabled")</li>
2717      *    <li>this Window's Set of FORWARD_TRAVERSAL_KEYS
2718      *        ("forwardFocusTraversalKeys")</li>
2719      *    <li>this Window's Set of BACKWARD_TRAVERSAL_KEYS
2720      *        ("backwardFocusTraversalKeys")</li>
2721      *    <li>this Window's Set of UP_CYCLE_TRAVERSAL_KEYS
2722      *        ("upCycleFocusTraversalKeys")</li>
2723      *    <li>this Window's Set of DOWN_CYCLE_TRAVERSAL_KEYS
2724      *        ("downCycleFocusTraversalKeys")</li>
2725      *    <li>this Window's focus traversal policy ("focusTraversalPolicy")
2726      *        </li>
2727      *    <li>this Window's focusable Window state ("focusableWindowState")
2728      *        </li>
2729      *    <li>this Window's always-on-top state("alwaysOnTop")</li>
2730      * </ul>
2731      * Note that if this Window is inheriting a bound property, then no
2732      * event will be fired in response to a change in the inherited property.
2733      * <p>
2734      * If listener is null, no exception is thrown and no action is performed.
2735      *
2736      * @param propertyName one of the property names listed above
2737      * @param listener the PropertyChangeListener to be added
2738      *
2739      * @see #addPropertyChangeListener(java.beans.PropertyChangeListener)
2740      * @see Component#removePropertyChangeListener
2741      */
2742     public void addPropertyChangeListener(String propertyName,
2743                                           PropertyChangeListener listener) {
2744         super.addPropertyChangeListener(propertyName, listener);
2745     }
2746 
2747     /**
2748      * Indicates if this container is a validate root.
2749      * <p>
2750      * {@code Window} objects are the validate roots, and, therefore, they
2751      * override this method to return {@code true}.
2752      *
2753      * @return {@code true}
2754      * @since 1.7
2755      * @see java.awt.Container#isValidateRoot
2756      */
2757     @Override
2758     public boolean isValidateRoot() {
2759         return true;
2760     }
2761 
2762     /**
2763      * Dispatches an event to this window or one of its sub components.
2764      * @param e the event
2765      */
2766     void dispatchEventImpl(AWTEvent e) {
2767         if (e.getID() == ComponentEvent.COMPONENT_RESIZED) {
2768             invalidate();
2769             validate();
2770         }
2771         super.dispatchEventImpl(e);
2772     }
2773 
2774     /**
2775      * @deprecated As of JDK version 1.1
2776      * replaced by {@code dispatchEvent(AWTEvent)}.
2777      */
2778     @Deprecated
2779     public boolean postEvent(Event e) {
2780         if (handleEvent(e)) {
2781             e.consume();
2782             return true;
2783         }
2784         return false;
2785     }
2786 
2787     /**
2788      * Checks if this Window is showing on screen.
2789      * @see Component#setVisible
2790     */
2791     public boolean isShowing() {
2792         return visible;
2793     }
2794 
2795     boolean isDisposing() {
2796         return disposing;
2797     }
2798 
2799     /**
2800      * @deprecated As of J2SE 1.4, replaced by
2801      * {@link Component#applyComponentOrientation Component.applyComponentOrientation}.
2802      * @param rb the resource bundle
2803      */
2804     @Deprecated
2805     public void applyResourceBundle(ResourceBundle rb) {
2806         applyComponentOrientation(ComponentOrientation.getOrientation(rb));
2807     }
2808 
2809     /**
2810      * @deprecated As of J2SE 1.4, replaced by
2811      * {@link Component#applyComponentOrientation Component.applyComponentOrientation}.
2812      * @param rbName the resource name
2813      */
2814     @Deprecated
2815     public void applyResourceBundle(String rbName) {
2816         // Use the unnamed module from the TCCL or system class loader.
2817         ClassLoader cl = Thread.currentThread().getContextClassLoader();
2818         if (cl == null) {
2819             cl = ClassLoader.getSystemClassLoader();
2820         }
2821         applyResourceBundle(ResourceBundle.getBundle(rbName, cl.getUnnamedModule()));
2822     }
2823 
2824    /*
2825     * Support for tracking all windows owned by this window
2826     */
2827     void addOwnedWindow(WeakReference<Window> weakWindow) {
2828         if (weakWindow != null) {
2829             synchronized(ownedWindowList) {
2830                 // this if statement should really be an assert, but we don't
2831                 // have asserts...
2832                 if (!ownedWindowList.contains(weakWindow)) {
2833                     ownedWindowList.addElement(weakWindow);
2834                 }
2835             }
2836         }
2837     }
2838 
2839     void removeOwnedWindow(WeakReference<Window> weakWindow) {
2840         if (weakWindow != null) {
2841             // synchronized block not required since removeElement is
2842             // already synchronized
2843             ownedWindowList.removeElement(weakWindow);
2844         }
2845     }
2846 
2847     void connectOwnedWindow(Window child) {
2848         child.parent = this;
2849         addOwnedWindow(child.weakThis);
2850         child.disposerRecord.updateOwner();
2851     }
2852 
2853     private void addToWindowList() {
2854         synchronized (Window.class) {
2855             @SuppressWarnings("unchecked")
2856             Vector<WeakReference<Window>> windowList = (Vector<WeakReference<Window>>)appContext.get(Window.class);
2857             if (windowList == null) {
2858                 windowList = new Vector<WeakReference<Window>>();
2859                 appContext.put(Window.class, windowList);
2860             }
2861             windowList.add(weakThis);
2862         }
2863     }
2864 
2865     private static void removeFromWindowList(AppContext context, WeakReference<Window> weakThis) {
2866         synchronized (Window.class) {
2867             @SuppressWarnings("unchecked")
2868             Vector<WeakReference<Window>> windowList = (Vector<WeakReference<Window>>)context.get(Window.class);
2869             if (windowList != null) {
2870                 windowList.remove(weakThis);
2871             }
2872         }
2873     }
2874 
2875     private void removeFromWindowList() {
2876         removeFromWindowList(appContext, weakThis);
2877     }
2878 
2879     /**
2880      * Window type.
2881      *
2882      * Synchronization: ObjectLock
2883      */
2884     private Type type = Type.NORMAL;
2885 
2886     /**
2887      * Sets the type of the window.
2888      *
2889      * This method can only be called while the window is not displayable.
2890      *
2891      * @param  type the window type
2892      * @throws IllegalComponentStateException if the window
2893      *         is displayable.
2894      * @throws IllegalArgumentException if the type is {@code null}
2895      * @see    Component#isDisplayable
2896      * @see    #getType
2897      * @since 1.7
2898      */
2899     public void setType(Type type) {
2900         if (type == null) {
2901             throw new IllegalArgumentException("type should not be null.");
2902         }
2903         synchronized (getTreeLock()) {
2904             if (isDisplayable()) {
2905                 throw new IllegalComponentStateException(
2906                         "The window is displayable.");
2907             }
2908             synchronized (getObjectLock()) {
2909                 this.type = type;
2910             }
2911         }
2912     }
2913 
2914     /**
2915      * Returns the type of the window.
2916      *
2917      * @return the type of the window
2918      * @see   #setType
2919      * @since 1.7
2920      */
2921     public Type getType() {
2922         synchronized (getObjectLock()) {
2923             return type;
2924         }
2925     }
2926 
2927     /**
2928      * The window serialized data version.
2929      *
2930      * @serial
2931      */
2932     private int windowSerializedDataVersion = 2;
2933 
2934     /**
2935      * Writes default serializable fields to stream.  Writes
2936      * a list of serializable {@code WindowListener}s and
2937      * {@code WindowFocusListener}s as optional data.
2938      * Writes a list of child windows as optional data.
2939      * Writes a list of icon images as optional data
2940      *
2941      * @param s the {@code ObjectOutputStream} to write
2942      * @serialData {@code null} terminated sequence of
2943      *    0 or more pairs; the pair consists of a {@code String}
2944      *    and {@code Object}; the {@code String}
2945      *    indicates the type of object and is one of the following:
2946      *    {@code windowListenerK} indicating a
2947      *      {@code WindowListener} object;
2948      *    {@code windowFocusWindowK} indicating a
2949      *      {@code WindowFocusListener} object;
2950      *    {@code ownedWindowK} indicating a child
2951      *      {@code Window} object
2952      *
2953      * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
2954      * @see Component#windowListenerK
2955      * @see Component#windowFocusListenerK
2956      * @see Component#ownedWindowK
2957      * @see #readObject(ObjectInputStream)
2958      */
2959     private void writeObject(ObjectOutputStream s) throws IOException {
2960         synchronized (this) {
2961             // Update old focusMgr fields so that our object stream can be read
2962             // by previous releases
2963             focusMgr = new FocusManager();
2964             focusMgr.focusRoot = this;
2965             focusMgr.focusOwner = getMostRecentFocusOwner();
2966 
2967             s.defaultWriteObject();
2968 
2969             // Clear fields so that we don't keep extra references around
2970             focusMgr = null;
2971 
2972             AWTEventMulticaster.save(s, windowListenerK, windowListener);
2973             AWTEventMulticaster.save(s, windowFocusListenerK, windowFocusListener);
2974             AWTEventMulticaster.save(s, windowStateListenerK, windowStateListener);
2975         }
2976 
2977         s.writeObject(null);
2978 
2979         synchronized (ownedWindowList) {
2980             for (int i = 0; i < ownedWindowList.size(); i++) {
2981                 Window child = ownedWindowList.elementAt(i).get();
2982                 if (child != null) {
2983                     s.writeObject(ownedWindowK);
2984                     s.writeObject(child);
2985                 }
2986             }
2987         }
2988         s.writeObject(null);
2989 
2990         //write icon array
2991         if (icons != null) {
2992             for (Image i : icons) {
2993                 if (i instanceof Serializable) {
2994                     s.writeObject(i);
2995                 }
2996             }
2997         }
2998         s.writeObject(null);
2999     }
3000 
3001     //
3002     // Part of deserialization procedure to be called before
3003     // user's code.
3004     //
3005     private void initDeserializedWindow() {
3006         setWarningString();
3007         inputContextLock = new Object();
3008 
3009         // Deserialized Windows are not yet visible.
3010         visible = false;
3011 
3012         weakThis = new WeakReference<>(this);
3013 
3014         anchor = new Object();
3015         disposerRecord = new WindowDisposerRecord(appContext, this);
3016         sun.java2d.Disposer.addRecord(anchor, disposerRecord);
3017 
3018         addToWindowList();
3019         initGC(null);
3020         ownedWindowList = new Vector<>();
3021     }
3022 
3023     private void deserializeResources(ObjectInputStream s)
3024         throws ClassNotFoundException, IOException, HeadlessException {
3025 
3026             if (windowSerializedDataVersion < 2) {
3027                 // Translate old-style focus tracking to new model. For 1.4 and
3028                 // later releases, we'll rely on the Window's initial focusable
3029                 // Component.
3030                 if (focusMgr != null) {
3031                     if (focusMgr.focusOwner != null) {
3032                         KeyboardFocusManager.
3033                             setMostRecentFocusOwner(this, focusMgr.focusOwner);
3034                     }
3035                 }
3036 
3037                 // This field is non-transient and relies on default serialization.
3038                 // However, the default value is insufficient, so we need to set
3039                 // it explicitly for object data streams prior to 1.4.
3040                 focusableWindowState = true;
3041 
3042 
3043             }
3044 
3045         Object keyOrNull;
3046         while(null != (keyOrNull = s.readObject())) {
3047             String key = ((String)keyOrNull).intern();
3048 
3049             if (windowListenerK == key) {
3050                 addWindowListener((WindowListener)(s.readObject()));
3051             } else if (windowFocusListenerK == key) {
3052                 addWindowFocusListener((WindowFocusListener)(s.readObject()));
3053             } else if (windowStateListenerK == key) {
3054                 addWindowStateListener((WindowStateListener)(s.readObject()));
3055             } else // skip value for unrecognized key
3056                 s.readObject();
3057         }
3058 
3059         try {
3060             while (null != (keyOrNull = s.readObject())) {
3061                 String key = ((String)keyOrNull).intern();
3062 
3063                 if (ownedWindowK == key)
3064                     connectOwnedWindow((Window) s.readObject());
3065 
3066                 else // skip value for unrecognized key
3067                     s.readObject();
3068             }
3069 
3070             //read icons
3071             Object obj = s.readObject(); //Throws OptionalDataException
3072                                          //for pre1.6 objects.
3073             icons = new ArrayList<Image>(); //Frame.readObject() assumes
3074                                             //pre1.6 version if icons is null.
3075             while (obj != null) {
3076                 if (obj instanceof Image) {
3077                     icons.add((Image)obj);
3078                 }
3079                 obj = s.readObject();
3080             }
3081         }
3082         catch (OptionalDataException e) {
3083             // 1.1 serialized form
3084             // ownedWindowList will be updated by Frame.readObject
3085         }
3086 
3087     }
3088 
3089     /**
3090      * Reads the {@code ObjectInputStream} and an optional
3091      * list of listeners to receive various events fired by
3092      * the component; also reads a list of
3093      * (possibly {@code null}) child windows.
3094      * Unrecognized keys or values will be ignored.
3095      *
3096      * @param s the {@code ObjectInputStream} to read
3097      * @exception HeadlessException if
3098      *   {@code GraphicsEnvironment.isHeadless} returns
3099      *   {@code true}
3100      * @see java.awt.GraphicsEnvironment#isHeadless
3101      * @see #writeObject
3102      */
3103     private void readObject(ObjectInputStream s)
3104       throws ClassNotFoundException, IOException, HeadlessException
3105     {
3106          GraphicsEnvironment.checkHeadless();
3107          initDeserializedWindow();
3108          ObjectInputStream.GetField f = s.readFields();
3109 
3110          syncLWRequests = f.get("syncLWRequests", systemSyncLWRequests);
3111          state = f.get("state", 0);
3112          focusableWindowState = f.get("focusableWindowState", true);
3113          windowSerializedDataVersion = f.get("windowSerializedDataVersion", 1);
3114          locationByPlatform = f.get("locationByPlatform", locationByPlatformProp);
3115          // Note: 1.4 (or later) doesn't use focusMgr
3116          focusMgr = (FocusManager)f.get("focusMgr", null);
3117          Dialog.ModalExclusionType et = (Dialog.ModalExclusionType)
3118              f.get("modalExclusionType", Dialog.ModalExclusionType.NO_EXCLUDE);
3119          setModalExclusionType(et); // since 6.0
3120          boolean aot = f.get("alwaysOnTop", false);
3121          if(aot) {
3122              setAlwaysOnTop(aot); // since 1.5; subject to permission check
3123          }
3124          shape = (Shape)f.get("shape", null);
3125          opacity = (Float)f.get("opacity", 1.0f);
3126 
3127          this.securityWarningWidth = 0;
3128          this.securityWarningHeight = 0;
3129 
3130          deserializeResources(s);
3131     }
3132 
3133     /*
3134      * --- Accessibility Support ---
3135      *
3136      */
3137 
3138     /**
3139      * Gets the AccessibleContext associated with this Window.
3140      * For windows, the AccessibleContext takes the form of an
3141      * AccessibleAWTWindow.
3142      * A new AccessibleAWTWindow instance is created if necessary.
3143      *
3144      * @return an AccessibleAWTWindow that serves as the
3145      *         AccessibleContext of this Window
3146      * @since 1.3
3147      */
3148     public AccessibleContext getAccessibleContext() {
3149         if (accessibleContext == null) {
3150             accessibleContext = new AccessibleAWTWindow();
3151         }
3152         return accessibleContext;
3153     }
3154 
3155     /**
3156      * This class implements accessibility support for the
3157      * {@code Window} class.  It provides an implementation of the
3158      * Java Accessibility API appropriate to window user-interface elements.
3159      * @since 1.3
3160      */
3161     protected class AccessibleAWTWindow extends AccessibleAWTContainer
3162     {
3163         /*
3164          * JDK 1.3 serialVersionUID
3165          */
3166         private static final long serialVersionUID = 4215068635060671780L;
3167 
3168         /**
3169          * Get the role of this object.
3170          *
3171          * @return an instance of AccessibleRole describing the role of the
3172          * object
3173          * @see javax.accessibility.AccessibleRole
3174          */
3175         public AccessibleRole getAccessibleRole() {
3176             return AccessibleRole.WINDOW;
3177         }
3178 
3179         /**
3180          * Get the state of this object.
3181          *
3182          * @return an instance of AccessibleStateSet containing the current
3183          * state set of the object
3184          * @see javax.accessibility.AccessibleState
3185          */
3186         public AccessibleStateSet getAccessibleStateSet() {
3187             AccessibleStateSet states = super.getAccessibleStateSet();
3188             if (getFocusOwner() != null) {
3189                 states.add(AccessibleState.ACTIVE);
3190             }
3191             return states;
3192         }
3193 
3194     } // inner class AccessibleAWTWindow
3195 
3196     @Override
3197     void setGraphicsConfiguration(GraphicsConfiguration gc) {
3198         if (gc == null) {
3199             gc = GraphicsEnvironment.
3200                     getLocalGraphicsEnvironment().
3201                     getDefaultScreenDevice().
3202                     getDefaultConfiguration();
3203         }
3204         synchronized (getTreeLock()) {
3205             super.setGraphicsConfiguration(gc);
3206             if (log.isLoggable(PlatformLogger.Level.FINER)) {
3207                 log.finer("+ Window.setGraphicsConfiguration(): new GC is \n+ " + getGraphicsConfiguration_NoClientCode() + "\n+ this is " + this);
3208             }
3209         }
3210     }
3211 
3212     /**
3213      * Sets the location of the window relative to the specified
3214      * component according to the following scenarios.
3215      * <p>
3216      * The target screen mentioned below is a screen to which
3217      * the window should be placed after the setLocationRelativeTo
3218      * method is called.
3219      * <ul>
3220      * <li>If the component is {@code null}, or the {@code
3221      * GraphicsConfiguration} associated with this component is
3222      * {@code null}, the window is placed in the center of the
3223      * screen. The center point can be obtained with the {@link
3224      * GraphicsEnvironment#getCenterPoint
3225      * GraphicsEnvironment.getCenterPoint} method.
3226      * <li>If the component is not {@code null}, but it is not
3227      * currently showing, the window is placed in the center of
3228      * the target screen defined by the {@code
3229      * GraphicsConfiguration} associated with this component.
3230      * <li>If the component is not {@code null} and is shown on
3231      * the screen, then the window is located in such a way that
3232      * the center of the window coincides with the center of the
3233      * component.
3234      * </ul>
3235      * <p>
3236      * If the screens configuration does not allow the window to
3237      * be moved from one screen to another, then the window is
3238      * only placed at the location determined according to the
3239      * above conditions and its {@code GraphicsConfiguration} is
3240      * not changed.
3241      * <p>
3242      * <b>Note</b>: If the lower edge of the window is out of the screen,
3243      * then the window is placed to the side of the {@code Component}
3244      * that is closest to the center of the screen. So if the
3245      * component is on the right part of the screen, the window
3246      * is placed to its left, and vice versa.
3247      * <p>
3248      * If after the window location has been calculated, the upper,
3249      * left, or right edge of the window is out of the screen,
3250      * then the window is located in such a way that the upper,
3251      * left, or right edge of the window coincides with the
3252      * corresponding edge of the screen. If both left and right
3253      * edges of the window are out of the screen, the window is
3254      * placed at the left side of the screen. The similar placement
3255      * will occur if both top and bottom edges are out of the screen.
3256      * In that case, the window is placed at the top side of the screen.
3257      * <p>
3258      * The method changes the geometry-related data. Therefore,
3259      * the native windowing system may ignore such requests, or it may modify
3260      * the requested data, so that the {@code Window} object is placed and sized
3261      * in a way that corresponds closely to the desktop settings.
3262      *
3263      * @param c  the component in relation to which the window's location
3264      *           is determined
3265      * @see java.awt.GraphicsEnvironment#getCenterPoint
3266      * @since 1.4
3267      */
3268     public void setLocationRelativeTo(Component c) {
3269         // target location
3270         int dx = 0, dy = 0;
3271         // target GC
3272         GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
3273         Rectangle gcBounds = gc.getBounds();
3274 
3275         Dimension windowSize = getSize();
3276 
3277         // search a top-level of c
3278         Window componentWindow = SunToolkit.getContainingWindow(c);
3279         if ((c == null) || (componentWindow == null)) {
3280             GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
3281             gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
3282             gcBounds = gc.getBounds();
3283             Point centerPoint = ge.getCenterPoint();
3284             dx = centerPoint.x - windowSize.width / 2;
3285             dy = centerPoint.y - windowSize.height / 2;
3286         } else if (!c.isShowing()) {
3287             gc = componentWindow.getGraphicsConfiguration();
3288             gcBounds = gc.getBounds();
3289             dx = gcBounds.x + (gcBounds.width - windowSize.width) / 2;
3290             dy = gcBounds.y + (gcBounds.height - windowSize.height) / 2;
3291         } else {
3292             gc = componentWindow.getGraphicsConfiguration();
3293             gcBounds = gc.getBounds();
3294             Dimension compSize = c.getSize();
3295             Point compLocation = c.getLocationOnScreen();
3296             dx = compLocation.x + ((compSize.width - windowSize.width) / 2);
3297             dy = compLocation.y + ((compSize.height - windowSize.height) / 2);
3298 
3299             // Adjust for bottom edge being offscreen
3300             if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
3301                 dy = gcBounds.y + gcBounds.height - windowSize.height;
3302                 if (compLocation.x - gcBounds.x + compSize.width / 2 < gcBounds.width / 2) {
3303                     dx = compLocation.x + compSize.width;
3304                 } else {
3305                     dx = compLocation.x - windowSize.width;
3306                 }
3307             }
3308         }
3309 
3310         // Avoid being placed off the edge of the screen:
3311         // bottom
3312         if (dy + windowSize.height > gcBounds.y + gcBounds.height) {
3313             dy = gcBounds.y + gcBounds.height - windowSize.height;
3314         }
3315         // top
3316         if (dy < gcBounds.y) {
3317             dy = gcBounds.y;
3318         }
3319         // right
3320         if (dx + windowSize.width > gcBounds.x + gcBounds.width) {
3321             dx = gcBounds.x + gcBounds.width - windowSize.width;
3322         }
3323         // left
3324         if (dx < gcBounds.x) {
3325             dx = gcBounds.x;
3326         }
3327 
3328         setLocation(dx, dy);
3329     }
3330 
3331     /**
3332      * Overridden from Component.  Top-level Windows should not propagate a
3333      * MouseWheelEvent beyond themselves into their owning Windows.
3334      */
3335     void deliverMouseWheelToAncestor(MouseWheelEvent e) {}
3336 
3337     /**
3338      * Overridden from Component.  Top-level Windows don't dispatch to ancestors
3339      */
3340     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {return false;}
3341 
3342     /**
3343      * Creates a new strategy for multi-buffering on this component.
3344      * Multi-buffering is useful for rendering performance.  This method
3345      * attempts to create the best strategy available with the number of
3346      * buffers supplied.  It will always create a {@code BufferStrategy}
3347      * with that number of buffers.
3348      * A page-flipping strategy is attempted first, then a blitting strategy
3349      * using accelerated buffers.  Finally, an unaccelerated blitting
3350      * strategy is used.
3351      * <p>
3352      * Each time this method is called,
3353      * the existing buffer strategy for this component is discarded.
3354      * @param numBuffers number of buffers to create
3355      * @exception IllegalArgumentException if numBuffers is less than 1.
3356      * @exception IllegalStateException if the component is not displayable
3357      * @see #isDisplayable
3358      * @see #getBufferStrategy
3359      * @since 1.4
3360      */
3361     public void createBufferStrategy(int numBuffers) {
3362         super.createBufferStrategy(numBuffers);
3363     }
3364 
3365     /**
3366      * Creates a new strategy for multi-buffering on this component with the
3367      * required buffer capabilities.  This is useful, for example, if only
3368      * accelerated memory or page flipping is desired (as specified by the
3369      * buffer capabilities).
3370      * <p>
3371      * Each time this method
3372      * is called, the existing buffer strategy for this component is discarded.
3373      * @param numBuffers number of buffers to create, including the front buffer
3374      * @param caps the required capabilities for creating the buffer strategy;
3375      * cannot be {@code null}
3376      * @exception AWTException if the capabilities supplied could not be
3377      * supported or met; this may happen, for example, if there is not enough
3378      * accelerated memory currently available, or if page flipping is specified
3379      * but not possible.
3380      * @exception IllegalArgumentException if numBuffers is less than 1, or if
3381      * caps is {@code null}
3382      * @see #getBufferStrategy
3383      * @since 1.4
3384      */
3385     public void createBufferStrategy(int numBuffers,
3386         BufferCapabilities caps) throws AWTException {
3387         super.createBufferStrategy(numBuffers, caps);
3388     }
3389 
3390     /**
3391      * Returns the {@code BufferStrategy} used by this component.  This
3392      * method will return null if a {@code BufferStrategy} has not yet
3393      * been created or has been disposed.
3394      *
3395      * @return the buffer strategy used by this component
3396      * @see #createBufferStrategy
3397      * @since 1.4
3398      */
3399     public BufferStrategy getBufferStrategy() {
3400         return super.getBufferStrategy();
3401     }
3402 
3403     Component getTemporaryLostComponent() {
3404         return temporaryLostComponent;
3405     }
3406     Component setTemporaryLostComponent(Component component) {
3407         Component previousComp = temporaryLostComponent;
3408         // Check that "component" is an acceptable focus owner and don't store it otherwise
3409         // - or later we will have problems with opposite while handling  WINDOW_GAINED_FOCUS
3410         if (component == null || component.canBeFocusOwner()) {
3411             temporaryLostComponent = component;
3412         } else {
3413             temporaryLostComponent = null;
3414         }
3415         return previousComp;
3416     }
3417 
3418     /**
3419      * Checks whether this window can contain focus owner.
3420      * Verifies that it is focusable and as container it can container focus owner.
3421      * @since 1.5
3422      */
3423     boolean canContainFocusOwner(Component focusOwnerCandidate) {
3424         return super.canContainFocusOwner(focusOwnerCandidate) && isFocusableWindow();
3425     }
3426 
3427     private volatile boolean locationByPlatform = locationByPlatformProp;
3428 
3429 
3430     /**
3431      * Sets whether this Window should appear at the default location for the
3432      * native windowing system or at the current location (returned by
3433      * {@code getLocation}) the next time the Window is made visible.
3434      * This behavior resembles a native window shown without programmatically
3435      * setting its location.  Most windowing systems cascade windows if their
3436      * locations are not explicitly set. The actual location is determined once the
3437      * window is shown on the screen.
3438      * <p>
3439      * This behavior can also be enabled by setting the System Property
3440      * "java.awt.Window.locationByPlatform" to "true", though calls to this method
3441      * take precedence.
3442      * <p>
3443      * Calls to {@code setVisible}, {@code setLocation} and
3444      * {@code setBounds} after calling {@code setLocationByPlatform} clear
3445      * this property of the Window.
3446      * <p>
3447      * For example, after the following code is executed:
3448      * <pre>
3449      * setLocationByPlatform(true);
3450      * setVisible(true);
3451      * boolean flag = isLocationByPlatform();
3452      * </pre>
3453      * The window will be shown at platform's default location and
3454      * {@code flag} will be {@code false}.
3455      * <p>
3456      * In the following sample:
3457      * <pre>
3458      * setLocationByPlatform(true);
3459      * setLocation(10, 10);
3460      * boolean flag = isLocationByPlatform();
3461      * setVisible(true);
3462      * </pre>
3463      * The window will be shown at (10, 10) and {@code flag} will be
3464      * {@code false}.
3465      *
3466      * @param locationByPlatform {@code true} if this Window should appear
3467      *        at the default location, {@code false} if at the current location
3468      * @throws IllegalComponentStateException if the window
3469      *         is showing on screen and locationByPlatform is {@code true}.
3470      * @see #setLocation
3471      * @see #isShowing
3472      * @see #setVisible
3473      * @see #isLocationByPlatform
3474      * @see java.lang.System#getProperty(String)
3475      * @since 1.5
3476      */
3477     public void setLocationByPlatform(boolean locationByPlatform) {
3478         synchronized (getTreeLock()) {
3479             if (locationByPlatform && isShowing()) {
3480                 throw new IllegalComponentStateException("The window is showing on screen.");
3481             }
3482             this.locationByPlatform = locationByPlatform;
3483         }
3484     }
3485 
3486     /**
3487      * Returns {@code true} if this Window will appear at the default location
3488      * for the native windowing system the next time this Window is made visible.
3489      * This method always returns {@code false} if the Window is showing on the
3490      * screen.
3491      *
3492      * @return whether this Window will appear at the default location
3493      * @see #setLocationByPlatform
3494      * @see #isShowing
3495      * @since 1.5
3496      */
3497     public boolean isLocationByPlatform() {
3498         return locationByPlatform;
3499     }
3500 
3501     /**
3502      * {@inheritDoc}
3503      * <p>
3504      * The {@code width} or {@code height} values
3505      * are automatically enlarged if either is less than
3506      * the minimum size as specified by previous call to
3507      * {@code setMinimumSize}.
3508      * <p>
3509      * The method changes the geometry-related data. Therefore,
3510      * the native windowing system may ignore such requests, or it may modify
3511      * the requested data, so that the {@code Window} object is placed and sized
3512      * in a way that corresponds closely to the desktop settings.
3513      *
3514      * @see #getBounds
3515      * @see #setLocation(int, int)
3516      * @see #setLocation(Point)
3517      * @see #setSize(int, int)
3518      * @see #setSize(Dimension)
3519      * @see #setMinimumSize
3520      * @see #setLocationByPlatform
3521      * @see #isLocationByPlatform
3522      * @since 1.6
3523      */
3524     public void setBounds(int x, int y, int width, int height) {
3525         synchronized (getTreeLock()) {
3526             if (getBoundsOp() == ComponentPeer.SET_LOCATION ||
3527                 getBoundsOp() == ComponentPeer.SET_BOUNDS)
3528             {
3529                 locationByPlatform = false;
3530             }
3531             super.setBounds(x, y, width, height);
3532         }
3533     }
3534 
3535     /**
3536      * {@inheritDoc}
3537      * <p>
3538      * The {@code r.width} or {@code r.height} values
3539      * will be automatically enlarged if either is less than
3540      * the minimum size as specified by previous call to
3541      * {@code setMinimumSize}.
3542      * <p>
3543      * The method changes the geometry-related data. Therefore,
3544      * the native windowing system may ignore such requests, or it may modify
3545      * the requested data, so that the {@code Window} object is placed and sized
3546      * in a way that corresponds closely to the desktop settings.
3547      *
3548      * @see #getBounds
3549      * @see #setLocation(int, int)
3550      * @see #setLocation(Point)
3551      * @see #setSize(int, int)
3552      * @see #setSize(Dimension)
3553      * @see #setMinimumSize
3554      * @see #setLocationByPlatform
3555      * @see #isLocationByPlatform
3556      * @since 1.6
3557      */
3558     public void setBounds(Rectangle r) {
3559         setBounds(r.x, r.y, r.width, r.height);
3560     }
3561 
3562     /**
3563      * Determines whether this component will be displayed on the screen.
3564      * @return {@code true} if the component and all of its ancestors
3565      *          until a toplevel window are visible, {@code false} otherwise
3566      */
3567     boolean isRecursivelyVisible() {
3568         // 5079694 fix: for a toplevel to be displayed, its parent doesn't have to be visible.
3569         // We're overriding isRecursivelyVisible to implement this policy.
3570         return visible;
3571     }
3572 
3573 
3574     // ******************** SHAPES & TRANSPARENCY CODE ********************
3575 
3576     /**
3577      * Returns the opacity of the window.
3578      *
3579      * @return the opacity of the window
3580      *
3581      * @see Window#setOpacity(float)
3582      * @see GraphicsDevice.WindowTranslucency
3583      *
3584      * @since 1.7
3585      */
3586     public float getOpacity() {
3587         return opacity;
3588     }
3589 
3590     /**
3591      * Sets the opacity of the window.
3592      * <p>
3593      * The opacity value is in the range [0..1]. Note that setting the opacity
3594      * level of 0 may or may not disable the mouse event handling on this
3595      * window. This is a platform-dependent behavior.
3596      * <p>
3597      * The following conditions must be met in order to set the opacity value
3598      * less than {@code 1.0f}:
3599      * <ul>
3600      * <li>The {@link GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}
3601      * translucency must be supported by the underlying system
3602      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3603      * and {@link Dialog#setUndecorated})
3604      * <li>The window must not be in full-screen mode (see {@link
3605      * GraphicsDevice#setFullScreenWindow(Window)})
3606      * </ul>
3607      * <p>
3608      * If the requested opacity value is less than {@code 1.0f}, and any of the
3609      * above conditions are not met, the window opacity will not change,
3610      * and the {@code IllegalComponentStateException} will be thrown.
3611      * <p>
3612      * The translucency levels of individual pixels may also be effected by the
3613      * alpha component of their color (see {@link Window#setBackground(Color)}) and the
3614      * current shape of this window (see {@link #setShape(Shape)}).
3615      *
3616      * @param opacity the opacity level to set to the window
3617      *
3618      * @throws IllegalArgumentException if the opacity is out of the range
3619      *     [0..1]
3620      * @throws IllegalComponentStateException if the window is decorated and
3621      *     the opacity is less than {@code 1.0f}
3622      * @throws IllegalComponentStateException if the window is in full screen
3623      *     mode, and the opacity is less than {@code 1.0f}
3624      * @throws UnsupportedOperationException if the {@code
3625      *     GraphicsDevice.WindowTranslucency#TRANSLUCENT TRANSLUCENT}
3626      *     translucency is not supported and the opacity is less than
3627      *     {@code 1.0f}
3628      *
3629      * @see Window#getOpacity
3630      * @see Window#setBackground(Color)
3631      * @see Window#setShape(Shape)
3632      * @see Frame#isUndecorated
3633      * @see Dialog#isUndecorated
3634      * @see GraphicsDevice.WindowTranslucency
3635      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3636      *
3637      * @since 1.7
3638      */
3639     @SuppressWarnings("deprecation")
3640     public void setOpacity(float opacity) {
3641         synchronized (getTreeLock()) {
3642             if (opacity < 0.0f || opacity > 1.0f) {
3643                 throw new IllegalArgumentException(
3644                     "The value of opacity should be in the range [0.0f .. 1.0f].");
3645             }
3646             if (opacity < 1.0f) {
3647                 GraphicsConfiguration gc = getGraphicsConfiguration();
3648                 GraphicsDevice gd = gc.getDevice();
3649                 if (gc.getDevice().getFullScreenWindow() == this) {
3650                     throw new IllegalComponentStateException(
3651                         "Setting opacity for full-screen window is not supported.");
3652                 }
3653                 if (!gd.isWindowTranslucencySupported(
3654                     GraphicsDevice.WindowTranslucency.TRANSLUCENT))
3655                 {
3656                     throw new UnsupportedOperationException(
3657                         "TRANSLUCENT translucency is not supported.");
3658                 }
3659             }
3660             this.opacity = opacity;
3661             WindowPeer peer = (WindowPeer) this.peer;
3662             if (peer != null) {
3663                 peer.setOpacity(opacity);
3664             }
3665         }
3666     }
3667 
3668     /**
3669      * Returns the shape of the window.
3670      *
3671      * The value returned by this method may not be the same as
3672      * previously set with {@code setShape(shape)}, but it is guaranteed
3673      * to represent the same shape.
3674      *
3675      * @return the shape of the window or {@code null} if no
3676      *     shape is specified for the window
3677      *
3678      * @see Window#setShape(Shape)
3679      * @see GraphicsDevice.WindowTranslucency
3680      *
3681      * @since 1.7
3682      */
3683     public Shape getShape() {
3684         synchronized (getTreeLock()) {
3685             return shape == null ? null : new Path2D.Float(shape);
3686         }
3687     }
3688 
3689     /**
3690      * Sets the shape of the window.
3691      * <p>
3692      * Setting a shape cuts off some parts of the window. Only the parts that
3693      * belong to the given {@link Shape} remain visible and clickable. If
3694      * the shape argument is {@code null}, this method restores the default
3695      * shape, making the window rectangular on most platforms.
3696      * <p>
3697      * The following conditions must be met to set a non-null shape:
3698      * <ul>
3699      * <li>The {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSPARENT
3700      * PERPIXEL_TRANSPARENT} translucency must be supported by the
3701      * underlying system
3702      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3703      * and {@link Dialog#setUndecorated})
3704      * <li>The window must not be in full-screen mode (see {@link
3705      * GraphicsDevice#setFullScreenWindow(Window)})
3706      * </ul>
3707      * <p>
3708      * If the requested shape is not {@code null}, and any of the above
3709      * conditions are not met, the shape of this window will not change,
3710      * and either the {@code UnsupportedOperationException} or {@code
3711      * IllegalComponentStateException} will be thrown.
3712      * <p>
3713      * The translucency levels of individual pixels may also be effected by the
3714      * alpha component of their color (see {@link Window#setBackground(Color)}) and the
3715      * opacity value (see {@link #setOpacity(float)}). See {@link
3716      * GraphicsDevice.WindowTranslucency} for more details.
3717      *
3718      * @param shape the shape to set to the window
3719      *
3720      * @throws IllegalComponentStateException if the shape is not {@code
3721      *     null} and the window is decorated
3722      * @throws IllegalComponentStateException if the shape is not {@code
3723      *     null} and the window is in full-screen mode
3724      * @throws UnsupportedOperationException if the shape is not {@code
3725      *     null} and {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSPARENT
3726      *     PERPIXEL_TRANSPARENT} translucency is not supported
3727      *
3728      * @see Window#getShape()
3729      * @see Window#setBackground(Color)
3730      * @see Window#setOpacity(float)
3731      * @see Frame#isUndecorated
3732      * @see Dialog#isUndecorated
3733      * @see GraphicsDevice.WindowTranslucency
3734      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3735      *
3736      * @since 1.7
3737      */
3738     public void setShape(Shape shape) {
3739         synchronized (getTreeLock()) {
3740             if (shape != null) {
3741                 GraphicsConfiguration gc = getGraphicsConfiguration();
3742                 GraphicsDevice gd = gc.getDevice();
3743                 if (gc.getDevice().getFullScreenWindow() == this) {
3744                     throw new IllegalComponentStateException(
3745                         "Setting shape for full-screen window is not supported.");
3746                 }
3747                 if (!gd.isWindowTranslucencySupported(
3748                         GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT))
3749                 {
3750                     throw new UnsupportedOperationException(
3751                         "PERPIXEL_TRANSPARENT translucency is not supported.");
3752                 }
3753             }
3754             this.shape = (shape == null) ? null : new Path2D.Float(shape);
3755             WindowPeer peer = (WindowPeer) this.peer;
3756             if (peer != null) {
3757                 peer.applyShape(shape == null ? null : Region.getInstance(shape, null));
3758             }
3759         }
3760     }
3761 
3762     /**
3763      * Gets the background color of this window.
3764      * <p>
3765      * Note that the alpha component of the returned color indicates whether
3766      * the window is in the non-opaque (per-pixel translucent) mode.
3767      *
3768      * @return this component's background color
3769      *
3770      * @see Window#setBackground(Color)
3771      * @see Window#isOpaque
3772      * @see GraphicsDevice.WindowTranslucency
3773      */
3774     @Override
3775     public Color getBackground() {
3776         return super.getBackground();
3777     }
3778 
3779     /**
3780      * Sets the background color of this window.
3781      * <p>
3782      * If the windowing system supports the {@link
3783      * GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT PERPIXEL_TRANSLUCENT}
3784      * translucency, the alpha component of the given background color
3785      * may effect the mode of operation for this window: it indicates whether
3786      * this window must be opaque (alpha equals {@code 1.0f}) or per-pixel translucent
3787      * (alpha is less than {@code 1.0f}). If the given background color is
3788      * {@code null}, the window is considered completely opaque.
3789      * <p>
3790      * All the following conditions must be met to enable the per-pixel
3791      * transparency mode for this window:
3792      * <ul>
3793      * <li>The {@link GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
3794      * PERPIXEL_TRANSLUCENT} translucency must be supported by the graphics
3795      * device where this window is located
3796      * <li>The window must be undecorated (see {@link Frame#setUndecorated}
3797      * and {@link Dialog#setUndecorated})
3798      * <li>The window must not be in full-screen mode (see {@link
3799      * GraphicsDevice#setFullScreenWindow(Window)})
3800      * </ul>
3801      * <p>
3802      * If the alpha component of the requested background color is less than
3803      * {@code 1.0f}, and any of the above conditions are not met, the background
3804      * color of this window will not change, the alpha component of the given
3805      * background color will not affect the mode of operation for this window,
3806      * and either the {@code UnsupportedOperationException} or {@code
3807      * IllegalComponentStateException} will be thrown.
3808      * <p>
3809      * When the window is per-pixel translucent, the drawing sub-system
3810      * respects the alpha value of each individual pixel. If a pixel gets
3811      * painted with the alpha color component equal to zero, it becomes
3812      * visually transparent. If the alpha of the pixel is equal to 1.0f, the
3813      * pixel is fully opaque. Interim values of the alpha color component make
3814      * the pixel semi-transparent. In this mode, the background of the window
3815      * gets painted with the alpha value of the given background color. If the
3816      * alpha value of the argument of this method is equal to {@code 0}, the
3817      * background is not painted at all.
3818      * <p>
3819      * The actual level of translucency of a given pixel also depends on window
3820      * opacity (see {@link #setOpacity(float)}), as well as the current shape of
3821      * this window (see {@link #setShape(Shape)}).
3822      * <p>
3823      * Note that painting a pixel with the alpha value of {@code 0} may or may
3824      * not disable the mouse event handling on this pixel. This is a
3825      * platform-dependent behavior. To make sure the mouse events do not get
3826      * dispatched to a particular pixel, the pixel must be excluded from the
3827      * shape of the window.
3828      * <p>
3829      * Enabling the per-pixel translucency mode may change the graphics
3830      * configuration of this window due to the native platform requirements.
3831      *
3832      * @param bgColor the color to become this window's background color.
3833      *
3834      * @throws IllegalComponentStateException if the alpha value of the given
3835      *     background color is less than {@code 1.0f} and the window is decorated
3836      * @throws IllegalComponentStateException if the alpha value of the given
3837      *     background color is less than {@code 1.0f} and the window is in
3838      *     full-screen mode
3839      * @throws UnsupportedOperationException if the alpha value of the given
3840      *     background color is less than {@code 1.0f} and {@link
3841      *     GraphicsDevice.WindowTranslucency#PERPIXEL_TRANSLUCENT
3842      *     PERPIXEL_TRANSLUCENT} translucency is not supported
3843      *
3844      * @see Window#getBackground
3845      * @see Window#isOpaque
3846      * @see Window#setOpacity(float)
3847      * @see Window#setShape(Shape)
3848      * @see Frame#isUndecorated
3849      * @see Dialog#isUndecorated
3850      * @see GraphicsDevice.WindowTranslucency
3851      * @see GraphicsDevice#isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency)
3852      * @see GraphicsConfiguration#isTranslucencyCapable()
3853      */
3854     @Override
3855     public void setBackground(Color bgColor) {
3856         Color oldBg = getBackground();
3857         super.setBackground(bgColor);
3858         if (oldBg != null && oldBg.equals(bgColor)) {
3859             return;
3860         }
3861         int oldAlpha = oldBg != null ? oldBg.getAlpha() : 255;
3862         int alpha = bgColor != null ? bgColor.getAlpha() : 255;
3863         if ((oldAlpha == 255) && (alpha < 255)) { // non-opaque window
3864             GraphicsConfiguration gc = getGraphicsConfiguration();
3865             GraphicsDevice gd = gc.getDevice();
3866             if (gc.getDevice().getFullScreenWindow() == this) {
3867                 throw new IllegalComponentStateException(
3868                     "Making full-screen window non opaque is not supported.");
3869             }
3870             if (!gc.isTranslucencyCapable()) {
3871                 GraphicsConfiguration capableGC = gd.getTranslucencyCapableGC();
3872                 if (capableGC == null) {
3873                     throw new UnsupportedOperationException(
3874                         "PERPIXEL_TRANSLUCENT translucency is not supported");
3875                 }
3876                 setGraphicsConfiguration(capableGC);
3877             }
3878             setLayersOpaque(this, false);
3879         } else if ((oldAlpha < 255) && (alpha == 255)) {
3880             setLayersOpaque(this, true);
3881         }
3882         WindowPeer peer = (WindowPeer) this.peer;
3883         if (peer != null) {
3884             peer.setOpaque(alpha == 255);
3885         }
3886     }
3887 
3888     /**
3889      * Indicates if the window is currently opaque.
3890      * <p>
3891      * The method returns {@code false} if the background color of the window
3892      * is not {@code null} and the alpha component of the color is less than
3893      * {@code 1.0f}. The method returns {@code true} otherwise.
3894      *
3895      * @return {@code true} if the window is opaque, {@code false} otherwise
3896      *
3897      * @see Window#getBackground
3898      * @see Window#setBackground(Color)
3899      * @since 1.7
3900      */
3901     @Override
3902     public boolean isOpaque() {
3903         Color bg = getBackground();
3904         return bg != null ? bg.getAlpha() == 255 : true;
3905     }
3906 
3907     private void updateWindow() {
3908         synchronized (getTreeLock()) {
3909             WindowPeer peer = (WindowPeer) this.peer;
3910             if (peer != null) {
3911                 peer.updateWindow();
3912             }
3913         }
3914     }
3915 
3916     /**
3917      * {@inheritDoc}
3918      *
3919      * @since 1.7
3920      */
3921     @Override
3922     public void paint(Graphics g) {
3923         if (!isOpaque()) {
3924             Graphics gg = g.create();
3925             try {
3926                 if (gg instanceof Graphics2D) {
3927                     gg.setColor(getBackground());
3928                     ((Graphics2D)gg).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
3929                     gg.fillRect(0, 0, getWidth(), getHeight());
3930                 }
3931             } finally {
3932                 gg.dispose();
3933             }
3934         }
3935         super.paint(g);
3936     }
3937 
3938     private static void setLayersOpaque(Component component, boolean isOpaque) {
3939         // Shouldn't use instanceof to avoid loading Swing classes
3940         //    if it's a pure AWT application.
3941         if (SunToolkit.isInstanceOf(component, "javax.swing.RootPaneContainer")) {
3942             javax.swing.RootPaneContainer rpc = (javax.swing.RootPaneContainer)component;
3943             javax.swing.JRootPane root = rpc.getRootPane();
3944             javax.swing.JLayeredPane lp = root.getLayeredPane();
3945             Container c = root.getContentPane();
3946             javax.swing.JComponent content =
3947                 (c instanceof javax.swing.JComponent) ? (javax.swing.JComponent)c : null;
3948             lp.setOpaque(isOpaque);
3949             root.setOpaque(isOpaque);
3950             if (content != null) {
3951                 content.setOpaque(isOpaque);
3952 
3953                 // Iterate down one level to see whether we have a JApplet
3954                 // (which is also a RootPaneContainer) which requires processing
3955                 int numChildren = content.getComponentCount();
3956                 if (numChildren > 0) {
3957                     Component child = content.getComponent(0);
3958                     // It's OK to use instanceof here because we've
3959                     // already loaded the RootPaneContainer class by now
3960                     if (child instanceof javax.swing.RootPaneContainer) {
3961                         setLayersOpaque(child, isOpaque);
3962                     }
3963                 }
3964             }
3965         }
3966     }
3967 
3968 
3969     // ************************** MIXING CODE *******************************
3970 
3971     // A window has an owner, but it does NOT have a container
3972     @Override
3973     final Container getContainer() {
3974         return null;
3975     }
3976 
3977     /**
3978      * Applies the shape to the component
3979      * @param shape Shape to be applied to the component
3980      */
3981     @Override
3982     final void applyCompoundShape(Region shape) {
3983         // The shape calculated by mixing code is not intended to be applied
3984         // to windows or frames
3985     }
3986 
3987     @Override
3988     final void applyCurrentShape() {
3989         // The shape calculated by mixing code is not intended to be applied
3990         // to windows or frames
3991     }
3992 
3993     @Override
3994     final void mixOnReshaping() {
3995         // The shape calculated by mixing code is not intended to be applied
3996         // to windows or frames
3997     }
3998 
3999     @Override
4000     final Point getLocationOnWindow() {
4001         return new Point(0, 0);
4002     }
4003 
4004     // ****************** END OF MIXING CODE ********************************
4005 
4006     /**
4007      * Limit the given double value with the given range.
4008      */
4009     private static double limit(double value, double min, double max) {
4010         value = Math.max(value, min);
4011         value = Math.min(value, max);
4012         return value;
4013     }
4014 
4015     /**
4016      * Calculate the position of the security warning.
4017      *
4018      * This method gets the window location/size as reported by the native
4019      * system since the locally cached values may represent outdated data.
4020      *
4021      * The method is used from the native code, or via AWTAccessor.
4022      *
4023      * NOTE: this method is invoked on the toolkit thread, and therefore is not
4024      * supposed to become public/user-overridable.
4025      */
4026     private Point2D calculateSecurityWarningPosition(double x, double y,
4027             double w, double h)
4028     {
4029          // The desired location for the security warning
4030         double wx = x + w * RIGHT_ALIGNMENT + 2.0;
4031         double wy = y + h * TOP_ALIGNMENT + 0.0;
4032 
4033         // First, make sure the warning is not too far from the window bounds
4034         wx = Window.limit(wx,
4035                 x - securityWarningWidth - 2,
4036                 x + w + 2);
4037         wy = Window.limit(wy,
4038                 y - securityWarningHeight - 2,
4039                 y + h + 2);
4040 
4041         // Now make sure the warning window is visible on the screen
4042         GraphicsConfiguration graphicsConfig =
4043             getGraphicsConfiguration_NoClientCode();
4044         Rectangle screenBounds = graphicsConfig.getBounds();
4045         Insets screenInsets =
4046             Toolkit.getDefaultToolkit().getScreenInsets(graphicsConfig);
4047 
4048         wx = Window.limit(wx,
4049                 screenBounds.x + screenInsets.left,
4050                 screenBounds.x + screenBounds.width - screenInsets.right
4051                 - securityWarningWidth);
4052         wy = Window.limit(wy,
4053                 screenBounds.y + screenInsets.top,
4054                 screenBounds.y + screenBounds.height - screenInsets.bottom
4055                 - securityWarningHeight);
4056 
4057         return new Point2D.Double(wx, wy);
4058     }
4059 
4060     static {
4061         AWTAccessor.setWindowAccessor(new AWTAccessor.WindowAccessor() {
4062             public void updateWindow(Window window) {
4063                 window.updateWindow();
4064             }
4065 
4066             public void setSecurityWarningSize(Window window, int width, int height)
4067             {
4068                 window.securityWarningWidth = width;
4069                 window.securityWarningHeight = height;
4070             }
4071 
4072             public Point2D calculateSecurityWarningPosition(Window window,
4073                     double x, double y, double w, double h)
4074             {
4075                 return window.calculateSecurityWarningPosition(x, y, w, h);
4076             }
4077 
4078             public void setLWRequestStatus(Window changed, boolean status) {
4079                 changed.syncLWRequests = status;
4080             }
4081 
4082             public boolean isAutoRequestFocus(Window w) {
4083                 return w.autoRequestFocus;
4084             }
4085 
4086             public boolean isTrayIconWindow(Window w) {
4087                 return w.isTrayIconWindow;
4088             }
4089 
4090             public void setTrayIconWindow(Window w, boolean isTrayIconWindow) {
4091                 w.isTrayIconWindow = isTrayIconWindow;
4092             }
4093 
4094             public Window[] getOwnedWindows(Window w) {
4095                 return w.getOwnedWindows_NoClientCode();
4096             }
4097         }); // WindowAccessor
4098     } // static
4099 
4100     // a window doesn't need to be updated in the Z-order.
4101     @Override
4102     void updateZOrder() {}
4103 
4104 } // class Window
4105 
4106 
4107 /**
4108  * This class is no longer used, but is maintained for Serialization
4109  * backward-compatibility.
4110  */
4111 class FocusManager implements java.io.Serializable {
4112     Container focusRoot;
4113     Component focusOwner;
4114 
4115     /*
4116      * JDK 1.1 serialVersionUID
4117      */
4118     static final long serialVersionUID = 2491878825643557906L;
4119 }