Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/awt/Component.java
38829 views
/*1* Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/24package java.awt;2526import java.io.PrintStream;27import java.io.PrintWriter;28import java.util.Objects;29import java.util.Vector;30import java.util.Locale;31import java.util.EventListener;32import java.util.HashSet;33import java.util.Map;34import java.util.Set;35import java.util.Collections;36import java.awt.peer.ComponentPeer;37import java.awt.peer.ContainerPeer;38import java.awt.peer.LightweightPeer;39import java.awt.image.BufferStrategy;40import java.awt.image.ImageObserver;41import java.awt.image.ImageProducer;42import java.awt.image.ColorModel;43import java.awt.image.VolatileImage;44import java.awt.event.*;45import java.io.Serializable;46import java.io.ObjectOutputStream;47import java.io.ObjectInputStream;48import java.io.IOException;49import java.beans.PropertyChangeListener;50import java.beans.PropertyChangeSupport;51import java.beans.Transient;52import java.awt.im.InputContext;53import java.awt.im.InputMethodRequests;54import java.awt.dnd.DropTarget;55import java.lang.reflect.InvocationTargetException;56import java.lang.reflect.Method;57import java.security.AccessController;58import java.security.PrivilegedAction;59import java.security.AccessControlContext;60import javax.accessibility.*;61import java.applet.Applet;6263import sun.security.action.GetPropertyAction;64import sun.awt.AppContext;65import sun.awt.AWTAccessor;66import sun.awt.ConstrainableGraphics;67import sun.awt.SubRegionShowable;68import sun.awt.SunToolkit;69import sun.awt.WindowClosingListener;70import sun.awt.CausedFocusEvent;71import sun.awt.EmbeddedFrame;72import sun.awt.dnd.SunDropTargetEvent;73import sun.awt.im.CompositionArea;74import sun.font.FontManager;75import sun.font.FontManagerFactory;76import sun.font.SunFontManager;77import sun.java2d.SunGraphics2D;78import sun.java2d.pipe.Region;79import sun.awt.image.VSyncedBSManager;80import sun.java2d.pipe.hw.ExtendedBufferCapabilities;81import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;82import sun.awt.RequestFocusController;83import sun.java2d.SunGraphicsEnvironment;84import sun.util.logging.PlatformLogger;8586/**87* A <em>component</em> is an object having a graphical representation88* that can be displayed on the screen and that can interact with the89* user. Examples of components are the buttons, checkboxes, and scrollbars90* of a typical graphical user interface. <p>91* The <code>Component</code> class is the abstract superclass of92* the nonmenu-related Abstract Window Toolkit components. Class93* <code>Component</code> can also be extended directly to create a94* lightweight component. A lightweight component is a component that is95* not associated with a native window. On the contrary, a heavyweight96* component is associated with a native window. The {@link #isLightweight()}97* method may be used to distinguish between the two kinds of the components.98* <p>99* Lightweight and heavyweight components may be mixed in a single component100* hierarchy. However, for correct operating of such a mixed hierarchy of101* components, the whole hierarchy must be valid. When the hierarchy gets102* invalidated, like after changing the bounds of components, or103* adding/removing components to/from containers, the whole hierarchy must be104* validated afterwards by means of the {@link Container#validate()} method105* invoked on the top-most invalid container of the hierarchy.106*107* <h3>Serialization</h3>108* It is important to note that only AWT listeners which conform109* to the <code>Serializable</code> protocol will be saved when110* the object is stored. If an AWT object has listeners that111* aren't marked serializable, they will be dropped at112* <code>writeObject</code> time. Developers will need, as always,113* to consider the implications of making an object serializable.114* One situation to watch out for is this:115* <pre>116* import java.awt.*;117* import java.awt.event.*;118* import java.io.Serializable;119*120* class MyApp implements ActionListener, Serializable121* {122* BigObjectThatShouldNotBeSerializedWithAButton bigOne;123* Button aButton = new Button();124*125* MyApp()126* {127* // Oops, now aButton has a listener with a reference128* // to bigOne!129* aButton.addActionListener(this);130* }131*132* public void actionPerformed(ActionEvent e)133* {134* System.out.println("Hello There");135* }136* }137* </pre>138* In this example, serializing <code>aButton</code> by itself139* will cause <code>MyApp</code> and everything it refers to140* to be serialized as well. The problem is that the listener141* is serializable by coincidence, not by design. To separate142* the decisions about <code>MyApp</code> and the143* <code>ActionListener</code> being serializable one can use a144* nested class, as in the following example:145* <pre>146* import java.awt.*;147* import java.awt.event.*;148* import java.io.Serializable;149*150* class MyApp implements java.io.Serializable151* {152* BigObjectThatShouldNotBeSerializedWithAButton bigOne;153* Button aButton = new Button();154*155* static class MyActionListener implements ActionListener156* {157* public void actionPerformed(ActionEvent e)158* {159* System.out.println("Hello There");160* }161* }162*163* MyApp()164* {165* aButton.addActionListener(new MyActionListener());166* }167* }168* </pre>169* <p>170* <b>Note</b>: For more information on the paint mechanisms utilitized171* by AWT and Swing, including information on how to write the most172* efficient painting code, see173* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.174* <p>175* For details on the focus subsystem, see176* <a href="https://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">177* How to Use the Focus Subsystem</a>,178* a section in <em>The Java Tutorial</em>, and the179* <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>180* for more information.181*182* @author Arthur van Hoff183* @author Sami Shaio184*/185public abstract class Component implements ImageObserver, MenuContainer,186Serializable187{188189private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");190private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");191private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");192private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");193194/**195* The peer of the component. The peer implements the component's196* behavior. The peer is set when the <code>Component</code> is197* added to a container that also is a peer.198* @see #addNotify199* @see #removeNotify200*/201transient ComponentPeer peer;202203/**204* The parent of the object. It may be <code>null</code>205* for top-level components.206* @see #getParent207*/208transient Container parent;209210/**211* The <code>AppContext</code> of the component. Applets/Plugin may212* change the AppContext.213*/214transient AppContext appContext;215216/**217* The x position of the component in the parent's coordinate system.218*219* @serial220* @see #getLocation221*/222int x;223224/**225* The y position of the component in the parent's coordinate system.226*227* @serial228* @see #getLocation229*/230int y;231232/**233* The width of the component.234*235* @serial236* @see #getSize237*/238int width;239240/**241* The height of the component.242*243* @serial244* @see #getSize245*/246int height;247248/**249* The foreground color for this component.250* <code>foreground</code> can be <code>null</code>.251*252* @serial253* @see #getForeground254* @see #setForeground255*/256Color foreground;257258/**259* The background color for this component.260* <code>background</code> can be <code>null</code>.261*262* @serial263* @see #getBackground264* @see #setBackground265*/266Color background;267268/**269* The font used by this component.270* The <code>font</code> can be <code>null</code>.271*272* @serial273* @see #getFont274* @see #setFont275*/276volatile Font font;277278/**279* The font which the peer is currently using.280* (<code>null</code> if no peer exists.)281*/282Font peerFont;283284/**285* The cursor displayed when pointer is over this component.286* This value can be <code>null</code>.287*288* @serial289* @see #getCursor290* @see #setCursor291*/292Cursor cursor;293294/**295* The locale for the component.296*297* @serial298* @see #getLocale299* @see #setLocale300*/301Locale locale;302303/**304* A reference to a <code>GraphicsConfiguration</code> object305* used to describe the characteristics of a graphics306* destination.307* This value can be <code>null</code>.308*309* @since 1.3310* @serial311* @see GraphicsConfiguration312* @see #getGraphicsConfiguration313*/314private transient volatile GraphicsConfiguration graphicsConfig;315316/**317* A reference to a <code>BufferStrategy</code> object318* used to manipulate the buffers on this component.319*320* @since 1.4321* @see java.awt.image.BufferStrategy322* @see #getBufferStrategy()323*/324transient BufferStrategy bufferStrategy = null;325326/**327* True when the object should ignore all repaint events.328*329* @since 1.4330* @serial331* @see #setIgnoreRepaint332* @see #getIgnoreRepaint333*/334boolean ignoreRepaint = false;335336/**337* True when the object is visible. An object that is not338* visible is not drawn on the screen.339*340* @serial341* @see #isVisible342* @see #setVisible343*/344boolean visible = true;345346/**347* True when the object is enabled. An object that is not348* enabled does not interact with the user.349*350* @serial351* @see #isEnabled352* @see #setEnabled353*/354boolean enabled = true;355356/**357* True when the object is valid. An invalid object needs to358* be layed out. This flag is set to false when the object359* size is changed.360*361* @serial362* @see #isValid363* @see #validate364* @see #invalidate365*/366private volatile boolean valid = false;367368/**369* The <code>DropTarget</code> associated with this component.370*371* @since 1.2372* @serial373* @see #setDropTarget374* @see #getDropTarget375*/376DropTarget dropTarget;377378/**379* @serial380* @see #add381*/382Vector<PopupMenu> popups;383384/**385* A component's name.386* This field can be <code>null</code>.387*388* @serial389* @see #getName390* @see #setName(String)391*/392private String name;393394/**395* A bool to determine whether the name has396* been set explicitly. <code>nameExplicitlySet</code> will397* be false if the name has not been set and398* true if it has.399*400* @serial401* @see #getName402* @see #setName(String)403*/404private boolean nameExplicitlySet = false;405406/**407* Indicates whether this Component can be focused.408*409* @serial410* @see #setFocusable411* @see #isFocusable412* @since 1.4413*/414private boolean focusable = true;415416private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;417private static final int FOCUS_TRAVERSABLE_DEFAULT = 1;418private static final int FOCUS_TRAVERSABLE_SET = 2;419420/**421* Tracks whether this Component is relying on default focus travesability.422*423* @serial424* @since 1.4425*/426private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;427428/**429* The focus traversal keys. These keys will generate focus traversal430* behavior for Components for which focus traversal keys are enabled. If a431* value of null is specified for a traversal key, this Component inherits432* that traversal key from its parent. If all ancestors of this Component433* have null specified for that traversal key, then the current434* KeyboardFocusManager's default traversal key is used.435*436* @serial437* @see #setFocusTraversalKeys438* @see #getFocusTraversalKeys439* @since 1.4440*/441Set<AWTKeyStroke>[] focusTraversalKeys;442443private static final String[] focusTraversalKeyPropertyNames = {444"forwardFocusTraversalKeys",445"backwardFocusTraversalKeys",446"upCycleFocusTraversalKeys",447"downCycleFocusTraversalKeys"448};449450/**451* Indicates whether focus traversal keys are enabled for this Component.452* Components for which focus traversal keys are disabled receive key453* events for focus traversal keys. Components for which focus traversal454* keys are enabled do not see these events; instead, the events are455* automatically converted to traversal operations.456*457* @serial458* @see #setFocusTraversalKeysEnabled459* @see #getFocusTraversalKeysEnabled460* @since 1.4461*/462private boolean focusTraversalKeysEnabled = true;463464/**465* The locking object for AWT component-tree and layout operations.466*467* @see #getTreeLock468*/469static final Object LOCK = new AWTTreeLock();470static class AWTTreeLock {}471472/*473* The component's AccessControlContext.474*/475private transient volatile AccessControlContext acc =476AccessController.getContext();477478/**479* Minimum size.480* (This field perhaps should have been transient).481*482* @serial483*/484Dimension minSize;485486/**487* Whether or not setMinimumSize has been invoked with a non-null value.488*/489boolean minSizeSet;490491/**492* Preferred size.493* (This field perhaps should have been transient).494*495* @serial496*/497Dimension prefSize;498499/**500* Whether or not setPreferredSize has been invoked with a non-null value.501*/502boolean prefSizeSet;503504/**505* Maximum size506*507* @serial508*/509Dimension maxSize;510511/**512* Whether or not setMaximumSize has been invoked with a non-null value.513*/514boolean maxSizeSet;515516/**517* The orientation for this component.518* @see #getComponentOrientation519* @see #setComponentOrientation520*/521transient ComponentOrientation componentOrientation522= ComponentOrientation.UNKNOWN;523524/**525* <code>newEventsOnly</code> will be true if the event is526* one of the event types enabled for the component.527* It will then allow for normal processing to528* continue. If it is false the event is passed529* to the component's parent and up the ancestor530* tree until the event has been consumed.531*532* @serial533* @see #dispatchEvent534*/535boolean newEventsOnly = false;536transient ComponentListener componentListener;537transient FocusListener focusListener;538transient HierarchyListener hierarchyListener;539transient HierarchyBoundsListener hierarchyBoundsListener;540transient KeyListener keyListener;541transient MouseListener mouseListener;542transient MouseMotionListener mouseMotionListener;543transient MouseWheelListener mouseWheelListener;544transient InputMethodListener inputMethodListener;545546transient RuntimeException windowClosingException = null;547548/** Internal, constants for serialization */549final static String actionListenerK = "actionL";550final static String adjustmentListenerK = "adjustmentL";551final static String componentListenerK = "componentL";552final static String containerListenerK = "containerL";553final static String focusListenerK = "focusL";554final static String itemListenerK = "itemL";555final static String keyListenerK = "keyL";556final static String mouseListenerK = "mouseL";557final static String mouseMotionListenerK = "mouseMotionL";558final static String mouseWheelListenerK = "mouseWheelL";559final static String textListenerK = "textL";560final static String ownedWindowK = "ownedL";561final static String windowListenerK = "windowL";562final static String inputMethodListenerK = "inputMethodL";563final static String hierarchyListenerK = "hierarchyL";564final static String hierarchyBoundsListenerK = "hierarchyBoundsL";565final static String windowStateListenerK = "windowStateL";566final static String windowFocusListenerK = "windowFocusL";567568/**569* The <code>eventMask</code> is ONLY set by subclasses via570* <code>enableEvents</code>.571* The mask should NOT be set when listeners are registered572* so that we can distinguish the difference between when573* listeners request events and subclasses request them.574* One bit is used to indicate whether input methods are575* enabled; this bit is set by <code>enableInputMethods</code> and is576* on by default.577*578* @serial579* @see #enableInputMethods580* @see AWTEvent581*/582long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;583584/**585* Static properties for incremental drawing.586* @see #imageUpdate587*/588static boolean isInc;589static int incRate;590static {591/* ensure that the necessary native libraries are loaded */592Toolkit.loadLibraries();593/* initialize JNI field and method ids */594if (!GraphicsEnvironment.isHeadless()) {595initIDs();596}597598String s = java.security.AccessController.doPrivileged(599new GetPropertyAction("awt.image.incrementaldraw"));600isInc = (s == null || s.equals("true"));601602s = java.security.AccessController.doPrivileged(603new GetPropertyAction("awt.image.redrawrate"));604incRate = (s != null) ? Integer.parseInt(s) : 100;605}606607/**608* Ease-of-use constant for <code>getAlignmentY()</code>.609* Specifies an alignment to the top of the component.610* @see #getAlignmentY611*/612public static final float TOP_ALIGNMENT = 0.0f;613614/**615* Ease-of-use constant for <code>getAlignmentY</code> and616* <code>getAlignmentX</code>. Specifies an alignment to617* the center of the component618* @see #getAlignmentX619* @see #getAlignmentY620*/621public static final float CENTER_ALIGNMENT = 0.5f;622623/**624* Ease-of-use constant for <code>getAlignmentY</code>.625* Specifies an alignment to the bottom of the component.626* @see #getAlignmentY627*/628public static final float BOTTOM_ALIGNMENT = 1.0f;629630/**631* Ease-of-use constant for <code>getAlignmentX</code>.632* Specifies an alignment to the left side of the component.633* @see #getAlignmentX634*/635public static final float LEFT_ALIGNMENT = 0.0f;636637/**638* Ease-of-use constant for <code>getAlignmentX</code>.639* Specifies an alignment to the right side of the component.640* @see #getAlignmentX641*/642public static final float RIGHT_ALIGNMENT = 1.0f;643644/*645* JDK 1.1 serialVersionUID646*/647private static final long serialVersionUID = -7644114512714619750L;648649/**650* If any <code>PropertyChangeListeners</code> have been registered,651* the <code>changeSupport</code> field describes them.652*653* @serial654* @since 1.2655* @see #addPropertyChangeListener656* @see #removePropertyChangeListener657* @see #firePropertyChange658*/659private PropertyChangeSupport changeSupport;660661/*662* In some cases using "this" as an object to synchronize by663* can lead to a deadlock if client code also uses synchronization664* by a component object. For every such situation revealed we should665* consider possibility of replacing "this" with the package private666* objectLock object introduced below. So far there're 3 issues known:667* - CR 6708322 (the getName/setName methods);668* - CR 6608764 (the PropertyChangeListener machinery);669* - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods).670*671* Note: this field is considered final, though readObject() prohibits672* initializing final fields.673*/674private transient Object objectLock = new Object();675Object getObjectLock() {676return objectLock;677}678679/*680* Returns the acc this component was constructed with.681*/682final AccessControlContext getAccessControlContext() {683if (acc == null) {684throw new SecurityException("Component is missing AccessControlContext");685}686return acc;687}688689boolean isPacked = false;690691/**692* Pseudoparameter for direct Geometry API (setLocation, setBounds setSize693* to signal setBounds what's changing. Should be used under TreeLock.694* This is only needed due to the inability to change the cross-calling695* order of public and deprecated methods.696*/697private int boundsOp = ComponentPeer.DEFAULT_OPERATION;698699/**700* Enumeration of the common ways the baseline of a component can701* change as the size changes. The baseline resize behavior is702* primarily for layout managers that need to know how the703* position of the baseline changes as the component size changes.704* In general the baseline resize behavior will be valid for sizes705* greater than or equal to the minimum size (the actual minimum706* size; not a developer specified minimum size). For sizes707* smaller than the minimum size the baseline may change in a way708* other than the baseline resize behavior indicates. Similarly,709* as the size approaches <code>Integer.MAX_VALUE</code> and/or710* <code>Short.MAX_VALUE</code> the baseline may change in a way711* other than the baseline resize behavior indicates.712*713* @see #getBaselineResizeBehavior714* @see #getBaseline(int,int)715* @since 1.6716*/717public enum BaselineResizeBehavior {718/**719* Indicates the baseline remains fixed relative to the720* y-origin. That is, <code>getBaseline</code> returns721* the same value regardless of the height or width. For example, a722* <code>JLabel</code> containing non-empty text with a723* vertical alignment of <code>TOP</code> should have a724* baseline type of <code>CONSTANT_ASCENT</code>.725*/726CONSTANT_ASCENT,727728/**729* Indicates the baseline remains fixed relative to the height730* and does not change as the width is varied. That is, for731* any height H the difference between H and732* <code>getBaseline(w, H)</code> is the same. For example, a733* <code>JLabel</code> containing non-empty text with a734* vertical alignment of <code>BOTTOM</code> should have a735* baseline type of <code>CONSTANT_DESCENT</code>.736*/737CONSTANT_DESCENT,738739/**740* Indicates the baseline remains a fixed distance from741* the center of the component. That is, for any height H the742* difference between <code>getBaseline(w, H)</code> and743* <code>H / 2</code> is the same (plus or minus one depending upon744* rounding error).745* <p>746* Because of possible rounding errors it is recommended747* you ask for the baseline with two consecutive heights and use748* the return value to determine if you need to pad calculations749* by 1. The following shows how to calculate the baseline for750* any height:751* <pre>752* Dimension preferredSize = component.getPreferredSize();753* int baseline = getBaseline(preferredSize.width,754* preferredSize.height);755* int nextBaseline = getBaseline(preferredSize.width,756* preferredSize.height + 1);757* // Amount to add to height when calculating where baseline758* // lands for a particular height:759* int padding = 0;760* // Where the baseline is relative to the mid point761* int baselineOffset = baseline - height / 2;762* if (preferredSize.height % 2 == 0 &&763* baseline != nextBaseline) {764* padding = 1;765* }766* else if (preferredSize.height % 2 == 1 &&767* baseline == nextBaseline) {768* baselineOffset--;769* padding = 1;770* }771* // The following calculates where the baseline lands for772* // the height z:773* int calculatedBaseline = (z + padding) / 2 + baselineOffset;774* </pre>775*/776CENTER_OFFSET,777778/**779* Indicates the baseline resize behavior can not be expressed using780* any of the other constants. This may also indicate the baseline781* varies with the width of the component. This is also returned782* by components that do not have a baseline.783*/784OTHER785}786787/*788* The shape set with the applyCompoundShape() method. It uncludes the result789* of the HW/LW mixing related shape computation. It may also include790* the user-specified shape of the component.791* The 'null' value means the component has normal shape (or has no shape at all)792* and applyCompoundShape() will skip the following shape identical to normal.793*/794private transient Region compoundShape = null;795796/*797* Represents the shape of this lightweight component to be cut out from798* heavyweight components should they intersect. Possible values:799* 1. null - consider the shape rectangular800* 2. EMPTY_REGION - nothing gets cut out (children still get cut out)801* 3. non-empty - this shape gets cut out.802*/803private transient Region mixingCutoutRegion = null;804805/*806* Indicates whether addNotify() is complete807* (i.e. the peer is created).808*/809private transient boolean isAddNotifyComplete = false;810811/**812* Should only be used in subclass getBounds to check that part of bounds813* is actualy changing814*/815int getBoundsOp() {816assert Thread.holdsLock(getTreeLock());817return boundsOp;818}819820void setBoundsOp(int op) {821assert Thread.holdsLock(getTreeLock());822if (op == ComponentPeer.RESET_OPERATION) {823boundsOp = ComponentPeer.DEFAULT_OPERATION;824} else825if (boundsOp == ComponentPeer.DEFAULT_OPERATION) {826boundsOp = op;827}828}829830// Whether this Component has had the background erase flag831// specified via SunToolkit.disableBackgroundErase(). This is832// needed in order to make this function work on X11 platforms,833// where currently there is no chance to interpose on the creation834// of the peer and therefore the call to XSetBackground.835transient boolean backgroundEraseDisabled;836837static {838AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() {839public void setBackgroundEraseDisabled(Component comp, boolean disabled) {840comp.backgroundEraseDisabled = disabled;841}842public boolean getBackgroundEraseDisabled(Component comp) {843return comp.backgroundEraseDisabled;844}845public Rectangle getBounds(Component comp) {846return new Rectangle(comp.x, comp.y, comp.width, comp.height);847}848public void setMixingCutoutShape(Component comp, Shape shape) {849Region region = shape == null ? null :850Region.getInstance(shape, null);851852synchronized (comp.getTreeLock()) {853boolean needShowing = false;854boolean needHiding = false;855856if (!comp.isNonOpaqueForMixing()) {857needHiding = true;858}859860comp.mixingCutoutRegion = region;861862if (!comp.isNonOpaqueForMixing()) {863needShowing = true;864}865866if (comp.isMixingNeeded()) {867if (needHiding) {868comp.mixOnHiding(comp.isLightweight());869}870if (needShowing) {871comp.mixOnShowing();872}873}874}875}876877public void setGraphicsConfiguration(Component comp,878GraphicsConfiguration gc)879{880comp.setGraphicsConfiguration(gc);881}882public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) {883return comp.requestFocus(cause);884}885public boolean canBeFocusOwner(Component comp) {886return comp.canBeFocusOwner();887}888889public boolean isVisible(Component comp) {890return comp.isVisible_NoClientCode();891}892public void setRequestFocusController893(RequestFocusController requestController)894{895Component.setRequestFocusController(requestController);896}897public AppContext getAppContext(Component comp) {898return comp.appContext;899}900public void setAppContext(Component comp, AppContext appContext) {901comp.appContext = appContext;902}903public Container getParent(Component comp) {904return comp.getParent_NoClientCode();905}906public void setParent(Component comp, Container parent) {907comp.parent = parent;908}909public void setSize(Component comp, int width, int height) {910comp.width = width;911comp.height = height;912}913public Point getLocation(Component comp) {914return comp.location_NoClientCode();915}916public void setLocation(Component comp, int x, int y) {917comp.x = x;918comp.y = y;919}920public boolean isEnabled(Component comp) {921return comp.isEnabledImpl();922}923public boolean isDisplayable(Component comp) {924return comp.peer != null;925}926public Cursor getCursor(Component comp) {927return comp.getCursor_NoClientCode();928}929public ComponentPeer getPeer(Component comp) {930return comp.peer;931}932public void setPeer(Component comp, ComponentPeer peer) {933comp.peer = peer;934}935public boolean isLightweight(Component comp) {936return (comp.peer instanceof LightweightPeer);937}938public boolean getIgnoreRepaint(Component comp) {939return comp.ignoreRepaint;940}941public int getWidth(Component comp) {942return comp.width;943}944public int getHeight(Component comp) {945return comp.height;946}947public int getX(Component comp) {948return comp.x;949}950public int getY(Component comp) {951return comp.y;952}953public Color getForeground(Component comp) {954return comp.foreground;955}956public Color getBackground(Component comp) {957return comp.background;958}959public void setBackground(Component comp, Color background) {960comp.background = background;961}962public Font getFont(Component comp) {963return comp.getFont_NoClientCode();964}965public void processEvent(Component comp, AWTEvent e) {966comp.processEvent(e);967}968969public AccessControlContext getAccessControlContext(Component comp) {970return comp.getAccessControlContext();971}972973public void revalidateSynchronously(Component comp) {974comp.revalidateSynchronously();975}976});977}978979/**980* Constructs a new component. Class <code>Component</code> can be981* extended directly to create a lightweight component that does not982* utilize an opaque native window. A lightweight component must be983* hosted by a native container somewhere higher up in the component984* tree (for example, by a <code>Frame</code> object).985*/986protected Component() {987appContext = AppContext.getAppContext();988}989990@SuppressWarnings({"rawtypes", "unchecked"})991void initializeFocusTraversalKeys() {992focusTraversalKeys = new Set[3];993}994995/**996* Constructs a name for this component. Called by <code>getName</code>997* when the name is <code>null</code>.998*/999String constructComponentName() {1000return null; // For strict compliance with prior platform versions, a Component1001// that doesn't set its name should return null from1002// getName()1003}10041005/**1006* Gets the name of the component.1007* @return this component's name1008* @see #setName1009* @since JDK1.11010*/1011public String getName() {1012if (name == null && !nameExplicitlySet) {1013synchronized(getObjectLock()) {1014if (name == null && !nameExplicitlySet)1015name = constructComponentName();1016}1017}1018return name;1019}10201021/**1022* Sets the name of the component to the specified string.1023* @param name the string that is to be this1024* component's name1025* @see #getName1026* @since JDK1.11027*/1028public void setName(String name) {1029String oldName;1030synchronized(getObjectLock()) {1031oldName = this.name;1032this.name = name;1033nameExplicitlySet = true;1034}1035firePropertyChange("name", oldName, name);1036}10371038/**1039* Gets the parent of this component.1040* @return the parent container of this component1041* @since JDK1.01042*/1043public Container getParent() {1044return getParent_NoClientCode();1045}10461047// NOTE: This method may be called by privileged threads.1048// This functionality is implemented in a package-private method1049// to insure that it cannot be overridden by client subclasses.1050// DO NOT INVOKE CLIENT CODE ON THIS THREAD!1051final Container getParent_NoClientCode() {1052return parent;1053}10541055// This method is overridden in the Window class to return null,1056// because the parent field of the Window object contains1057// the owner of the window, not its parent.1058Container getContainer() {1059return getParent_NoClientCode();1060}10611062/**1063* @deprecated As of JDK version 1.1,1064* programs should not directly manipulate peers;1065* replaced by <code>boolean isDisplayable()</code>.1066*/1067@Deprecated1068public ComponentPeer getPeer() {1069return peer;1070}10711072/**1073* Associate a <code>DropTarget</code> with this component.1074* The <code>Component</code> will receive drops only if it1075* is enabled.1076*1077* @see #isEnabled1078* @param dt The DropTarget1079*/10801081public synchronized void setDropTarget(DropTarget dt) {1082if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))1083return;10841085DropTarget old;10861087if ((old = dropTarget) != null) {1088if (peer != null) dropTarget.removeNotify(peer);10891090DropTarget t = dropTarget;10911092dropTarget = null;10931094try {1095t.setComponent(null);1096} catch (IllegalArgumentException iae) {1097// ignore it.1098}1099}11001101// if we have a new one, and we have a peer, add it!11021103if ((dropTarget = dt) != null) {1104try {1105dropTarget.setComponent(this);1106if (peer != null) dropTarget.addNotify(peer);1107} catch (IllegalArgumentException iae) {1108if (old != null) {1109try {1110old.setComponent(this);1111if (peer != null) dropTarget.addNotify(peer);1112} catch (IllegalArgumentException iae1) {1113// ignore it!1114}1115}1116}1117}1118}11191120/**1121* Gets the <code>DropTarget</code> associated with this1122* <code>Component</code>.1123*/11241125public synchronized DropTarget getDropTarget() { return dropTarget; }11261127/**1128* Gets the <code>GraphicsConfiguration</code> associated with this1129* <code>Component</code>.1130* If the <code>Component</code> has not been assigned a specific1131* <code>GraphicsConfiguration</code>,1132* the <code>GraphicsConfiguration</code> of the1133* <code>Component</code> object's top-level container is1134* returned.1135* If the <code>Component</code> has been created, but not yet added1136* to a <code>Container</code>, this method returns <code>null</code>.1137*1138* @return the <code>GraphicsConfiguration</code> used by this1139* <code>Component</code> or <code>null</code>1140* @since 1.31141*/1142public GraphicsConfiguration getGraphicsConfiguration() {1143return getGraphicsConfiguration_NoClientCode();1144}11451146final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {1147return graphicsConfig;1148}11491150void setGraphicsConfiguration(GraphicsConfiguration gc) {1151synchronized(getTreeLock()) {1152if (updateGraphicsData(gc)) {1153removeNotify();1154addNotify();1155}1156}1157}11581159boolean updateGraphicsData(GraphicsConfiguration gc) {1160checkTreeLock();11611162if (graphicsConfig == gc) {1163return false;1164}11651166graphicsConfig = gc;11671168ComponentPeer peer = getPeer();1169if (peer != null) {1170return peer.updateGraphicsData(gc);1171}1172return false;1173}11741175/**1176* Checks that this component's <code>GraphicsDevice</code>1177* <code>idString</code> matches the string argument.1178*/1179void checkGD(String stringID) {1180if (graphicsConfig != null) {1181if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {1182throw new IllegalArgumentException(1183"adding a container to a container on a different GraphicsDevice");1184}1185}1186}11871188/**1189* Gets this component's locking object (the object that owns the thread1190* synchronization monitor) for AWT component-tree and layout1191* operations.1192* @return this component's locking object1193*/1194public final Object getTreeLock() {1195return LOCK;1196}11971198final void checkTreeLock() {1199if (!Thread.holdsLock(getTreeLock())) {1200throw new IllegalStateException("This function should be called while holding treeLock");1201}1202}12031204/**1205* Gets the toolkit of this component. Note that1206* the frame that contains a component controls which1207* toolkit is used by that component. Therefore if the component1208* is moved from one frame to another, the toolkit it uses may change.1209* @return the toolkit of this component1210* @since JDK1.01211*/1212public Toolkit getToolkit() {1213return getToolkitImpl();1214}12151216/*1217* This is called by the native code, so client code can't1218* be called on the toolkit thread.1219*/1220final Toolkit getToolkitImpl() {1221Container parent = this.parent;1222if (parent != null) {1223return parent.getToolkitImpl();1224}1225return Toolkit.getDefaultToolkit();1226}12271228/**1229* Determines whether this component is valid. A component is valid1230* when it is correctly sized and positioned within its parent1231* container and all its children are also valid.1232* In order to account for peers' size requirements, components are invalidated1233* before they are first shown on the screen. By the time the parent container1234* is fully realized, all its components will be valid.1235* @return <code>true</code> if the component is valid, <code>false</code>1236* otherwise1237* @see #validate1238* @see #invalidate1239* @since JDK1.01240*/1241public boolean isValid() {1242return (peer != null) && valid;1243}12441245/**1246* Determines whether this component is displayable. A component is1247* displayable when it is connected to a native screen resource.1248* <p>1249* A component is made displayable either when it is added to1250* a displayable containment hierarchy or when its containment1251* hierarchy is made displayable.1252* A containment hierarchy is made displayable when its ancestor1253* window is either packed or made visible.1254* <p>1255* A component is made undisplayable either when it is removed from1256* a displayable containment hierarchy or when its containment hierarchy1257* is made undisplayable. A containment hierarchy is made1258* undisplayable when its ancestor window is disposed.1259*1260* @return <code>true</code> if the component is displayable,1261* <code>false</code> otherwise1262* @see Container#add(Component)1263* @see Window#pack1264* @see Window#show1265* @see Container#remove(Component)1266* @see Window#dispose1267* @since 1.21268*/1269public boolean isDisplayable() {1270return getPeer() != null;1271}12721273/**1274* Determines whether this component should be visible when its1275* parent is visible. Components are1276* initially visible, with the exception of top level components such1277* as <code>Frame</code> objects.1278* @return <code>true</code> if the component is visible,1279* <code>false</code> otherwise1280* @see #setVisible1281* @since JDK1.01282*/1283@Transient1284public boolean isVisible() {1285return isVisible_NoClientCode();1286}1287final boolean isVisible_NoClientCode() {1288return visible;1289}12901291/**1292* Determines whether this component will be displayed on the screen.1293* @return <code>true</code> if the component and all of its ancestors1294* until a toplevel window or null parent are visible,1295* <code>false</code> otherwise1296*/1297boolean isRecursivelyVisible() {1298return visible && (parent == null || parent.isRecursivelyVisible());1299}13001301/**1302* Determines the bounds of a visible part of the component relative to its1303* parent.1304*1305* @return the visible part of bounds1306*/1307private Rectangle getRecursivelyVisibleBounds() {1308final Component container = getContainer();1309final Rectangle bounds = getBounds();1310if (container == null) {1311// we are top level window or haven't a container, return our bounds1312return bounds;1313}1314// translate the container's bounds to our coordinate space1315final Rectangle parentsBounds = container.getRecursivelyVisibleBounds();1316parentsBounds.setLocation(0, 0);1317return parentsBounds.intersection(bounds);1318}13191320/**1321* Translates absolute coordinates into coordinates in the coordinate1322* space of this component.1323*/1324Point pointRelativeToComponent(Point absolute) {1325Point compCoords = getLocationOnScreen();1326return new Point(absolute.x - compCoords.x,1327absolute.y - compCoords.y);1328}13291330/**1331* Assuming that mouse location is stored in PointerInfo passed1332* to this method, it finds a Component that is in the same1333* Window as this Component and is located under the mouse pointer.1334* If no such Component exists, null is returned.1335* NOTE: this method should be called under the protection of1336* tree lock, as it is done in Component.getMousePosition() and1337* Container.getMousePosition(boolean).1338*/1339Component findUnderMouseInWindow(PointerInfo pi) {1340if (!isShowing()) {1341return null;1342}1343Window win = getContainingWindow();1344if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) {1345return null;1346}1347final boolean INCLUDE_DISABLED = true;1348Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());1349Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,1350relativeToWindow.y,1351INCLUDE_DISABLED);1352return inTheSameWindow;1353}13541355/**1356* Returns the position of the mouse pointer in this <code>Component</code>'s1357* coordinate space if the <code>Component</code> is directly under the mouse1358* pointer, otherwise returns <code>null</code>.1359* If the <code>Component</code> is not showing on the screen, this method1360* returns <code>null</code> even if the mouse pointer is above the area1361* where the <code>Component</code> would be displayed.1362* If the <code>Component</code> is partially or fully obscured by other1363* <code>Component</code>s or native windows, this method returns a non-null1364* value only if the mouse pointer is located above the unobscured part of the1365* <code>Component</code>.1366* <p>1367* For <code>Container</code>s it returns a non-null value if the mouse is1368* above the <code>Container</code> itself or above any of its descendants.1369* Use {@link Container#getMousePosition(boolean)} if you need to exclude children.1370* <p>1371* Sometimes the exact mouse coordinates are not important, and the only thing1372* that matters is whether a specific <code>Component</code> is under the mouse1373* pointer. If the return value of this method is <code>null</code>, mouse1374* pointer is not directly above the <code>Component</code>.1375*1376* @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true1377* @see #isShowing1378* @see Container#getMousePosition1379* @return mouse coordinates relative to this <code>Component</code>, or null1380* @since 1.51381*/1382public Point getMousePosition() throws HeadlessException {1383if (GraphicsEnvironment.isHeadless()) {1384throw new HeadlessException();1385}13861387PointerInfo pi = java.security.AccessController.doPrivileged(1388new java.security.PrivilegedAction<PointerInfo>() {1389public PointerInfo run() {1390return MouseInfo.getPointerInfo();1391}1392}1393);13941395synchronized (getTreeLock()) {1396Component inTheSameWindow = findUnderMouseInWindow(pi);1397if (!isSameOrAncestorOf(inTheSameWindow, true)) {1398return null;1399}1400return pointRelativeToComponent(pi.getLocation());1401}1402}14031404/**1405* Overridden in Container. Must be called under TreeLock.1406*/1407boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {1408return comp == this;1409}14101411/**1412* Determines whether this component is showing on screen. This means1413* that the component must be visible, and it must be in a container1414* that is visible and showing.1415* <p>1416* <strong>Note:</strong> sometimes there is no way to detect whether the1417* {@code Component} is actually visible to the user. This can happen when:1418* <ul>1419* <li>the component has been added to a visible {@code ScrollPane} but1420* the {@code Component} is not currently in the scroll pane's view port.1421* <li>the {@code Component} is obscured by another {@code Component} or1422* {@code Container}.1423* </ul>1424* @return <code>true</code> if the component is showing,1425* <code>false</code> otherwise1426* @see #setVisible1427* @since JDK1.01428*/1429public boolean isShowing() {1430if (visible && (peer != null)) {1431Container parent = this.parent;1432return (parent == null) || parent.isShowing();1433}1434return false;1435}14361437/**1438* Determines whether this component is enabled. An enabled component1439* can respond to user input and generate events. Components are1440* enabled initially by default. A component may be enabled or disabled by1441* calling its <code>setEnabled</code> method.1442* @return <code>true</code> if the component is enabled,1443* <code>false</code> otherwise1444* @see #setEnabled1445* @since JDK1.01446*/1447public boolean isEnabled() {1448return isEnabledImpl();1449}14501451/*1452* This is called by the native code, so client code can't1453* be called on the toolkit thread.1454*/1455final boolean isEnabledImpl() {1456return enabled;1457}14581459/**1460* Enables or disables this component, depending on the value of the1461* parameter <code>b</code>. An enabled component can respond to user1462* input and generate events. Components are enabled initially by default.1463*1464* <p>Note: Disabling a lightweight component does not prevent it from1465* receiving MouseEvents.1466* <p>Note: Disabling a heavyweight container prevents all components1467* in this container from receiving any input events. But disabling a1468* lightweight container affects only this container.1469*1470* @param b If <code>true</code>, this component is1471* enabled; otherwise this component is disabled1472* @see #isEnabled1473* @see #isLightweight1474* @since JDK1.11475*/1476public void setEnabled(boolean b) {1477enable(b);1478}14791480/**1481* @deprecated As of JDK version 1.1,1482* replaced by <code>setEnabled(boolean)</code>.1483*/1484@Deprecated1485public void enable() {1486if (!enabled) {1487synchronized (getTreeLock()) {1488enabled = true;1489ComponentPeer peer = this.peer;1490if (peer != null) {1491peer.setEnabled(true);1492if (visible && !getRecursivelyVisibleBounds().isEmpty()) {1493updateCursorImmediately();1494}1495}1496}1497if (accessibleContext != null) {1498accessibleContext.firePropertyChange(1499AccessibleContext.ACCESSIBLE_STATE_PROPERTY,1500null, AccessibleState.ENABLED);1501}1502}1503}15041505/**1506* @deprecated As of JDK version 1.1,1507* replaced by <code>setEnabled(boolean)</code>.1508*/1509@Deprecated1510public void enable(boolean b) {1511if (b) {1512enable();1513} else {1514disable();1515}1516}15171518/**1519* @deprecated As of JDK version 1.1,1520* replaced by <code>setEnabled(boolean)</code>.1521*/1522@Deprecated1523public void disable() {1524if (enabled) {1525KeyboardFocusManager.clearMostRecentFocusOwner(this);1526synchronized (getTreeLock()) {1527enabled = false;1528// A disabled lw container is allowed to contain a focus owner.1529if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&1530KeyboardFocusManager.isAutoFocusTransferEnabled())1531{1532// Don't clear the global focus owner. If transferFocus1533// fails, we want the focus to stay on the disabled1534// Component so that keyboard traversal, et. al. still1535// makes sense to the user.1536transferFocus(false);1537}1538ComponentPeer peer = this.peer;1539if (peer != null) {1540peer.setEnabled(false);1541if (visible && !getRecursivelyVisibleBounds().isEmpty()) {1542updateCursorImmediately();1543}1544}1545}1546if (accessibleContext != null) {1547accessibleContext.firePropertyChange(1548AccessibleContext.ACCESSIBLE_STATE_PROPERTY,1549null, AccessibleState.ENABLED);1550}1551}1552}15531554/**1555* Returns true if this component is painted to an offscreen image1556* ("buffer") that's copied to the screen later. Component1557* subclasses that support double buffering should override this1558* method to return true if double buffering is enabled.1559*1560* @return false by default1561*/1562public boolean isDoubleBuffered() {1563return false;1564}15651566/**1567* Enables or disables input method support for this component. If input1568* method support is enabled and the component also processes key events,1569* incoming events are offered to1570* the current input method and will only be processed by the component or1571* dispatched to its listeners if the input method does not consume them.1572* By default, input method support is enabled.1573*1574* @param enable true to enable, false to disable1575* @see #processKeyEvent1576* @since 1.21577*/1578public void enableInputMethods(boolean enable) {1579if (enable) {1580if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0)1581return;15821583// If this component already has focus, then activate the1584// input method by dispatching a synthesized focus gained1585// event.1586if (isFocusOwner()) {1587InputContext inputContext = getInputContext();1588if (inputContext != null) {1589FocusEvent focusGainedEvent =1590new FocusEvent(this, FocusEvent.FOCUS_GAINED);1591inputContext.dispatchEvent(focusGainedEvent);1592}1593}15941595eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;1596} else {1597if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {1598InputContext inputContext = getInputContext();1599if (inputContext != null) {1600inputContext.endComposition();1601inputContext.removeNotify(this);1602}1603}1604eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;1605}1606}16071608/**1609* Shows or hides this component depending on the value of parameter1610* <code>b</code>.1611* <p>1612* This method changes layout-related information, and therefore,1613* invalidates the component hierarchy.1614*1615* @param b if <code>true</code>, shows this component;1616* otherwise, hides this component1617* @see #isVisible1618* @see #invalidate1619* @since JDK1.11620*/1621public void setVisible(boolean b) {1622show(b);1623}16241625/**1626* @deprecated As of JDK version 1.1,1627* replaced by <code>setVisible(boolean)</code>.1628*/1629@Deprecated1630public void show() {1631if (!visible) {1632synchronized (getTreeLock()) {1633visible = true;1634mixOnShowing();1635ComponentPeer peer = this.peer;1636if (peer != null) {1637peer.setVisible(true);1638createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,1639this, parent,1640HierarchyEvent.SHOWING_CHANGED,1641Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));1642if (peer instanceof LightweightPeer) {1643repaint();1644}1645updateCursorImmediately();1646}16471648if (componentListener != null ||1649(eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||1650Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {1651ComponentEvent e = new ComponentEvent(this,1652ComponentEvent.COMPONENT_SHOWN);1653Toolkit.getEventQueue().postEvent(e);1654}1655}1656Container parent = this.parent;1657if (parent != null) {1658parent.invalidate();1659}1660}1661}16621663/**1664* @deprecated As of JDK version 1.1,1665* replaced by <code>setVisible(boolean)</code>.1666*/1667@Deprecated1668public void show(boolean b) {1669if (b) {1670show();1671} else {1672hide();1673}1674}16751676boolean containsFocus() {1677return isFocusOwner();1678}16791680void clearMostRecentFocusOwnerOnHide() {1681KeyboardFocusManager.clearMostRecentFocusOwner(this);1682}16831684void clearCurrentFocusCycleRootOnHide() {1685/* do nothing */1686}16871688/**1689* @deprecated As of JDK version 1.1,1690* replaced by <code>setVisible(boolean)</code>.1691*/1692@Deprecated1693public void hide() {1694isPacked = false;16951696if (visible) {1697clearCurrentFocusCycleRootOnHide();1698clearMostRecentFocusOwnerOnHide();1699synchronized (getTreeLock()) {1700visible = false;1701mixOnHiding(isLightweight());1702if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {1703transferFocus(true);1704}1705ComponentPeer peer = this.peer;1706if (peer != null) {1707peer.setVisible(false);1708createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,1709this, parent,1710HierarchyEvent.SHOWING_CHANGED,1711Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));1712if (peer instanceof LightweightPeer) {1713repaint();1714}1715updateCursorImmediately();1716}1717if (componentListener != null ||1718(eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||1719Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {1720ComponentEvent e = new ComponentEvent(this,1721ComponentEvent.COMPONENT_HIDDEN);1722Toolkit.getEventQueue().postEvent(e);1723}1724}1725Container parent = this.parent;1726if (parent != null) {1727parent.invalidate();1728}1729}1730}17311732/**1733* Gets the foreground color of this component.1734* @return this component's foreground color; if this component does1735* not have a foreground color, the foreground color of its parent1736* is returned1737* @see #setForeground1738* @since JDK1.01739* @beaninfo1740* bound: true1741*/1742@Transient1743public Color getForeground() {1744Color foreground = this.foreground;1745if (foreground != null) {1746return foreground;1747}1748Container parent = this.parent;1749return (parent != null) ? parent.getForeground() : null;1750}17511752/**1753* Sets the foreground color of this component.1754* @param c the color to become this component's1755* foreground color; if this parameter is <code>null</code>1756* then this component will inherit1757* the foreground color of its parent1758* @see #getForeground1759* @since JDK1.01760*/1761public void setForeground(Color c) {1762Color oldColor = foreground;1763ComponentPeer peer = this.peer;1764foreground = c;1765if (peer != null) {1766c = getForeground();1767if (c != null) {1768peer.setForeground(c);1769}1770}1771// This is a bound property, so report the change to1772// any registered listeners. (Cheap if there are none.)1773firePropertyChange("foreground", oldColor, c);1774}17751776/**1777* Returns whether the foreground color has been explicitly set for this1778* Component. If this method returns <code>false</code>, this Component is1779* inheriting its foreground color from an ancestor.1780*1781* @return <code>true</code> if the foreground color has been explicitly1782* set for this Component; <code>false</code> otherwise.1783* @since 1.41784*/1785public boolean isForegroundSet() {1786return (foreground != null);1787}17881789/**1790* Gets the background color of this component.1791* @return this component's background color; if this component does1792* not have a background color,1793* the background color of its parent is returned1794* @see #setBackground1795* @since JDK1.01796*/1797@Transient1798public Color getBackground() {1799Color background = this.background;1800if (background != null) {1801return background;1802}1803Container parent = this.parent;1804return (parent != null) ? parent.getBackground() : null;1805}18061807/**1808* Sets the background color of this component.1809* <p>1810* The background color affects each component differently and the1811* parts of the component that are affected by the background color1812* may differ between operating systems.1813*1814* @param c the color to become this component's color;1815* if this parameter is <code>null</code>, then this1816* component will inherit the background color of its parent1817* @see #getBackground1818* @since JDK1.01819* @beaninfo1820* bound: true1821*/1822public void setBackground(Color c) {1823Color oldColor = background;1824ComponentPeer peer = this.peer;1825background = c;1826if (peer != null) {1827c = getBackground();1828if (c != null) {1829peer.setBackground(c);1830}1831}1832// This is a bound property, so report the change to1833// any registered listeners. (Cheap if there are none.)1834firePropertyChange("background", oldColor, c);1835}18361837/**1838* Returns whether the background color has been explicitly set for this1839* Component. If this method returns <code>false</code>, this Component is1840* inheriting its background color from an ancestor.1841*1842* @return <code>true</code> if the background color has been explicitly1843* set for this Component; <code>false</code> otherwise.1844* @since 1.41845*/1846public boolean isBackgroundSet() {1847return (background != null);1848}18491850/**1851* Gets the font of this component.1852* @return this component's font; if a font has not been set1853* for this component, the font of its parent is returned1854* @see #setFont1855* @since JDK1.01856*/1857@Transient1858public Font getFont() {1859return getFont_NoClientCode();1860}18611862// NOTE: This method may be called by privileged threads.1863// This functionality is implemented in a package-private method1864// to insure that it cannot be overridden by client subclasses.1865// DO NOT INVOKE CLIENT CODE ON THIS THREAD!1866final Font getFont_NoClientCode() {1867Font font = this.font;1868if (font != null) {1869return font;1870}1871Container parent = this.parent;1872return (parent != null) ? parent.getFont_NoClientCode() : null;1873}18741875/**1876* Sets the font of this component.1877* <p>1878* This method changes layout-related information, and therefore,1879* invalidates the component hierarchy.1880*1881* @param f the font to become this component's font;1882* if this parameter is <code>null</code> then this1883* component will inherit the font of its parent1884* @see #getFont1885* @see #invalidate1886* @since JDK1.01887* @beaninfo1888* bound: true1889*/1890public void setFont(Font f) {1891Font oldFont, newFont;1892synchronized(getTreeLock()) {1893oldFont = font;1894newFont = font = f;1895ComponentPeer peer = this.peer;1896if (peer != null) {1897f = getFont();1898if (f != null) {1899peer.setFont(f);1900peerFont = f;1901}1902}1903}1904// This is a bound property, so report the change to1905// any registered listeners. (Cheap if there are none.)1906firePropertyChange("font", oldFont, newFont);19071908// This could change the preferred size of the Component.1909// Fix for 6213660. Should compare old and new fonts and do not1910// call invalidate() if they are equal.1911if (f != oldFont && (oldFont == null ||1912!oldFont.equals(f))) {1913invalidateIfValid();1914}1915}19161917/**1918* Returns whether the font has been explicitly set for this Component. If1919* this method returns <code>false</code>, this Component is inheriting its1920* font from an ancestor.1921*1922* @return <code>true</code> if the font has been explicitly set for this1923* Component; <code>false</code> otherwise.1924* @since 1.41925*/1926public boolean isFontSet() {1927return (font != null);1928}19291930/**1931* Gets the locale of this component.1932* @return this component's locale; if this component does not1933* have a locale, the locale of its parent is returned1934* @see #setLocale1935* @exception IllegalComponentStateException if the <code>Component</code>1936* does not have its own locale and has not yet been added to1937* a containment hierarchy such that the locale can be determined1938* from the containing parent1939* @since JDK1.11940*/1941public Locale getLocale() {1942Locale locale = this.locale;1943if (locale != null) {1944return locale;1945}1946Container parent = this.parent;19471948if (parent == null) {1949throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");1950} else {1951return parent.getLocale();1952}1953}19541955/**1956* Sets the locale of this component. This is a bound property.1957* <p>1958* This method changes layout-related information, and therefore,1959* invalidates the component hierarchy.1960*1961* @param l the locale to become this component's locale1962* @see #getLocale1963* @see #invalidate1964* @since JDK1.11965*/1966public void setLocale(Locale l) {1967Locale oldValue = locale;1968locale = l;19691970// This is a bound property, so report the change to1971// any registered listeners. (Cheap if there are none.)1972firePropertyChange("locale", oldValue, l);19731974// This could change the preferred size of the Component.1975invalidateIfValid();1976}19771978/**1979* Gets the instance of <code>ColorModel</code> used to display1980* the component on the output device.1981* @return the color model used by this component1982* @see java.awt.image.ColorModel1983* @see java.awt.peer.ComponentPeer#getColorModel()1984* @see Toolkit#getColorModel()1985* @since JDK1.01986*/1987public ColorModel getColorModel() {1988ComponentPeer peer = this.peer;1989if ((peer != null) && ! (peer instanceof LightweightPeer)) {1990return peer.getColorModel();1991} else if (GraphicsEnvironment.isHeadless()) {1992return ColorModel.getRGBdefault();1993} // else1994return getToolkit().getColorModel();1995}19961997/**1998* Gets the location of this component in the form of a1999* point specifying the component's top-left corner.2000* The location will be relative to the parent's coordinate space.2001* <p>2002* Due to the asynchronous nature of native event handling, this2003* method can return outdated values (for instance, after several calls2004* of <code>setLocation()</code> in rapid succession). For this2005* reason, the recommended method of obtaining a component's position is2006* within <code>java.awt.event.ComponentListener.componentMoved()</code>,2007* which is called after the operating system has finished moving the2008* component.2009* </p>2010* @return an instance of <code>Point</code> representing2011* the top-left corner of the component's bounds in2012* the coordinate space of the component's parent2013* @see #setLocation2014* @see #getLocationOnScreen2015* @since JDK1.12016*/2017public Point getLocation() {2018return location();2019}20202021/**2022* Gets the location of this component in the form of a point2023* specifying the component's top-left corner in the screen's2024* coordinate space.2025* @return an instance of <code>Point</code> representing2026* the top-left corner of the component's bounds in the2027* coordinate space of the screen2028* @throws IllegalComponentStateException if the2029* component is not showing on the screen2030* @see #setLocation2031* @see #getLocation2032*/2033public Point getLocationOnScreen() {2034synchronized (getTreeLock()) {2035return getLocationOnScreen_NoTreeLock();2036}2037}20382039/*2040* a package private version of getLocationOnScreen2041* used by GlobalCursormanager to update cursor2042*/2043final Point getLocationOnScreen_NoTreeLock() {20442045if (peer != null && isShowing()) {2046if (peer instanceof LightweightPeer) {2047// lightweight component location needs to be translated2048// relative to a native component.2049Container host = getNativeContainer();2050Point pt = host.peer.getLocationOnScreen();2051for(Component c = this; c != host; c = c.getParent()) {2052pt.x += c.x;2053pt.y += c.y;2054}2055return pt;2056} else {2057Point pt = peer.getLocationOnScreen();2058return pt;2059}2060} else {2061throw new IllegalComponentStateException("component must be showing on the screen to determine its location");2062}2063}206420652066/**2067* @deprecated As of JDK version 1.1,2068* replaced by <code>getLocation()</code>.2069*/2070@Deprecated2071public Point location() {2072return location_NoClientCode();2073}20742075private Point location_NoClientCode() {2076return new Point(x, y);2077}20782079/**2080* Moves this component to a new location. The top-left corner of2081* the new location is specified by the <code>x</code> and <code>y</code>2082* parameters in the coordinate space of this component's parent.2083* <p>2084* This method changes layout-related information, and therefore,2085* invalidates the component hierarchy.2086*2087* @param x the <i>x</i>-coordinate of the new location's2088* top-left corner in the parent's coordinate space2089* @param y the <i>y</i>-coordinate of the new location's2090* top-left corner in the parent's coordinate space2091* @see #getLocation2092* @see #setBounds2093* @see #invalidate2094* @since JDK1.12095*/2096public void setLocation(int x, int y) {2097move(x, y);2098}20992100/**2101* @deprecated As of JDK version 1.1,2102* replaced by <code>setLocation(int, int)</code>.2103*/2104@Deprecated2105public void move(int x, int y) {2106synchronized(getTreeLock()) {2107setBoundsOp(ComponentPeer.SET_LOCATION);2108setBounds(x, y, width, height);2109}2110}21112112/**2113* Moves this component to a new location. The top-left corner of2114* the new location is specified by point <code>p</code>. Point2115* <code>p</code> is given in the parent's coordinate space.2116* <p>2117* This method changes layout-related information, and therefore,2118* invalidates the component hierarchy.2119*2120* @param p the point defining the top-left corner2121* of the new location, given in the coordinate space of this2122* component's parent2123* @see #getLocation2124* @see #setBounds2125* @see #invalidate2126* @since JDK1.12127*/2128public void setLocation(Point p) {2129setLocation(p.x, p.y);2130}21312132/**2133* Returns the size of this component in the form of a2134* <code>Dimension</code> object. The <code>height</code>2135* field of the <code>Dimension</code> object contains2136* this component's height, and the <code>width</code>2137* field of the <code>Dimension</code> object contains2138* this component's width.2139* @return a <code>Dimension</code> object that indicates the2140* size of this component2141* @see #setSize2142* @since JDK1.12143*/2144public Dimension getSize() {2145return size();2146}21472148/**2149* @deprecated As of JDK version 1.1,2150* replaced by <code>getSize()</code>.2151*/2152@Deprecated2153public Dimension size() {2154return new Dimension(width, height);2155}21562157/**2158* Resizes this component so that it has width <code>width</code>2159* and height <code>height</code>.2160* <p>2161* This method changes layout-related information, and therefore,2162* invalidates the component hierarchy.2163*2164* @param width the new width of this component in pixels2165* @param height the new height of this component in pixels2166* @see #getSize2167* @see #setBounds2168* @see #invalidate2169* @since JDK1.12170*/2171public void setSize(int width, int height) {2172resize(width, height);2173}21742175/**2176* @deprecated As of JDK version 1.1,2177* replaced by <code>setSize(int, int)</code>.2178*/2179@Deprecated2180public void resize(int width, int height) {2181synchronized(getTreeLock()) {2182setBoundsOp(ComponentPeer.SET_SIZE);2183setBounds(x, y, width, height);2184}2185}21862187/**2188* Resizes this component so that it has width <code>d.width</code>2189* and height <code>d.height</code>.2190* <p>2191* This method changes layout-related information, and therefore,2192* invalidates the component hierarchy.2193*2194* @param d the dimension specifying the new size2195* of this component2196* @throws NullPointerException if {@code d} is {@code null}2197* @see #setSize2198* @see #setBounds2199* @see #invalidate2200* @since JDK1.12201*/2202public void setSize(Dimension d) {2203resize(d);2204}22052206/**2207* @deprecated As of JDK version 1.1,2208* replaced by <code>setSize(Dimension)</code>.2209*/2210@Deprecated2211public void resize(Dimension d) {2212setSize(d.width, d.height);2213}22142215/**2216* Gets the bounds of this component in the form of a2217* <code>Rectangle</code> object. The bounds specify this2218* component's width, height, and location relative to2219* its parent.2220* @return a rectangle indicating this component's bounds2221* @see #setBounds2222* @see #getLocation2223* @see #getSize2224*/2225public Rectangle getBounds() {2226return bounds();2227}22282229/**2230* @deprecated As of JDK version 1.1,2231* replaced by <code>getBounds()</code>.2232*/2233@Deprecated2234public Rectangle bounds() {2235return new Rectangle(x, y, width, height);2236}22372238/**2239* Moves and resizes this component. The new location of the top-left2240* corner is specified by <code>x</code> and <code>y</code>, and the2241* new size is specified by <code>width</code> and <code>height</code>.2242* <p>2243* This method changes layout-related information, and therefore,2244* invalidates the component hierarchy.2245*2246* @param x the new <i>x</i>-coordinate of this component2247* @param y the new <i>y</i>-coordinate of this component2248* @param width the new <code>width</code> of this component2249* @param height the new <code>height</code> of this2250* component2251* @see #getBounds2252* @see #setLocation(int, int)2253* @see #setLocation(Point)2254* @see #setSize(int, int)2255* @see #setSize(Dimension)2256* @see #invalidate2257* @since JDK1.12258*/2259public void setBounds(int x, int y, int width, int height) {2260reshape(x, y, width, height);2261}22622263/**2264* @deprecated As of JDK version 1.1,2265* replaced by <code>setBounds(int, int, int, int)</code>.2266*/2267@Deprecated2268public void reshape(int x, int y, int width, int height) {2269synchronized (getTreeLock()) {2270try {2271setBoundsOp(ComponentPeer.SET_BOUNDS);2272boolean resized = (this.width != width) || (this.height != height);2273boolean moved = (this.x != x) || (this.y != y);2274if (!resized && !moved) {2275return;2276}2277int oldX = this.x;2278int oldY = this.y;2279int oldWidth = this.width;2280int oldHeight = this.height;2281this.x = x;2282this.y = y;2283this.width = width;2284this.height = height;22852286if (resized) {2287isPacked = false;2288}22892290boolean needNotify = true;2291mixOnReshaping();2292if (peer != null) {2293// LightwightPeer is an empty stub so can skip peer.reshape2294if (!(peer instanceof LightweightPeer)) {2295reshapeNativePeer(x, y, width, height, getBoundsOp());2296// Check peer actualy changed coordinates2297resized = (oldWidth != this.width) || (oldHeight != this.height);2298moved = (oldX != this.x) || (oldY != this.y);2299// fix for 5025858: do not send ComponentEvents for toplevel2300// windows here as it is done from peer or native code when2301// the window is really resized or moved, otherwise some2302// events may be sent twice2303if (this instanceof Window) {2304needNotify = false;2305}2306}2307if (resized) {2308invalidate();2309}2310if (parent != null) {2311parent.invalidateIfValid();2312}2313}2314if (needNotify) {2315notifyNewBounds(resized, moved);2316}2317repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight);2318} finally {2319setBoundsOp(ComponentPeer.RESET_OPERATION);2320}2321}2322}23232324private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth,2325int oldHeight)2326{2327if (parent != null && peer instanceof LightweightPeer && isShowing()) {2328// Have the parent redraw the area this component occupied.2329parent.repaint(oldX, oldY, oldWidth, oldHeight);2330// Have the parent redraw the area this component *now* occupies.2331repaint();2332}2333}23342335private void reshapeNativePeer(int x, int y, int width, int height, int op) {2336// native peer might be offset by more than direct2337// parent since parent might be lightweight.2338int nativeX = x;2339int nativeY = y;2340for (Component c = parent;2341(c != null) && (c.peer instanceof LightweightPeer);2342c = c.parent)2343{2344nativeX += c.x;2345nativeY += c.y;2346}2347peer.setBounds(nativeX, nativeY, width, height, op);2348}23492350@SuppressWarnings("deprecation")2351private void notifyNewBounds(boolean resized, boolean moved) {2352if (componentListener != null2353|| (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 02354|| Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK))2355{2356if (resized) {2357ComponentEvent e = new ComponentEvent(this,2358ComponentEvent.COMPONENT_RESIZED);2359Toolkit.getEventQueue().postEvent(e);2360}2361if (moved) {2362ComponentEvent e = new ComponentEvent(this,2363ComponentEvent.COMPONENT_MOVED);2364Toolkit.getEventQueue().postEvent(e);2365}2366} else {2367if (this instanceof Container && ((Container)this).countComponents() > 0) {2368boolean enabledOnToolkit =2369Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);2370if (resized) {23712372((Container)this).createChildHierarchyEvents(2373HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);2374}2375if (moved) {2376((Container)this).createChildHierarchyEvents(2377HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);2378}2379}2380}2381}23822383/**2384* Moves and resizes this component to conform to the new2385* bounding rectangle <code>r</code>. This component's new2386* position is specified by <code>r.x</code> and <code>r.y</code>,2387* and its new size is specified by <code>r.width</code> and2388* <code>r.height</code>2389* <p>2390* This method changes layout-related information, and therefore,2391* invalidates the component hierarchy.2392*2393* @param r the new bounding rectangle for this component2394* @throws NullPointerException if {@code r} is {@code null}2395* @see #getBounds2396* @see #setLocation(int, int)2397* @see #setLocation(Point)2398* @see #setSize(int, int)2399* @see #setSize(Dimension)2400* @see #invalidate2401* @since JDK1.12402*/2403public void setBounds(Rectangle r) {2404setBounds(r.x, r.y, r.width, r.height);2405}240624072408/**2409* Returns the current x coordinate of the components origin.2410* This method is preferable to writing2411* <code>component.getBounds().x</code>,2412* or <code>component.getLocation().x</code> because it doesn't2413* cause any heap allocations.2414*2415* @return the current x coordinate of the components origin2416* @since 1.22417*/2418public int getX() {2419return x;2420}242124222423/**2424* Returns the current y coordinate of the components origin.2425* This method is preferable to writing2426* <code>component.getBounds().y</code>,2427* or <code>component.getLocation().y</code> because it2428* doesn't cause any heap allocations.2429*2430* @return the current y coordinate of the components origin2431* @since 1.22432*/2433public int getY() {2434return y;2435}243624372438/**2439* Returns the current width of this component.2440* This method is preferable to writing2441* <code>component.getBounds().width</code>,2442* or <code>component.getSize().width</code> because it2443* doesn't cause any heap allocations.2444*2445* @return the current width of this component2446* @since 1.22447*/2448public int getWidth() {2449return width;2450}245124522453/**2454* Returns the current height of this component.2455* This method is preferable to writing2456* <code>component.getBounds().height</code>,2457* or <code>component.getSize().height</code> because it2458* doesn't cause any heap allocations.2459*2460* @return the current height of this component2461* @since 1.22462*/2463public int getHeight() {2464return height;2465}24662467/**2468* Stores the bounds of this component into "return value" <b>rv</b> and2469* return <b>rv</b>. If rv is <code>null</code> a new2470* <code>Rectangle</code> is allocated.2471* This version of <code>getBounds</code> is useful if the caller2472* wants to avoid allocating a new <code>Rectangle</code> object2473* on the heap.2474*2475* @param rv the return value, modified to the components bounds2476* @return rv2477*/2478public Rectangle getBounds(Rectangle rv) {2479if (rv == null) {2480return new Rectangle(getX(), getY(), getWidth(), getHeight());2481}2482else {2483rv.setBounds(getX(), getY(), getWidth(), getHeight());2484return rv;2485}2486}24872488/**2489* Stores the width/height of this component into "return value" <b>rv</b>2490* and return <b>rv</b>. If rv is <code>null</code> a new2491* <code>Dimension</code> object is allocated. This version of2492* <code>getSize</code> is useful if the caller wants to avoid2493* allocating a new <code>Dimension</code> object on the heap.2494*2495* @param rv the return value, modified to the components size2496* @return rv2497*/2498public Dimension getSize(Dimension rv) {2499if (rv == null) {2500return new Dimension(getWidth(), getHeight());2501}2502else {2503rv.setSize(getWidth(), getHeight());2504return rv;2505}2506}25072508/**2509* Stores the x,y origin of this component into "return value" <b>rv</b>2510* and return <b>rv</b>. If rv is <code>null</code> a new2511* <code>Point</code> is allocated.2512* This version of <code>getLocation</code> is useful if the2513* caller wants to avoid allocating a new <code>Point</code>2514* object on the heap.2515*2516* @param rv the return value, modified to the components location2517* @return rv2518*/2519public Point getLocation(Point rv) {2520if (rv == null) {2521return new Point(getX(), getY());2522}2523else {2524rv.setLocation(getX(), getY());2525return rv;2526}2527}25282529/**2530* Returns true if this component is completely opaque, returns2531* false by default.2532* <p>2533* An opaque component paints every pixel within its2534* rectangular region. A non-opaque component paints only some of2535* its pixels, allowing the pixels underneath it to "show through".2536* A component that does not fully paint its pixels therefore2537* provides a degree of transparency.2538* <p>2539* Subclasses that guarantee to always completely paint their2540* contents should override this method and return true.2541*2542* @return true if this component is completely opaque2543* @see #isLightweight2544* @since 1.22545*/2546public boolean isOpaque() {2547if (getPeer() == null) {2548return false;2549}2550else {2551return !isLightweight();2552}2553}255425552556/**2557* A lightweight component doesn't have a native toolkit peer.2558* Subclasses of <code>Component</code> and <code>Container</code>,2559* other than the ones defined in this package like <code>Button</code>2560* or <code>Scrollbar</code>, are lightweight.2561* All of the Swing components are lightweights.2562* <p>2563* This method will always return <code>false</code> if this component2564* is not displayable because it is impossible to determine the2565* weight of an undisplayable component.2566*2567* @return true if this component has a lightweight peer; false if2568* it has a native peer or no peer2569* @see #isDisplayable2570* @since 1.22571*/2572public boolean isLightweight() {2573return getPeer() instanceof LightweightPeer;2574}257525762577/**2578* Sets the preferred size of this component to a constant2579* value. Subsequent calls to <code>getPreferredSize</code> will always2580* return this value. Setting the preferred size to <code>null</code>2581* restores the default behavior.2582*2583* @param preferredSize The new preferred size, or null2584* @see #getPreferredSize2585* @see #isPreferredSizeSet2586* @since 1.52587*/2588public void setPreferredSize(Dimension preferredSize) {2589Dimension old;2590// If the preferred size was set, use it as the old value, otherwise2591// use null to indicate we didn't previously have a set preferred2592// size.2593if (prefSizeSet) {2594old = this.prefSize;2595}2596else {2597old = null;2598}2599this.prefSize = preferredSize;2600prefSizeSet = (preferredSize != null);2601firePropertyChange("preferredSize", old, preferredSize);2602}260326042605/**2606* Returns true if the preferred size has been set to a2607* non-<code>null</code> value otherwise returns false.2608*2609* @return true if <code>setPreferredSize</code> has been invoked2610* with a non-null value.2611* @since 1.52612*/2613public boolean isPreferredSizeSet() {2614return prefSizeSet;2615}261626172618/**2619* Gets the preferred size of this component.2620* @return a dimension object indicating this component's preferred size2621* @see #getMinimumSize2622* @see LayoutManager2623*/2624public Dimension getPreferredSize() {2625return preferredSize();2626}262726282629/**2630* @deprecated As of JDK version 1.1,2631* replaced by <code>getPreferredSize()</code>.2632*/2633@Deprecated2634public Dimension preferredSize() {2635/* Avoid grabbing the lock if a reasonable cached size value2636* is available.2637*/2638Dimension dim = prefSize;2639if (dim == null || !(isPreferredSizeSet() || isValid())) {2640synchronized (getTreeLock()) {2641prefSize = (peer != null) ?2642peer.getPreferredSize() :2643getMinimumSize();2644dim = prefSize;2645}2646}2647return new Dimension(dim);2648}26492650/**2651* Sets the minimum size of this component to a constant2652* value. Subsequent calls to <code>getMinimumSize</code> will always2653* return this value. Setting the minimum size to <code>null</code>2654* restores the default behavior.2655*2656* @param minimumSize the new minimum size of this component2657* @see #getMinimumSize2658* @see #isMinimumSizeSet2659* @since 1.52660*/2661public void setMinimumSize(Dimension minimumSize) {2662Dimension old;2663// If the minimum size was set, use it as the old value, otherwise2664// use null to indicate we didn't previously have a set minimum2665// size.2666if (minSizeSet) {2667old = this.minSize;2668}2669else {2670old = null;2671}2672this.minSize = minimumSize;2673minSizeSet = (minimumSize != null);2674firePropertyChange("minimumSize", old, minimumSize);2675}26762677/**2678* Returns whether or not <code>setMinimumSize</code> has been2679* invoked with a non-null value.2680*2681* @return true if <code>setMinimumSize</code> has been invoked with a2682* non-null value.2683* @since 1.52684*/2685public boolean isMinimumSizeSet() {2686return minSizeSet;2687}26882689/**2690* Gets the minimum size of this component.2691* @return a dimension object indicating this component's minimum size2692* @see #getPreferredSize2693* @see LayoutManager2694*/2695public Dimension getMinimumSize() {2696return minimumSize();2697}26982699/**2700* @deprecated As of JDK version 1.1,2701* replaced by <code>getMinimumSize()</code>.2702*/2703@Deprecated2704public Dimension minimumSize() {2705/* Avoid grabbing the lock if a reasonable cached size value2706* is available.2707*/2708Dimension dim = minSize;2709if (dim == null || !(isMinimumSizeSet() || isValid())) {2710synchronized (getTreeLock()) {2711minSize = (peer != null) ?2712peer.getMinimumSize() :2713size();2714dim = minSize;2715}2716}2717return new Dimension(dim);2718}27192720/**2721* Sets the maximum size of this component to a constant2722* value. Subsequent calls to <code>getMaximumSize</code> will always2723* return this value. Setting the maximum size to <code>null</code>2724* restores the default behavior.2725*2726* @param maximumSize a <code>Dimension</code> containing the2727* desired maximum allowable size2728* @see #getMaximumSize2729* @see #isMaximumSizeSet2730* @since 1.52731*/2732public void setMaximumSize(Dimension maximumSize) {2733// If the maximum size was set, use it as the old value, otherwise2734// use null to indicate we didn't previously have a set maximum2735// size.2736Dimension old;2737if (maxSizeSet) {2738old = this.maxSize;2739}2740else {2741old = null;2742}2743this.maxSize = maximumSize;2744maxSizeSet = (maximumSize != null);2745firePropertyChange("maximumSize", old, maximumSize);2746}27472748/**2749* Returns true if the maximum size has been set to a non-<code>null</code>2750* value otherwise returns false.2751*2752* @return true if <code>maximumSize</code> is non-<code>null</code>,2753* false otherwise2754* @since 1.52755*/2756public boolean isMaximumSizeSet() {2757return maxSizeSet;2758}27592760/**2761* Gets the maximum size of this component.2762* @return a dimension object indicating this component's maximum size2763* @see #getMinimumSize2764* @see #getPreferredSize2765* @see LayoutManager2766*/2767public Dimension getMaximumSize() {2768if (isMaximumSizeSet()) {2769return new Dimension(maxSize);2770}2771return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);2772}27732774/**2775* Returns the alignment along the x axis. This specifies how2776* the component would like to be aligned relative to other2777* components. The value should be a number between 0 and 12778* where 0 represents alignment along the origin, 1 is aligned2779* the furthest away from the origin, 0.5 is centered, etc.2780*/2781public float getAlignmentX() {2782return CENTER_ALIGNMENT;2783}27842785/**2786* Returns the alignment along the y axis. This specifies how2787* the component would like to be aligned relative to other2788* components. The value should be a number between 0 and 12789* where 0 represents alignment along the origin, 1 is aligned2790* the furthest away from the origin, 0.5 is centered, etc.2791*/2792public float getAlignmentY() {2793return CENTER_ALIGNMENT;2794}27952796/**2797* Returns the baseline. The baseline is measured from the top of2798* the component. This method is primarily meant for2799* <code>LayoutManager</code>s to align components along their2800* baseline. A return value less than 0 indicates this component2801* does not have a reasonable baseline and that2802* <code>LayoutManager</code>s should not align this component on2803* its baseline.2804* <p>2805* The default implementation returns -1. Subclasses that support2806* baseline should override appropriately. If a value >= 0 is2807* returned, then the component has a valid baseline for any2808* size >= the minimum size and <code>getBaselineResizeBehavior</code>2809* can be used to determine how the baseline changes with size.2810*2811* @param width the width to get the baseline for2812* @param height the height to get the baseline for2813* @return the baseline or < 0 indicating there is no reasonable2814* baseline2815* @throws IllegalArgumentException if width or height is < 02816* @see #getBaselineResizeBehavior2817* @see java.awt.FontMetrics2818* @since 1.62819*/2820public int getBaseline(int width, int height) {2821if (width < 0 || height < 0) {2822throw new IllegalArgumentException(2823"Width and height must be >= 0");2824}2825return -1;2826}28272828/**2829* Returns an enum indicating how the baseline of the component2830* changes as the size changes. This method is primarily meant for2831* layout managers and GUI builders.2832* <p>2833* The default implementation returns2834* <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a2835* baseline should override appropriately. Subclasses should2836* never return <code>null</code>; if the baseline can not be2837* calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers2838* should first ask for the baseline using2839* <code>getBaseline</code> and if a value >= 0 is returned use2840* this method. It is acceptable for this method to return a2841* value other than <code>BaselineResizeBehavior.OTHER</code> even if2842* <code>getBaseline</code> returns a value less than 0.2843*2844* @return an enum indicating how the baseline changes as the component2845* size changes2846* @see #getBaseline(int, int)2847* @since 1.62848*/2849public BaselineResizeBehavior getBaselineResizeBehavior() {2850return BaselineResizeBehavior.OTHER;2851}28522853/**2854* Prompts the layout manager to lay out this component. This is2855* usually called when the component (more specifically, container)2856* is validated.2857* @see #validate2858* @see LayoutManager2859*/2860public void doLayout() {2861layout();2862}28632864/**2865* @deprecated As of JDK version 1.1,2866* replaced by <code>doLayout()</code>.2867*/2868@Deprecated2869public void layout() {2870}28712872/**2873* Validates this component.2874* <p>2875* The meaning of the term <i>validating</i> is defined by the ancestors of2876* this class. See {@link Container#validate} for more details.2877*2878* @see #invalidate2879* @see #doLayout()2880* @see LayoutManager2881* @see Container#validate2882* @since JDK1.02883*/2884public void validate() {2885synchronized (getTreeLock()) {2886ComponentPeer peer = this.peer;2887boolean wasValid = isValid();2888if (!wasValid && peer != null) {2889Font newfont = getFont();2890Font oldfont = peerFont;2891if (newfont != oldfont && (oldfont == null2892|| !oldfont.equals(newfont))) {2893peer.setFont(newfont);2894peerFont = newfont;2895}2896peer.layout();2897}2898valid = true;2899if (!wasValid) {2900mixOnValidating();2901}2902}2903}29042905/**2906* Invalidates this component and its ancestors.2907* <p>2908* By default, all the ancestors of the component up to the top-most2909* container of the hierarchy are marked invalid. If the {@code2910* java.awt.smartInvalidate} system property is set to {@code true},2911* invalidation stops on the nearest validate root of this component.2912* Marking a container <i>invalid</i> indicates that the container needs to2913* be laid out.2914* <p>2915* This method is called automatically when any layout-related information2916* changes (e.g. setting the bounds of the component, or adding the2917* component to a container).2918* <p>2919* This method might be called often, so it should work fast.2920*2921* @see #validate2922* @see #doLayout2923* @see LayoutManager2924* @see java.awt.Container#isValidateRoot2925* @since JDK1.02926*/2927public void invalidate() {2928synchronized (getTreeLock()) {2929/* Nullify cached layout and size information.2930* For efficiency, propagate invalidate() upwards only if2931* some other component hasn't already done so first.2932*/2933valid = false;2934if (!isPreferredSizeSet()) {2935prefSize = null;2936}2937if (!isMinimumSizeSet()) {2938minSize = null;2939}2940if (!isMaximumSizeSet()) {2941maxSize = null;2942}2943invalidateParent();2944}2945}29462947/**2948* Invalidates the parent of this component if any.2949*2950* This method MUST BE invoked under the TreeLock.2951*/2952void invalidateParent() {2953if (parent != null) {2954parent.invalidateIfValid();2955}2956}29572958/** Invalidates the component unless it is already invalid.2959*/2960final void invalidateIfValid() {2961if (isValid()) {2962invalidate();2963}2964}29652966/**2967* Revalidates the component hierarchy up to the nearest validate root.2968* <p>2969* This method first invalidates the component hierarchy starting from this2970* component up to the nearest validate root. Afterwards, the component2971* hierarchy is validated starting from the nearest validate root.2972* <p>2973* This is a convenience method supposed to help application developers2974* avoid looking for validate roots manually. Basically, it's equivalent to2975* first calling the {@link #invalidate()} method on this component, and2976* then calling the {@link #validate()} method on the nearest validate2977* root.2978*2979* @see Container#isValidateRoot2980* @since 1.72981*/2982public void revalidate() {2983revalidateSynchronously();2984}29852986/**2987* Revalidates the component synchronously.2988*/2989final void revalidateSynchronously() {2990synchronized (getTreeLock()) {2991invalidate();29922993Container root = getContainer();2994if (root == null) {2995// There's no parents. Just validate itself.2996validate();2997} else {2998while (!root.isValidateRoot()) {2999if (root.getContainer() == null) {3000// If there's no validate roots, we'll validate the3001// topmost container3002break;3003}30043005root = root.getContainer();3006}30073008root.validate();3009}3010}3011}30123013/**3014* Creates a graphics context for this component. This method will3015* return <code>null</code> if this component is currently not3016* displayable.3017* @return a graphics context for this component, or <code>null</code>3018* if it has none3019* @see #paint3020* @since JDK1.03021*/3022public Graphics getGraphics() {3023if (peer instanceof LightweightPeer) {3024// This is for a lightweight component, need to3025// translate coordinate spaces and clip relative3026// to the parent.3027if (parent == null) return null;3028Graphics g = parent.getGraphics();3029if (g == null) return null;3030if (g instanceof ConstrainableGraphics) {3031((ConstrainableGraphics) g).constrain(x, y, width, height);3032} else {3033g.translate(x,y);3034g.setClip(0, 0, width, height);3035}3036g.setFont(getFont());3037return g;3038} else {3039ComponentPeer peer = this.peer;3040return (peer != null) ? peer.getGraphics() : null;3041}3042}30433044final Graphics getGraphics_NoClientCode() {3045ComponentPeer peer = this.peer;3046if (peer instanceof LightweightPeer) {3047// This is for a lightweight component, need to3048// translate coordinate spaces and clip relative3049// to the parent.3050Container parent = this.parent;3051if (parent == null) return null;3052Graphics g = parent.getGraphics_NoClientCode();3053if (g == null) return null;3054if (g instanceof ConstrainableGraphics) {3055((ConstrainableGraphics) g).constrain(x, y, width, height);3056} else {3057g.translate(x,y);3058g.setClip(0, 0, width, height);3059}3060g.setFont(getFont_NoClientCode());3061return g;3062} else {3063return (peer != null) ? peer.getGraphics() : null;3064}3065}30663067/**3068* Gets the font metrics for the specified font.3069* Warning: Since Font metrics are affected by the3070* {@link java.awt.font.FontRenderContext FontRenderContext} and3071* this method does not provide one, it can return only metrics for3072* the default render context which may not match that used when3073* rendering on the Component if {@link Graphics2D} functionality is being3074* used. Instead metrics can be obtained at rendering time by calling3075* {@link Graphics#getFontMetrics()} or text measurement APIs on the3076* {@link Font Font} class.3077* @param font the font for which font metrics is to be3078* obtained3079* @return the font metrics for <code>font</code>3080* @see #getFont3081* @see #getPeer3082* @see java.awt.peer.ComponentPeer#getFontMetrics(Font)3083* @see Toolkit#getFontMetrics(Font)3084* @since JDK1.03085*/3086public FontMetrics getFontMetrics(Font font) {3087// This is an unsupported hack, but left in for a customer.3088// Do not remove.3089FontManager fm = FontManagerFactory.getInstance();3090if (fm instanceof SunFontManager3091&& ((SunFontManager) fm).usePlatformFontMetrics()) {30923093if (peer != null &&3094!(peer instanceof LightweightPeer)) {3095return peer.getFontMetrics(font);3096}3097}3098return sun.font.FontDesignMetrics.getMetrics(font);3099}31003101/**3102* Sets the cursor image to the specified cursor. This cursor3103* image is displayed when the <code>contains</code> method for3104* this component returns true for the current cursor location, and3105* this Component is visible, displayable, and enabled. Setting the3106* cursor of a <code>Container</code> causes that cursor to be displayed3107* within all of the container's subcomponents, except for those3108* that have a non-<code>null</code> cursor.3109* <p>3110* The method may have no visual effect if the Java platform3111* implementation and/or the native system do not support3112* changing the mouse cursor shape.3113* @param cursor One of the constants defined3114* by the <code>Cursor</code> class;3115* if this parameter is <code>null</code>3116* then this component will inherit3117* the cursor of its parent3118* @see #isEnabled3119* @see #isShowing3120* @see #getCursor3121* @see #contains3122* @see Toolkit#createCustomCursor3123* @see Cursor3124* @since JDK1.13125*/3126public void setCursor(Cursor cursor) {3127this.cursor = cursor;3128updateCursorImmediately();3129}31303131/**3132* Updates the cursor. May not be invoked from the native3133* message pump.3134*/3135final void updateCursorImmediately() {3136if (peer instanceof LightweightPeer) {3137Container nativeContainer = getNativeContainer();31383139if (nativeContainer == null) return;31403141ComponentPeer cPeer = nativeContainer.getPeer();31423143if (cPeer != null) {3144cPeer.updateCursorImmediately();3145}3146} else if (peer != null) {3147peer.updateCursorImmediately();3148}3149}31503151/**3152* Gets the cursor set in the component. If the component does3153* not have a cursor set, the cursor of its parent is returned.3154* If no cursor is set in the entire hierarchy,3155* <code>Cursor.DEFAULT_CURSOR</code> is returned.3156* @see #setCursor3157* @since JDK1.13158*/3159public Cursor getCursor() {3160return getCursor_NoClientCode();3161}31623163final Cursor getCursor_NoClientCode() {3164Cursor cursor = this.cursor;3165if (cursor != null) {3166return cursor;3167}3168Container parent = this.parent;3169if (parent != null) {3170return parent.getCursor_NoClientCode();3171} else {3172return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);3173}3174}31753176/**3177* Returns whether the cursor has been explicitly set for this Component.3178* If this method returns <code>false</code>, this Component is inheriting3179* its cursor from an ancestor.3180*3181* @return <code>true</code> if the cursor has been explicitly set for this3182* Component; <code>false</code> otherwise.3183* @since 1.43184*/3185public boolean isCursorSet() {3186return (cursor != null);3187}31883189/**3190* Paints this component.3191* <p>3192* This method is called when the contents of the component should3193* be painted; such as when the component is first being shown or3194* is damaged and in need of repair. The clip rectangle in the3195* <code>Graphics</code> parameter is set to the area3196* which needs to be painted.3197* Subclasses of <code>Component</code> that override this3198* method need not call <code>super.paint(g)</code>.3199* <p>3200* For performance reasons, <code>Component</code>s with zero width3201* or height aren't considered to need painting when they are first shown,3202* and also aren't considered to need repair.3203* <p>3204* <b>Note</b>: For more information on the paint mechanisms utilitized3205* by AWT and Swing, including information on how to write the most3206* efficient painting code, see3207* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.3208*3209* @param g the graphics context to use for painting3210* @see #update3211* @since JDK1.03212*/3213public void paint(Graphics g) {3214}32153216/**3217* Updates this component.3218* <p>3219* If this component is not a lightweight component, the3220* AWT calls the <code>update</code> method in response to3221* a call to <code>repaint</code>. You can assume that3222* the background is not cleared.3223* <p>3224* The <code>update</code> method of <code>Component</code>3225* calls this component's <code>paint</code> method to redraw3226* this component. This method is commonly overridden by subclasses3227* which need to do additional work in response to a call to3228* <code>repaint</code>.3229* Subclasses of Component that override this method should either3230* call <code>super.update(g)</code>, or call <code>paint(g)</code>3231* directly from their <code>update</code> method.3232* <p>3233* The origin of the graphics context, its3234* (<code>0</code>, <code>0</code>) coordinate point, is the3235* top-left corner of this component. The clipping region of the3236* graphics context is the bounding rectangle of this component.3237*3238* <p>3239* <b>Note</b>: For more information on the paint mechanisms utilitized3240* by AWT and Swing, including information on how to write the most3241* efficient painting code, see3242* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.3243*3244* @param g the specified context to use for updating3245* @see #paint3246* @see #repaint()3247* @since JDK1.03248*/3249public void update(Graphics g) {3250paint(g);3251}32523253/**3254* Paints this component and all of its subcomponents.3255* <p>3256* The origin of the graphics context, its3257* (<code>0</code>, <code>0</code>) coordinate point, is the3258* top-left corner of this component. The clipping region of the3259* graphics context is the bounding rectangle of this component.3260*3261* @param g the graphics context to use for painting3262* @see #paint3263* @since JDK1.03264*/3265public void paintAll(Graphics g) {3266if (isShowing()) {3267GraphicsCallback.PeerPaintCallback.getInstance().3268runOneComponent(this, new Rectangle(0, 0, width, height),3269g, g.getClip(),3270GraphicsCallback.LIGHTWEIGHTS |3271GraphicsCallback.HEAVYWEIGHTS);3272}3273}32743275/**3276* Simulates the peer callbacks into java.awt for painting of3277* lightweight Components.3278* @param g the graphics context to use for painting3279* @see #paintAll3280*/3281void lightweightPaint(Graphics g) {3282paint(g);3283}32843285/**3286* Paints all the heavyweight subcomponents.3287*/3288void paintHeavyweightComponents(Graphics g) {3289}32903291/**3292* Repaints this component.3293* <p>3294* If this component is a lightweight component, this method3295* causes a call to this component's <code>paint</code>3296* method as soon as possible. Otherwise, this method causes3297* a call to this component's <code>update</code> method as soon3298* as possible.3299* <p>3300* <b>Note</b>: For more information on the paint mechanisms utilitized3301* by AWT and Swing, including information on how to write the most3302* efficient painting code, see3303* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.33043305*3306* @see #update(Graphics)3307* @since JDK1.03308*/3309public void repaint() {3310repaint(0, 0, 0, width, height);3311}33123313/**3314* Repaints the component. If this component is a lightweight3315* component, this results in a call to <code>paint</code>3316* within <code>tm</code> milliseconds.3317* <p>3318* <b>Note</b>: For more information on the paint mechanisms utilitized3319* by AWT and Swing, including information on how to write the most3320* efficient painting code, see3321* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.3322*3323* @param tm maximum time in milliseconds before update3324* @see #paint3325* @see #update(Graphics)3326* @since JDK1.03327*/3328public void repaint(long tm) {3329repaint(tm, 0, 0, width, height);3330}33313332/**3333* Repaints the specified rectangle of this component.3334* <p>3335* If this component is a lightweight component, this method3336* causes a call to this component's <code>paint</code> method3337* as soon as possible. Otherwise, this method causes a call to3338* this component's <code>update</code> method as soon as possible.3339* <p>3340* <b>Note</b>: For more information on the paint mechanisms utilitized3341* by AWT and Swing, including information on how to write the most3342* efficient painting code, see3343* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.3344*3345* @param x the <i>x</i> coordinate3346* @param y the <i>y</i> coordinate3347* @param width the width3348* @param height the height3349* @see #update(Graphics)3350* @since JDK1.03351*/3352public void repaint(int x, int y, int width, int height) {3353repaint(0, x, y, width, height);3354}33553356/**3357* Repaints the specified rectangle of this component within3358* <code>tm</code> milliseconds.3359* <p>3360* If this component is a lightweight component, this method causes3361* a call to this component's <code>paint</code> method.3362* Otherwise, this method causes a call to this component's3363* <code>update</code> method.3364* <p>3365* <b>Note</b>: For more information on the paint mechanisms utilitized3366* by AWT and Swing, including information on how to write the most3367* efficient painting code, see3368* <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.3369*3370* @param tm maximum time in milliseconds before update3371* @param x the <i>x</i> coordinate3372* @param y the <i>y</i> coordinate3373* @param width the width3374* @param height the height3375* @see #update(Graphics)3376* @since JDK1.03377*/3378public void repaint(long tm, int x, int y, int width, int height) {3379if (this.peer instanceof LightweightPeer) {3380// Needs to be translated to parent coordinates since3381// a parent native container provides the actual repaint3382// services. Additionally, the request is restricted to3383// the bounds of the component.3384if (parent != null) {3385if (x < 0) {3386width += x;3387x = 0;3388}3389if (y < 0) {3390height += y;3391y = 0;3392}33933394int pwidth = (width > this.width) ? this.width : width;3395int pheight = (height > this.height) ? this.height : height;33963397if (pwidth <= 0 || pheight <= 0) {3398return;3399}34003401int px = this.x + x;3402int py = this.y + y;3403parent.repaint(tm, px, py, pwidth, pheight);3404}3405} else {3406if (isVisible() && (this.peer != null) &&3407(width > 0) && (height > 0)) {3408PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,3409new Rectangle(x, y, width, height));3410SunToolkit.postEvent(SunToolkit.targetToAppContext(this), e);3411}3412}3413}34143415/**3416* Prints this component. Applications should override this method3417* for components that must do special processing before being3418* printed or should be printed differently than they are painted.3419* <p>3420* The default implementation of this method calls the3421* <code>paint</code> method.3422* <p>3423* The origin of the graphics context, its3424* (<code>0</code>, <code>0</code>) coordinate point, is the3425* top-left corner of this component. The clipping region of the3426* graphics context is the bounding rectangle of this component.3427* @param g the graphics context to use for printing3428* @see #paint(Graphics)3429* @since JDK1.03430*/3431public void print(Graphics g) {3432paint(g);3433}34343435/**3436* Prints this component and all of its subcomponents.3437* <p>3438* The origin of the graphics context, its3439* (<code>0</code>, <code>0</code>) coordinate point, is the3440* top-left corner of this component. The clipping region of the3441* graphics context is the bounding rectangle of this component.3442* @param g the graphics context to use for printing3443* @see #print(Graphics)3444* @since JDK1.03445*/3446public void printAll(Graphics g) {3447if (isShowing()) {3448GraphicsCallback.PeerPrintCallback.getInstance().3449runOneComponent(this, new Rectangle(0, 0, width, height),3450g, g.getClip(),3451GraphicsCallback.LIGHTWEIGHTS |3452GraphicsCallback.HEAVYWEIGHTS);3453}3454}34553456/**3457* Simulates the peer callbacks into java.awt for printing of3458* lightweight Components.3459* @param g the graphics context to use for printing3460* @see #printAll3461*/3462void lightweightPrint(Graphics g) {3463print(g);3464}34653466/**3467* Prints all the heavyweight subcomponents.3468*/3469void printHeavyweightComponents(Graphics g) {3470}34713472private Insets getInsets_NoClientCode() {3473ComponentPeer peer = this.peer;3474if (peer instanceof ContainerPeer) {3475return (Insets)((ContainerPeer)peer).getInsets().clone();3476}3477return new Insets(0, 0, 0, 0);3478}34793480/**3481* Repaints the component when the image has changed.3482* This <code>imageUpdate</code> method of an <code>ImageObserver</code>3483* is called when more information about an3484* image which had been previously requested using an asynchronous3485* routine such as the <code>drawImage</code> method of3486* <code>Graphics</code> becomes available.3487* See the definition of <code>imageUpdate</code> for3488* more information on this method and its arguments.3489* <p>3490* The <code>imageUpdate</code> method of <code>Component</code>3491* incrementally draws an image on the component as more of the bits3492* of the image are available.3493* <p>3494* If the system property <code>awt.image.incrementaldraw</code>3495* is missing or has the value <code>true</code>, the image is3496* incrementally drawn. If the system property has any other value,3497* then the image is not drawn until it has been completely loaded.3498* <p>3499* Also, if incremental drawing is in effect, the value of the3500* system property <code>awt.image.redrawrate</code> is interpreted3501* as an integer to give the maximum redraw rate, in milliseconds. If3502* the system property is missing or cannot be interpreted as an3503* integer, the redraw rate is once every 100ms.3504* <p>3505* The interpretation of the <code>x</code>, <code>y</code>,3506* <code>width</code>, and <code>height</code> arguments depends on3507* the value of the <code>infoflags</code> argument.3508*3509* @param img the image being observed3510* @param infoflags see <code>imageUpdate</code> for more information3511* @param x the <i>x</i> coordinate3512* @param y the <i>y</i> coordinate3513* @param w the width3514* @param h the height3515* @return <code>false</code> if the infoflags indicate that the3516* image is completely loaded; <code>true</code> otherwise.3517*3518* @see java.awt.image.ImageObserver3519* @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)3520* @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)3521* @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)3522* @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)3523* @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)3524* @since JDK1.03525*/3526public boolean imageUpdate(Image img, int infoflags,3527int x, int y, int w, int h) {3528int rate = -1;3529if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {3530rate = 0;3531} else if ((infoflags & SOMEBITS) != 0) {3532if (isInc) {3533rate = incRate;3534if (rate < 0) {3535rate = 0;3536}3537}3538}3539if (rate >= 0) {3540repaint(rate, 0, 0, width, height);3541}3542return (infoflags & (ALLBITS|ABORT)) == 0;3543}35443545/**3546* Creates an image from the specified image producer.3547* @param producer the image producer3548* @return the image produced3549* @since JDK1.03550*/3551public Image createImage(ImageProducer producer) {3552ComponentPeer peer = this.peer;3553if ((peer != null) && ! (peer instanceof LightweightPeer)) {3554return peer.createImage(producer);3555}3556return getToolkit().createImage(producer);3557}35583559/**3560* Creates an off-screen drawable image3561* to be used for double buffering.3562* @param width the specified width3563* @param height the specified height3564* @return an off-screen drawable image, which can be used for double3565* buffering. The return value may be <code>null</code> if the3566* component is not displayable. This will always happen if3567* <code>GraphicsEnvironment.isHeadless()</code> returns3568* <code>true</code>.3569* @see #isDisplayable3570* @see GraphicsEnvironment#isHeadless3571* @since JDK1.03572*/3573public Image createImage(int width, int height) {3574ComponentPeer peer = this.peer;3575if (peer instanceof LightweightPeer) {3576if (parent != null) { return parent.createImage(width, height); }3577else { return null;}3578} else {3579return (peer != null) ? peer.createImage(width, height) : null;3580}3581}35823583/**3584* Creates a volatile off-screen drawable image3585* to be used for double buffering.3586* @param width the specified width.3587* @param height the specified height.3588* @return an off-screen drawable image, which can be used for double3589* buffering. The return value may be <code>null</code> if the3590* component is not displayable. This will always happen if3591* <code>GraphicsEnvironment.isHeadless()</code> returns3592* <code>true</code>.3593* @see java.awt.image.VolatileImage3594* @see #isDisplayable3595* @see GraphicsEnvironment#isHeadless3596* @since 1.43597*/3598public VolatileImage createVolatileImage(int width, int height) {3599ComponentPeer peer = this.peer;3600if (peer instanceof LightweightPeer) {3601if (parent != null) {3602return parent.createVolatileImage(width, height);3603}3604else { return null;}3605} else {3606return (peer != null) ?3607peer.createVolatileImage(width, height) : null;3608}3609}36103611/**3612* Creates a volatile off-screen drawable image, with the given capabilities.3613* The contents of this image may be lost at any time due3614* to operating system issues, so the image must be managed3615* via the <code>VolatileImage</code> interface.3616* @param width the specified width.3617* @param height the specified height.3618* @param caps the image capabilities3619* @exception AWTException if an image with the specified capabilities cannot3620* be created3621* @return a VolatileImage object, which can be used3622* to manage surface contents loss and capabilities.3623* @see java.awt.image.VolatileImage3624* @since 1.43625*/3626public VolatileImage createVolatileImage(int width, int height,3627ImageCapabilities caps) throws AWTException {3628// REMIND : check caps3629return createVolatileImage(width, height);3630}36313632/**3633* Prepares an image for rendering on this component. The image3634* data is downloaded asynchronously in another thread and the3635* appropriate screen representation of the image is generated.3636* @param image the <code>Image</code> for which to3637* prepare a screen representation3638* @param observer the <code>ImageObserver</code> object3639* to be notified as the image is being prepared3640* @return <code>true</code> if the image has already been fully3641* prepared; <code>false</code> otherwise3642* @since JDK1.03643*/3644public boolean prepareImage(Image image, ImageObserver observer) {3645return prepareImage(image, -1, -1, observer);3646}36473648/**3649* Prepares an image for rendering on this component at the3650* specified width and height.3651* <p>3652* The image data is downloaded asynchronously in another thread,3653* and an appropriately scaled screen representation of the image is3654* generated.3655* @param image the instance of <code>Image</code>3656* for which to prepare a screen representation3657* @param width the width of the desired screen representation3658* @param height the height of the desired screen representation3659* @param observer the <code>ImageObserver</code> object3660* to be notified as the image is being prepared3661* @return <code>true</code> if the image has already been fully3662* prepared; <code>false</code> otherwise3663* @see java.awt.image.ImageObserver3664* @since JDK1.03665*/3666public boolean prepareImage(Image image, int width, int height,3667ImageObserver observer) {3668ComponentPeer peer = this.peer;3669if (peer instanceof LightweightPeer) {3670return (parent != null)3671? parent.prepareImage(image, width, height, observer)3672: getToolkit().prepareImage(image, width, height, observer);3673} else {3674return (peer != null)3675? peer.prepareImage(image, width, height, observer)3676: getToolkit().prepareImage(image, width, height, observer);3677}3678}36793680/**3681* Returns the status of the construction of a screen representation3682* of the specified image.3683* <p>3684* This method does not cause the image to begin loading. An3685* application must use the <code>prepareImage</code> method3686* to force the loading of an image.3687* <p>3688* Information on the flags returned by this method can be found3689* with the discussion of the <code>ImageObserver</code> interface.3690* @param image the <code>Image</code> object whose status3691* is being checked3692* @param observer the <code>ImageObserver</code>3693* object to be notified as the image is being prepared3694* @return the bitwise inclusive <b>OR</b> of3695* <code>ImageObserver</code> flags indicating what3696* information about the image is currently available3697* @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)3698* @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)3699* @see java.awt.image.ImageObserver3700* @since JDK1.03701*/3702public int checkImage(Image image, ImageObserver observer) {3703return checkImage(image, -1, -1, observer);3704}37053706/**3707* Returns the status of the construction of a screen representation3708* of the specified image.3709* <p>3710* This method does not cause the image to begin loading. An3711* application must use the <code>prepareImage</code> method3712* to force the loading of an image.3713* <p>3714* The <code>checkImage</code> method of <code>Component</code>3715* calls its peer's <code>checkImage</code> method to calculate3716* the flags. If this component does not yet have a peer, the3717* component's toolkit's <code>checkImage</code> method is called3718* instead.3719* <p>3720* Information on the flags returned by this method can be found3721* with the discussion of the <code>ImageObserver</code> interface.3722* @param image the <code>Image</code> object whose status3723* is being checked3724* @param width the width of the scaled version3725* whose status is to be checked3726* @param height the height of the scaled version3727* whose status is to be checked3728* @param observer the <code>ImageObserver</code> object3729* to be notified as the image is being prepared3730* @return the bitwise inclusive <b>OR</b> of3731* <code>ImageObserver</code> flags indicating what3732* information about the image is currently available3733* @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)3734* @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)3735* @see java.awt.image.ImageObserver3736* @since JDK1.03737*/3738public int checkImage(Image image, int width, int height,3739ImageObserver observer) {3740ComponentPeer peer = this.peer;3741if (peer instanceof LightweightPeer) {3742return (parent != null)3743? parent.checkImage(image, width, height, observer)3744: getToolkit().checkImage(image, width, height, observer);3745} else {3746return (peer != null)3747? peer.checkImage(image, width, height, observer)3748: getToolkit().checkImage(image, width, height, observer);3749}3750}37513752/**3753* Creates a new strategy for multi-buffering on this component.3754* Multi-buffering is useful for rendering performance. This method3755* attempts to create the best strategy available with the number of3756* buffers supplied. It will always create a <code>BufferStrategy</code>3757* with that number of buffers.3758* A page-flipping strategy is attempted first, then a blitting strategy3759* using accelerated buffers. Finally, an unaccelerated blitting3760* strategy is used.3761* <p>3762* Each time this method is called,3763* the existing buffer strategy for this component is discarded.3764* @param numBuffers number of buffers to create, including the front buffer3765* @exception IllegalArgumentException if numBuffers is less than 1.3766* @exception IllegalStateException if the component is not displayable3767* @see #isDisplayable3768* @see Window#getBufferStrategy()3769* @see Canvas#getBufferStrategy()3770* @since 1.43771*/3772void createBufferStrategy(int numBuffers) {3773BufferCapabilities bufferCaps;3774if (numBuffers > 1) {3775// Try to create a page-flipping strategy3776bufferCaps = new BufferCapabilities(new ImageCapabilities(true),3777new ImageCapabilities(true),3778BufferCapabilities.FlipContents.UNDEFINED);3779try {3780createBufferStrategy(numBuffers, bufferCaps);3781return; // Success3782} catch (AWTException e) {3783// Failed3784}3785}3786// Try a blitting (but still accelerated) strategy3787bufferCaps = new BufferCapabilities(new ImageCapabilities(true),3788new ImageCapabilities(true),3789null);3790try {3791createBufferStrategy(numBuffers, bufferCaps);3792return; // Success3793} catch (AWTException e) {3794// Failed3795}3796// Try an unaccelerated blitting strategy3797bufferCaps = new BufferCapabilities(new ImageCapabilities(false),3798new ImageCapabilities(false),3799null);3800try {3801createBufferStrategy(numBuffers, bufferCaps);3802return; // Success3803} catch (AWTException e) {3804// Code should never reach here (an unaccelerated blitting3805// strategy should always work)3806throw new InternalError("Could not create a buffer strategy", e);3807}3808}38093810/**3811* Creates a new strategy for multi-buffering on this component with the3812* required buffer capabilities. This is useful, for example, if only3813* accelerated memory or page flipping is desired (as specified by the3814* buffer capabilities).3815* <p>3816* Each time this method3817* is called, <code>dispose</code> will be invoked on the existing3818* <code>BufferStrategy</code>.3819* @param numBuffers number of buffers to create3820* @param caps the required capabilities for creating the buffer strategy;3821* cannot be <code>null</code>3822* @exception AWTException if the capabilities supplied could not be3823* supported or met; this may happen, for example, if there is not enough3824* accelerated memory currently available, or if page flipping is specified3825* but not possible.3826* @exception IllegalArgumentException if numBuffers is less than 1, or if3827* caps is <code>null</code>3828* @see Window#getBufferStrategy()3829* @see Canvas#getBufferStrategy()3830* @since 1.43831*/3832void createBufferStrategy(int numBuffers,3833BufferCapabilities caps) throws AWTException {3834// Check arguments3835if (numBuffers < 1) {3836throw new IllegalArgumentException(3837"Number of buffers must be at least 1");3838}3839if (caps == null) {3840throw new IllegalArgumentException("No capabilities specified");3841}3842// Destroy old buffers3843if (bufferStrategy != null) {3844bufferStrategy.dispose();3845}3846if (numBuffers == 1) {3847bufferStrategy = new SingleBufferStrategy(caps);3848} else {3849SunGraphicsEnvironment sge = (SunGraphicsEnvironment)3850GraphicsEnvironment.getLocalGraphicsEnvironment();3851if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) {3852caps = new ProxyCapabilities(caps);3853}3854// assert numBuffers > 1;3855if (caps.isPageFlipping()) {3856bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps);3857} else {3858bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps);3859}3860}3861}38623863/**3864* This is a proxy capabilities class used when a FlipBufferStrategy3865* is created instead of the requested Blit strategy.3866*3867* @see sun.java2d.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer)3868*/3869private class ProxyCapabilities extends ExtendedBufferCapabilities {3870private BufferCapabilities orig;3871private ProxyCapabilities(BufferCapabilities orig) {3872super(orig.getFrontBufferCapabilities(),3873orig.getBackBufferCapabilities(),3874orig.getFlipContents() ==3875BufferCapabilities.FlipContents.BACKGROUND ?3876BufferCapabilities.FlipContents.BACKGROUND :3877BufferCapabilities.FlipContents.COPIED);3878this.orig = orig;3879}3880}38813882/**3883* @return the buffer strategy used by this component3884* @see Window#createBufferStrategy3885* @see Canvas#createBufferStrategy3886* @since 1.43887*/3888BufferStrategy getBufferStrategy() {3889return bufferStrategy;3890}38913892/**3893* @return the back buffer currently used by this component's3894* BufferStrategy. If there is no BufferStrategy or no3895* back buffer, this method returns null.3896*/3897Image getBackBuffer() {3898if (bufferStrategy != null) {3899if (bufferStrategy instanceof BltBufferStrategy) {3900BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;3901return bltBS.getBackBuffer();3902} else if (bufferStrategy instanceof FlipBufferStrategy) {3903FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;3904return flipBS.getBackBuffer();3905}3906}3907return null;3908}39093910/**3911* Inner class for flipping buffers on a component. That component must3912* be a <code>Canvas</code> or <code>Window</code>.3913* @see Canvas3914* @see Window3915* @see java.awt.image.BufferStrategy3916* @author Michael Martak3917* @since 1.43918*/3919protected class FlipBufferStrategy extends BufferStrategy {3920/**3921* The number of buffers3922*/3923protected int numBuffers; // = 03924/**3925* The buffering capabilities3926*/3927protected BufferCapabilities caps; // = null3928/**3929* The drawing buffer3930*/3931protected Image drawBuffer; // = null3932/**3933* The drawing buffer as a volatile image3934*/3935protected VolatileImage drawVBuffer; // = null3936/**3937* Whether or not the drawing buffer has been recently restored from3938* a lost state.3939*/3940protected boolean validatedContents; // = false3941/**3942* Size of the back buffers. (Note: these fields were added in 6.03943* but kept package-private to avoid exposing them in the spec.3944* None of these fields/methods really should have been marked3945* protected when they were introduced in 1.4, but now we just have3946* to live with that decision.)3947*/3948int width;3949int height;39503951/**3952* Creates a new flipping buffer strategy for this component.3953* The component must be a <code>Canvas</code> or <code>Window</code>.3954* @see Canvas3955* @see Window3956* @param numBuffers the number of buffers3957* @param caps the capabilities of the buffers3958* @exception AWTException if the capabilities supplied could not be3959* supported or met3960* @exception ClassCastException if the component is not a canvas or3961* window.3962* @exception IllegalStateException if the component has no peer3963* @exception IllegalArgumentException if {@code numBuffers} is less than two,3964* or if {@code BufferCapabilities.isPageFlipping} is not3965* {@code true}.3966* @see #createBuffers(int, BufferCapabilities)3967*/3968protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)3969throws AWTException3970{3971if (!(Component.this instanceof Window) &&3972!(Component.this instanceof Canvas))3973{3974throw new ClassCastException(3975"Component must be a Canvas or Window");3976}3977this.numBuffers = numBuffers;3978this.caps = caps;3979createBuffers(numBuffers, caps);3980}39813982/**3983* Creates one or more complex, flipping buffers with the given3984* capabilities.3985* @param numBuffers number of buffers to create; must be greater than3986* one3987* @param caps the capabilities of the buffers.3988* <code>BufferCapabilities.isPageFlipping</code> must be3989* <code>true</code>.3990* @exception AWTException if the capabilities supplied could not be3991* supported or met3992* @exception IllegalStateException if the component has no peer3993* @exception IllegalArgumentException if numBuffers is less than two,3994* or if <code>BufferCapabilities.isPageFlipping</code> is not3995* <code>true</code>.3996* @see java.awt.BufferCapabilities#isPageFlipping()3997*/3998protected void createBuffers(int numBuffers, BufferCapabilities caps)3999throws AWTException4000{4001if (numBuffers < 2) {4002throw new IllegalArgumentException(4003"Number of buffers cannot be less than two");4004} else if (peer == null) {4005throw new IllegalStateException(4006"Component must have a valid peer");4007} else if (caps == null || !caps.isPageFlipping()) {4008throw new IllegalArgumentException(4009"Page flipping capabilities must be specified");4010}40114012// save the current bounds4013width = getWidth();4014height = getHeight();40154016if (drawBuffer != null) {4017// dispose the existing backbuffers4018drawBuffer = null;4019drawVBuffer = null;4020destroyBuffers();4021// ... then recreate the backbuffers4022}40234024if (caps instanceof ExtendedBufferCapabilities) {4025ExtendedBufferCapabilities ebc =4026(ExtendedBufferCapabilities)caps;4027if (ebc.getVSync() == VSYNC_ON) {4028// if this buffer strategy is not allowed to be v-synced,4029// change the caps that we pass to the peer but keep on4030// trying to create v-synced buffers;4031// do not throw IAE here in case it is disallowed, see4032// ExtendedBufferCapabilities for more info4033if (!VSyncedBSManager.vsyncAllowed(this)) {4034caps = ebc.derive(VSYNC_DEFAULT);4035}4036}4037}40384039peer.createBuffers(numBuffers, caps);4040updateInternalBuffers();4041}40424043/**4044* Updates internal buffers (both volatile and non-volatile)4045* by requesting the back-buffer from the peer.4046*/4047private void updateInternalBuffers() {4048// get the images associated with the draw buffer4049drawBuffer = getBackBuffer();4050if (drawBuffer instanceof VolatileImage) {4051drawVBuffer = (VolatileImage)drawBuffer;4052} else {4053drawVBuffer = null;4054}4055}40564057/**4058* @return direct access to the back buffer, as an image.4059* @exception IllegalStateException if the buffers have not yet4060* been created4061*/4062protected Image getBackBuffer() {4063if (peer != null) {4064return peer.getBackBuffer();4065} else {4066throw new IllegalStateException(4067"Component must have a valid peer");4068}4069}40704071/**4072* Flipping moves the contents of the back buffer to the front buffer,4073* either by copying or by moving the video pointer.4074* @param flipAction an integer value describing the flipping action4075* for the contents of the back buffer. This should be one of the4076* values of the <code>BufferCapabilities.FlipContents</code>4077* property.4078* @exception IllegalStateException if the buffers have not yet4079* been created4080* @see java.awt.BufferCapabilities#getFlipContents()4081*/4082protected void flip(BufferCapabilities.FlipContents flipAction) {4083if (peer != null) {4084Image backBuffer = getBackBuffer();4085if (backBuffer != null) {4086peer.flip(0, 0,4087backBuffer.getWidth(null),4088backBuffer.getHeight(null), flipAction);4089}4090} else {4091throw new IllegalStateException(4092"Component must have a valid peer");4093}4094}40954096void flipSubRegion(int x1, int y1, int x2, int y2,4097BufferCapabilities.FlipContents flipAction)4098{4099if (peer != null) {4100peer.flip(x1, y1, x2, y2, flipAction);4101} else {4102throw new IllegalStateException(4103"Component must have a valid peer");4104}4105}41064107/**4108* Destroys the buffers created through this object4109*/4110protected void destroyBuffers() {4111VSyncedBSManager.releaseVsync(this);4112if (peer != null) {4113peer.destroyBuffers();4114} else {4115throw new IllegalStateException(4116"Component must have a valid peer");4117}4118}41194120/**4121* @return the buffering capabilities of this strategy4122*/4123public BufferCapabilities getCapabilities() {4124if (caps instanceof ProxyCapabilities) {4125return ((ProxyCapabilities)caps).orig;4126} else {4127return caps;4128}4129}41304131/**4132* @return the graphics on the drawing buffer. This method may not4133* be synchronized for performance reasons; use of this method by multiple4134* threads should be handled at the application level. Disposal of the4135* graphics object must be handled by the application.4136*/4137public Graphics getDrawGraphics() {4138revalidate();4139return drawBuffer.getGraphics();4140}41414142/**4143* Restore the drawing buffer if it has been lost4144*/4145protected void revalidate() {4146revalidate(true);4147}41484149void revalidate(boolean checkSize) {4150validatedContents = false;41514152if (checkSize && (getWidth() != width || getHeight() != height)) {4153// component has been resized; recreate the backbuffers4154try {4155createBuffers(numBuffers, caps);4156} catch (AWTException e) {4157// shouldn't be possible4158}4159validatedContents = true;4160}41614162// get the buffers from the peer every time since they4163// might have been replaced in response to a display change event4164updateInternalBuffers();41654166// now validate the backbuffer4167if (drawVBuffer != null) {4168GraphicsConfiguration gc =4169getGraphicsConfiguration_NoClientCode();4170int returnCode = drawVBuffer.validate(gc);4171if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {4172try {4173createBuffers(numBuffers, caps);4174} catch (AWTException e) {4175// shouldn't be possible4176}4177if (drawVBuffer != null) {4178// backbuffers were recreated, so validate again4179drawVBuffer.validate(gc);4180}4181validatedContents = true;4182} else if (returnCode == VolatileImage.IMAGE_RESTORED) {4183validatedContents = true;4184}4185}4186}41874188/**4189* @return whether the drawing buffer was lost since the last call to4190* <code>getDrawGraphics</code>4191*/4192public boolean contentsLost() {4193if (drawVBuffer == null) {4194return false;4195}4196return drawVBuffer.contentsLost();4197}41984199/**4200* @return whether the drawing buffer was recently restored from a lost4201* state and reinitialized to the default background color (white)4202*/4203public boolean contentsRestored() {4204return validatedContents;4205}42064207/**4208* Makes the next available buffer visible by either blitting or4209* flipping.4210*/4211public void show() {4212flip(caps.getFlipContents());4213}42144215/**4216* Makes specified region of the the next available buffer visible4217* by either blitting or flipping.4218*/4219void showSubRegion(int x1, int y1, int x2, int y2) {4220flipSubRegion(x1, y1, x2, y2, caps.getFlipContents());4221}42224223/**4224* {@inheritDoc}4225* @since 1.64226*/4227public void dispose() {4228if (Component.this.bufferStrategy == this) {4229Component.this.bufferStrategy = null;4230if (peer != null) {4231destroyBuffers();4232}4233}4234}42354236} // Inner class FlipBufferStrategy42374238/**4239* Inner class for blitting offscreen surfaces to a component.4240*4241* @author Michael Martak4242* @since 1.44243*/4244protected class BltBufferStrategy extends BufferStrategy {42454246/**4247* The buffering capabilities4248*/4249protected BufferCapabilities caps; // = null4250/**4251* The back buffers4252*/4253protected VolatileImage[] backBuffers; // = null4254/**4255* Whether or not the drawing buffer has been recently restored from4256* a lost state.4257*/4258protected boolean validatedContents; // = false4259/**4260* Size of the back buffers4261*/4262protected int width;4263protected int height;42644265/**4266* Insets for the hosting Component. The size of the back buffer4267* is constrained by these.4268*/4269private Insets insets;42704271/**4272* Creates a new blt buffer strategy around a component4273* @param numBuffers number of buffers to create, including the4274* front buffer4275* @param caps the capabilities of the buffers4276*/4277protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) {4278this.caps = caps;4279createBackBuffers(numBuffers - 1);4280}42814282/**4283* {@inheritDoc}4284* @since 1.64285*/4286public void dispose() {4287if (backBuffers != null) {4288for (int counter = backBuffers.length - 1; counter >= 0;4289counter--) {4290if (backBuffers[counter] != null) {4291backBuffers[counter].flush();4292backBuffers[counter] = null;4293}4294}4295}4296if (Component.this.bufferStrategy == this) {4297Component.this.bufferStrategy = null;4298}4299}43004301/**4302* Creates the back buffers4303*/4304protected void createBackBuffers(int numBuffers) {4305if (numBuffers == 0) {4306backBuffers = null;4307} else {4308// save the current bounds4309width = getWidth();4310height = getHeight();4311insets = getInsets_NoClientCode();4312int iWidth = width - insets.left - insets.right;4313int iHeight = height - insets.top - insets.bottom;43144315// It is possible for the component's width and/or height4316// to be 0 here. Force the size of the backbuffers to4317// be > 0 so that creating the image won't fail.4318iWidth = Math.max(1, iWidth);4319iHeight = Math.max(1, iHeight);4320if (backBuffers == null) {4321backBuffers = new VolatileImage[numBuffers];4322} else {4323// flush any existing backbuffers4324for (int i = 0; i < numBuffers; i++) {4325if (backBuffers[i] != null) {4326backBuffers[i].flush();4327backBuffers[i] = null;4328}4329}4330}43314332// create the backbuffers4333for (int i = 0; i < numBuffers; i++) {4334backBuffers[i] = createVolatileImage(iWidth, iHeight);4335}4336}4337}43384339/**4340* @return the buffering capabilities of this strategy4341*/4342public BufferCapabilities getCapabilities() {4343return caps;4344}43454346/**4347* @return the draw graphics4348*/4349public Graphics getDrawGraphics() {4350revalidate();4351Image backBuffer = getBackBuffer();4352if (backBuffer == null) {4353return getGraphics();4354}4355SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();4356g.constrain(-insets.left, -insets.top,4357backBuffer.getWidth(null) + insets.left,4358backBuffer.getHeight(null) + insets.top);4359return g;4360}43614362/**4363* @return direct access to the back buffer, as an image.4364* If there is no back buffer, returns null.4365*/4366Image getBackBuffer() {4367if (backBuffers != null) {4368return backBuffers[backBuffers.length - 1];4369} else {4370return null;4371}4372}43734374/**4375* Makes the next available buffer visible.4376*/4377public void show() {4378showSubRegion(insets.left, insets.top,4379width - insets.right,4380height - insets.bottom);4381}43824383/**4384* Package-private method to present a specific rectangular area4385* of this buffer. This class currently shows only the entire4386* buffer, by calling showSubRegion() with the full dimensions of4387* the buffer. Subclasses (e.g., BltSubRegionBufferStrategy4388* and FlipSubRegionBufferStrategy) may have region-specific show4389* methods that call this method with actual sub regions of the4390* buffer.4391*/4392void showSubRegion(int x1, int y1, int x2, int y2) {4393if (backBuffers == null) {4394return;4395}4396// Adjust location to be relative to client area.4397x1 -= insets.left;4398x2 -= insets.left;4399y1 -= insets.top;4400y2 -= insets.top;4401Graphics g = getGraphics_NoClientCode();4402if (g == null) {4403// Not showing, bail4404return;4405}4406try {4407// First image copy is in terms of Frame's coordinates, need4408// to translate to client area.4409g.translate(insets.left, insets.top);4410for (int i = 0; i < backBuffers.length; i++) {4411g.drawImage(backBuffers[i],4412x1, y1, x2, y2,4413x1, y1, x2, y2,4414null);4415g.dispose();4416g = null;4417g = backBuffers[i].getGraphics();4418}4419} finally {4420if (g != null) {4421g.dispose();4422}4423}4424}44254426/**4427* Restore the drawing buffer if it has been lost4428*/4429protected void revalidate() {4430revalidate(true);4431}44324433void revalidate(boolean checkSize) {4434validatedContents = false;44354436if (backBuffers == null) {4437return;4438}44394440if (checkSize) {4441Insets insets = getInsets_NoClientCode();4442if (getWidth() != width || getHeight() != height ||4443!insets.equals(this.insets)) {4444// component has been resized; recreate the backbuffers4445createBackBuffers(backBuffers.length);4446validatedContents = true;4447}4448}44494450// now validate the backbuffer4451GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();4452int returnCode =4453backBuffers[backBuffers.length - 1].validate(gc);4454if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {4455if (checkSize) {4456createBackBuffers(backBuffers.length);4457// backbuffers were recreated, so validate again4458backBuffers[backBuffers.length - 1].validate(gc);4459}4460// else case means we're called from Swing on the toolkit4461// thread, don't recreate buffers as that'll deadlock4462// (creating VolatileImages invokes getting GraphicsConfig4463// which grabs treelock).4464validatedContents = true;4465} else if (returnCode == VolatileImage.IMAGE_RESTORED) {4466validatedContents = true;4467}4468}44694470/**4471* @return whether the drawing buffer was lost since the last call to4472* <code>getDrawGraphics</code>4473*/4474public boolean contentsLost() {4475if (backBuffers == null) {4476return false;4477} else {4478return backBuffers[backBuffers.length - 1].contentsLost();4479}4480}44814482/**4483* @return whether the drawing buffer was recently restored from a lost4484* state and reinitialized to the default background color (white)4485*/4486public boolean contentsRestored() {4487return validatedContents;4488}4489} // Inner class BltBufferStrategy44904491/**4492* Private class to perform sub-region flipping.4493*/4494private class FlipSubRegionBufferStrategy extends FlipBufferStrategy4495implements SubRegionShowable4496{44974498protected FlipSubRegionBufferStrategy(int numBuffers,4499BufferCapabilities caps)4500throws AWTException4501{4502super(numBuffers, caps);4503}45044505public void show(int x1, int y1, int x2, int y2) {4506showSubRegion(x1, y1, x2, y2);4507}45084509// This is invoked by Swing on the toolkit thread.4510public boolean showIfNotLost(int x1, int y1, int x2, int y2) {4511if (!contentsLost()) {4512showSubRegion(x1, y1, x2, y2);4513return !contentsLost();4514}4515return false;4516}4517}45184519/**4520* Private class to perform sub-region blitting. Swing will use4521* this subclass via the SubRegionShowable interface in order to4522* copy only the area changed during a repaint.4523* See javax.swing.BufferStrategyPaintManager.4524*/4525private class BltSubRegionBufferStrategy extends BltBufferStrategy4526implements SubRegionShowable4527{45284529protected BltSubRegionBufferStrategy(int numBuffers,4530BufferCapabilities caps)4531{4532super(numBuffers, caps);4533}45344535public void show(int x1, int y1, int x2, int y2) {4536showSubRegion(x1, y1, x2, y2);4537}45384539// This method is called by Swing on the toolkit thread.4540public boolean showIfNotLost(int x1, int y1, int x2, int y2) {4541if (!contentsLost()) {4542showSubRegion(x1, y1, x2, y2);4543return !contentsLost();4544}4545return false;4546}4547}45484549/**4550* Inner class for flipping buffers on a component. That component must4551* be a <code>Canvas</code> or <code>Window</code>.4552* @see Canvas4553* @see Window4554* @see java.awt.image.BufferStrategy4555* @author Michael Martak4556* @since 1.44557*/4558private class SingleBufferStrategy extends BufferStrategy {45594560private BufferCapabilities caps;45614562public SingleBufferStrategy(BufferCapabilities caps) {4563this.caps = caps;4564}4565public BufferCapabilities getCapabilities() {4566return caps;4567}4568public Graphics getDrawGraphics() {4569return getGraphics();4570}4571public boolean contentsLost() {4572return false;4573}4574public boolean contentsRestored() {4575return false;4576}4577public void show() {4578// Do nothing4579}4580} // Inner class SingleBufferStrategy45814582/**4583* Sets whether or not paint messages received from the operating system4584* should be ignored. This does not affect paint events generated in4585* software by the AWT, unless they are an immediate response to an4586* OS-level paint message.4587* <p>4588* This is useful, for example, if running under full-screen mode and4589* better performance is desired, or if page-flipping is used as the4590* buffer strategy.4591*4592* @since 1.44593* @see #getIgnoreRepaint4594* @see Canvas#createBufferStrategy4595* @see Window#createBufferStrategy4596* @see java.awt.image.BufferStrategy4597* @see GraphicsDevice#setFullScreenWindow4598*/4599public void setIgnoreRepaint(boolean ignoreRepaint) {4600this.ignoreRepaint = ignoreRepaint;4601}46024603/**4604* @return whether or not paint messages received from the operating system4605* should be ignored.4606*4607* @since 1.44608* @see #setIgnoreRepaint4609*/4610public boolean getIgnoreRepaint() {4611return ignoreRepaint;4612}46134614/**4615* Checks whether this component "contains" the specified point,4616* where <code>x</code> and <code>y</code> are defined to be4617* relative to the coordinate system of this component.4618* @param x the <i>x</i> coordinate of the point4619* @param y the <i>y</i> coordinate of the point4620* @see #getComponentAt(int, int)4621* @since JDK1.14622*/4623public boolean contains(int x, int y) {4624return inside(x, y);4625}46264627/**4628* @deprecated As of JDK version 1.1,4629* replaced by contains(int, int).4630*/4631@Deprecated4632public boolean inside(int x, int y) {4633return (x >= 0) && (x < width) && (y >= 0) && (y < height);4634}46354636/**4637* Checks whether this component "contains" the specified point,4638* where the point's <i>x</i> and <i>y</i> coordinates are defined4639* to be relative to the coordinate system of this component.4640* @param p the point4641* @throws NullPointerException if {@code p} is {@code null}4642* @see #getComponentAt(Point)4643* @since JDK1.14644*/4645public boolean contains(Point p) {4646return contains(p.x, p.y);4647}46484649/**4650* Determines if this component or one of its immediate4651* subcomponents contains the (<i>x</i>, <i>y</i>) location,4652* and if so, returns the containing component. This method only4653* looks one level deep. If the point (<i>x</i>, <i>y</i>) is4654* inside a subcomponent that itself has subcomponents, it does not4655* go looking down the subcomponent tree.4656* <p>4657* The <code>locate</code> method of <code>Component</code> simply4658* returns the component itself if the (<i>x</i>, <i>y</i>)4659* coordinate location is inside its bounding box, and <code>null</code>4660* otherwise.4661* @param x the <i>x</i> coordinate4662* @param y the <i>y</i> coordinate4663* @return the component or subcomponent that contains the4664* (<i>x</i>, <i>y</i>) location;4665* <code>null</code> if the location4666* is outside this component4667* @see #contains(int, int)4668* @since JDK1.04669*/4670public Component getComponentAt(int x, int y) {4671return locate(x, y);4672}46734674/**4675* @deprecated As of JDK version 1.1,4676* replaced by getComponentAt(int, int).4677*/4678@Deprecated4679public Component locate(int x, int y) {4680return contains(x, y) ? this : null;4681}46824683/**4684* Returns the component or subcomponent that contains the4685* specified point.4686* @param p the point4687* @see java.awt.Component#contains4688* @since JDK1.14689*/4690public Component getComponentAt(Point p) {4691return getComponentAt(p.x, p.y);4692}46934694/**4695* @deprecated As of JDK version 1.1,4696* replaced by <code>dispatchEvent(AWTEvent e)</code>.4697*/4698@Deprecated4699public void deliverEvent(Event e) {4700postEvent(e);4701}47024703/**4704* Dispatches an event to this component or one of its sub components.4705* Calls <code>processEvent</code> before returning for 1.1-style4706* events which have been enabled for the <code>Component</code>.4707* @param e the event4708*/4709public final void dispatchEvent(AWTEvent e) {4710dispatchEventImpl(e);4711}47124713@SuppressWarnings("deprecation")4714void dispatchEventImpl(AWTEvent e) {4715int id = e.getID();47164717// Check that this component belongs to this app-context4718AppContext compContext = appContext;4719if (compContext != null && !compContext.equals(AppContext.getAppContext())) {4720if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {4721eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");4722}4723}47244725if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {4726eventLog.finest("{0}", e);4727}47284729/*4730* 0. Set timestamp and modifiers of current event.4731*/4732if (!(e instanceof KeyEvent)) {4733// Timestamp of a key event is set later in DKFM.preDispatchKeyEvent(KeyEvent).4734EventQueue.setCurrentEventAndMostRecentTime(e);4735}47364737/*4738* 1. Pre-dispatchers. Do any necessary retargeting/reordering here4739* before we notify AWTEventListeners.4740*/47414742if (e instanceof SunDropTargetEvent) {4743((SunDropTargetEvent)e).dispatch();4744return;4745}47464747if (!e.focusManagerIsDispatching) {4748// Invoke the private focus retargeting method which provides4749// lightweight Component support4750if (e.isPosted) {4751e = KeyboardFocusManager.retargetFocusEvent(e);4752e.isPosted = true;4753}47544755// Now, with the event properly targeted to a lightweight4756// descendant if necessary, invoke the public focus retargeting4757// and dispatching function4758if (KeyboardFocusManager.getCurrentKeyboardFocusManager().4759dispatchEvent(e))4760{4761return;4762}4763}4764if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {4765focusLog.finest("" + e);4766}4767// MouseWheel may need to be retargeted here so that4768// AWTEventListener sees the event go to the correct4769// Component. If the MouseWheelEvent needs to go to an ancestor,4770// the event is dispatched to the ancestor, and dispatching here4771// stops.4772if (id == MouseEvent.MOUSE_WHEEL &&4773(!eventTypeEnabled(id)) &&4774(peer != null && !peer.handlesWheelScrolling()) &&4775(dispatchMouseWheelToAncestor((MouseWheelEvent)e)))4776{4777return;4778}47794780/*4781* 2. Allow the Toolkit to pass this to AWTEventListeners.4782*/4783Toolkit toolkit = Toolkit.getDefaultToolkit();4784toolkit.notifyAWTEventListeners(e);478547864787/*4788* 3. If no one has consumed a key event, allow the4789* KeyboardFocusManager to process it.4790*/4791if (!e.isConsumed()) {4792if (e instanceof java.awt.event.KeyEvent) {4793KeyboardFocusManager.getCurrentKeyboardFocusManager().4794processKeyEvent(this, (KeyEvent)e);4795if (e.isConsumed()) {4796return;4797}4798}4799}48004801/*4802* 4. Allow input methods to process the event4803*/4804if (areInputMethodsEnabled()) {4805// We need to pass on InputMethodEvents since some host4806// input method adapters send them through the Java4807// event queue instead of directly to the component,4808// and the input context also handles the Java composition window4809if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea))4810||4811// Otherwise, we only pass on input and focus events, because4812// a) input methods shouldn't know about semantic or component-level events4813// b) passing on the events takes time4814// c) isConsumed() is always true for semantic events.4815(e instanceof InputEvent) || (e instanceof FocusEvent)) {4816InputContext inputContext = getInputContext();481748184819if (inputContext != null) {4820inputContext.dispatchEvent(e);4821if (e.isConsumed()) {4822if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) {4823focusLog.finest("3579: Skipping " + e);4824}4825return;4826}4827}4828}4829} else {4830// When non-clients get focus, we need to explicitly disable the native4831// input method. The native input method is actually not disabled when4832// the active/passive/peered clients loose focus.4833if (id == FocusEvent.FOCUS_GAINED) {4834InputContext inputContext = getInputContext();4835if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) {4836((sun.awt.im.InputContext)inputContext).disableNativeIM();4837}4838}4839}484048414842/*4843* 5. Pre-process any special events before delivery4844*/4845switch(id) {4846// Handling of the PAINT and UPDATE events is now done in the4847// peer's handleEvent() method so the background can be cleared4848// selectively for non-native components on Windows only.4849// - [email protected], 5-8-9848504851case KeyEvent.KEY_PRESSED:4852case KeyEvent.KEY_RELEASED:4853Container p = (Container)((this instanceof Container) ? this : parent);4854if (p != null) {4855p.preProcessKeyEvent((KeyEvent)e);4856if (e.isConsumed()) {4857if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {4858focusLog.finest("Pre-process consumed event");4859}4860return;4861}4862}4863break;48644865case WindowEvent.WINDOW_CLOSING:4866if (toolkit instanceof WindowClosingListener) {4867windowClosingException = ((WindowClosingListener)4868toolkit).windowClosingNotify((WindowEvent)e);4869if (checkWindowClosingException()) {4870return;4871}4872}4873break;48744875default:4876break;4877}48784879/*4880* 6. Deliver event for normal processing4881*/4882if (newEventsOnly) {4883// Filtering needs to really be moved to happen at a lower4884// level in order to get maximum performance gain; it is4885// here temporarily to ensure the API spec is honored.4886//4887if (eventEnabled(e)) {4888processEvent(e);4889}4890} else if (id == MouseEvent.MOUSE_WHEEL) {4891// newEventsOnly will be false for a listenerless ScrollPane, but4892// MouseWheelEvents still need to be dispatched to it so scrolling4893// can be done.4894autoProcessMouseWheel((MouseWheelEvent)e);4895} else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) {4896//4897// backward compatibility4898//4899Event olde = e.convertToOld();4900if (olde != null) {4901int key = olde.key;4902int modifiers = olde.modifiers;49034904postEvent(olde);4905if (olde.isConsumed()) {4906e.consume();4907}4908// if target changed key or modifier values, copy them4909// back to original event4910//4911switch(olde.id) {4912case Event.KEY_PRESS:4913case Event.KEY_RELEASE:4914case Event.KEY_ACTION:4915case Event.KEY_ACTION_RELEASE:4916if (olde.key != key) {4917((KeyEvent)e).setKeyChar(olde.getKeyEventChar());4918}4919if (olde.modifiers != modifiers) {4920((KeyEvent)e).setModifiers(olde.modifiers);4921}4922break;4923default:4924break;4925}4926}4927}49284929/*4930* 8. Special handling for 4061116 : Hook for browser to close modal4931* dialogs.4932*/4933if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) {4934if (toolkit instanceof WindowClosingListener) {4935windowClosingException =4936((WindowClosingListener)toolkit).4937windowClosingDelivered((WindowEvent)e);4938if (checkWindowClosingException()) {4939return;4940}4941}4942}49434944/*4945* 9. Allow the peer to process the event.4946* Except KeyEvents, they will be processed by peer after4947* all KeyEventPostProcessors4948* (see DefaultKeyboardFocusManager.dispatchKeyEvent())4949*/4950if (!(e instanceof KeyEvent)) {4951ComponentPeer tpeer = peer;4952if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) {4953// if focus owner is lightweight then its native container4954// processes event4955Component source = (Component)e.getSource();4956if (source != null) {4957Container target = source.getNativeContainer();4958if (target != null) {4959tpeer = target.getPeer();4960}4961}4962}4963if (tpeer != null) {4964tpeer.handleEvent(e);4965}4966}49674968if (SunToolkit.isTouchKeyboardAutoShowEnabled() &&4969(toolkit instanceof SunToolkit) &&4970((e instanceof MouseEvent) || (e instanceof FocusEvent))) {4971((SunToolkit)toolkit).showOrHideTouchKeyboard(this, e);4972}4973} // dispatchEventImpl()49744975/*4976* If newEventsOnly is false, method is called so that ScrollPane can4977* override it and handle common-case mouse wheel scrolling. NOP4978* for Component.4979*/4980void autoProcessMouseWheel(MouseWheelEvent e) {}49814982/*4983* Dispatch given MouseWheelEvent to the first ancestor for which4984* MouseWheelEvents are enabled.4985*4986* Returns whether or not event was dispatched to an ancestor4987*/4988boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {4989int newX, newY;4990newX = e.getX() + getX(); // Coordinates take into account at least4991newY = e.getY() + getY(); // the cursor's position relative to this4992// Component (e.getX()), and this Component's4993// position relative to its parent.4994MouseWheelEvent newMWE;49954996if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {4997eventLog.finest("dispatchMouseWheelToAncestor");4998eventLog.finest("orig event src is of " + e.getSource().getClass());4999}50005001/* parent field for Window refers to the owning Window.5002* MouseWheelEvents should NOT be propagated into owning Windows5003*/5004synchronized (getTreeLock()) {5005Container anc = getParent();5006while (anc != null && !anc.eventEnabled(e)) {5007// fix coordinates to be relative to new event source5008newX += anc.getX();5009newY += anc.getY();50105011if (!(anc instanceof Window)) {5012anc = anc.getParent();5013}5014else {5015break;5016}5017}50185019if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {5020eventLog.finest("new event src is " + anc.getClass());5021}50225023if (anc != null && anc.eventEnabled(e)) {5024// Change event to be from new source, with new x,y5025// For now, just create a new event - yucky50265027newMWE = new MouseWheelEvent(anc, // new source5028e.getID(),5029e.getWhen(),5030e.getModifiers(),5031newX, // x relative to new source5032newY, // y relative to new source5033e.getXOnScreen(),5034e.getYOnScreen(),5035e.getClickCount(),5036e.isPopupTrigger(),5037e.getScrollType(),5038e.getScrollAmount(),5039e.getWheelRotation(),5040e.getPreciseWheelRotation());5041((AWTEvent)e).copyPrivateDataInto(newMWE);5042// When dispatching a wheel event to5043// ancestor, there is no need trying to find descendant5044// lightweights to dispatch event to.5045// If we dispatch the event to toplevel ancestor,5046// this could encolse the loop: 6480024.5047anc.dispatchEventToSelf(newMWE);5048if (newMWE.isConsumed()) {5049e.consume();5050}5051return true;5052}5053}5054return false;5055}50565057boolean checkWindowClosingException() {5058if (windowClosingException != null) {5059if (this instanceof Dialog) {5060((Dialog)this).interruptBlocking();5061} else {5062windowClosingException.fillInStackTrace();5063windowClosingException.printStackTrace();5064windowClosingException = null;5065}5066return true;5067}5068return false;5069}50705071boolean areInputMethodsEnabled() {5072// in 1.2, we assume input method support is required for all5073// components that handle key events, but components can turn off5074// input methods by calling enableInputMethods(false).5075return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) &&5076((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null);5077}50785079// REMIND: remove when filtering is handled at lower level5080boolean eventEnabled(AWTEvent e) {5081return eventTypeEnabled(e.id);5082}50835084boolean eventTypeEnabled(int type) {5085switch(type) {5086case ComponentEvent.COMPONENT_MOVED:5087case ComponentEvent.COMPONENT_RESIZED:5088case ComponentEvent.COMPONENT_SHOWN:5089case ComponentEvent.COMPONENT_HIDDEN:5090if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||5091componentListener != null) {5092return true;5093}5094break;5095case FocusEvent.FOCUS_GAINED:5096case FocusEvent.FOCUS_LOST:5097if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 ||5098focusListener != null) {5099return true;5100}5101break;5102case KeyEvent.KEY_PRESSED:5103case KeyEvent.KEY_RELEASED:5104case KeyEvent.KEY_TYPED:5105if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 ||5106keyListener != null) {5107return true;5108}5109break;5110case MouseEvent.MOUSE_PRESSED:5111case MouseEvent.MOUSE_RELEASED:5112case MouseEvent.MOUSE_ENTERED:5113case MouseEvent.MOUSE_EXITED:5114case MouseEvent.MOUSE_CLICKED:5115if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 ||5116mouseListener != null) {5117return true;5118}5119break;5120case MouseEvent.MOUSE_MOVED:5121case MouseEvent.MOUSE_DRAGGED:5122if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 ||5123mouseMotionListener != null) {5124return true;5125}5126break;5127case MouseEvent.MOUSE_WHEEL:5128if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 ||5129mouseWheelListener != null) {5130return true;5131}5132break;5133case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:5134case InputMethodEvent.CARET_POSITION_CHANGED:5135if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 ||5136inputMethodListener != null) {5137return true;5138}5139break;5140case HierarchyEvent.HIERARCHY_CHANGED:5141if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||5142hierarchyListener != null) {5143return true;5144}5145break;5146case HierarchyEvent.ANCESTOR_MOVED:5147case HierarchyEvent.ANCESTOR_RESIZED:5148if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||5149hierarchyBoundsListener != null) {5150return true;5151}5152break;5153case ActionEvent.ACTION_PERFORMED:5154if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) {5155return true;5156}5157break;5158case TextEvent.TEXT_VALUE_CHANGED:5159if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) {5160return true;5161}5162break;5163case ItemEvent.ITEM_STATE_CHANGED:5164if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) {5165return true;5166}5167break;5168case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED:5169if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) {5170return true;5171}5172break;5173default:5174break;5175}5176//5177// Always pass on events defined by external programs.5178//5179if (type > AWTEvent.RESERVED_ID_MAX) {5180return true;5181}5182return false;5183}51845185/**5186* @deprecated As of JDK version 1.1,5187* replaced by dispatchEvent(AWTEvent).5188*/5189@Deprecated5190public boolean postEvent(Event e) {5191ComponentPeer peer = this.peer;51925193if (handleEvent(e)) {5194e.consume();5195return true;5196}51975198Component parent = this.parent;5199int eventx = e.x;5200int eventy = e.y;5201if (parent != null) {5202e.translate(x, y);5203if (parent.postEvent(e)) {5204e.consume();5205return true;5206}5207// restore coords5208e.x = eventx;5209e.y = eventy;5210}5211return false;5212}52135214// Event source interfaces52155216/**5217* Adds the specified component listener to receive component events from5218* this component.5219* If listener <code>l</code> is <code>null</code>,5220* no exception is thrown and no action is performed.5221* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5222* >AWT Threading Issues</a> for details on AWT's threading model.5223*5224* @param l the component listener5225* @see java.awt.event.ComponentEvent5226* @see java.awt.event.ComponentListener5227* @see #removeComponentListener5228* @see #getComponentListeners5229* @since JDK1.15230*/5231public synchronized void addComponentListener(ComponentListener l) {5232if (l == null) {5233return;5234}5235componentListener = AWTEventMulticaster.add(componentListener, l);5236newEventsOnly = true;5237}52385239/**5240* Removes the specified component listener so that it no longer5241* receives component events from this component. This method performs5242* no function, nor does it throw an exception, if the listener5243* specified by the argument was not previously added to this component.5244* If listener <code>l</code> is <code>null</code>,5245* no exception is thrown and no action is performed.5246* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5247* >AWT Threading Issues</a> for details on AWT's threading model.5248* @param l the component listener5249* @see java.awt.event.ComponentEvent5250* @see java.awt.event.ComponentListener5251* @see #addComponentListener5252* @see #getComponentListeners5253* @since JDK1.15254*/5255public synchronized void removeComponentListener(ComponentListener l) {5256if (l == null) {5257return;5258}5259componentListener = AWTEventMulticaster.remove(componentListener, l);5260}52615262/**5263* Returns an array of all the component listeners5264* registered on this component.5265*5266* @return all <code>ComponentListener</code>s of this component5267* or an empty array if no component5268* listeners are currently registered5269*5270* @see #addComponentListener5271* @see #removeComponentListener5272* @since 1.45273*/5274public synchronized ComponentListener[] getComponentListeners() {5275return getListeners(ComponentListener.class);5276}52775278/**5279* Adds the specified focus listener to receive focus events from5280* this component when this component gains input focus.5281* If listener <code>l</code> is <code>null</code>,5282* no exception is thrown and no action is performed.5283* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5284* >AWT Threading Issues</a> for details on AWT's threading model.5285*5286* @param l the focus listener5287* @see java.awt.event.FocusEvent5288* @see java.awt.event.FocusListener5289* @see #removeFocusListener5290* @see #getFocusListeners5291* @since JDK1.15292*/5293public synchronized void addFocusListener(FocusListener l) {5294if (l == null) {5295return;5296}5297focusListener = AWTEventMulticaster.add(focusListener, l);5298newEventsOnly = true;52995300// if this is a lightweight component, enable focus events5301// in the native container.5302if (peer instanceof LightweightPeer) {5303parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);5304}5305}53065307/**5308* Removes the specified focus listener so that it no longer5309* receives focus events from this component. This method performs5310* no function, nor does it throw an exception, if the listener5311* specified by the argument was not previously added to this component.5312* If listener <code>l</code> is <code>null</code>,5313* no exception is thrown and no action is performed.5314* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5315* >AWT Threading Issues</a> for details on AWT's threading model.5316*5317* @param l the focus listener5318* @see java.awt.event.FocusEvent5319* @see java.awt.event.FocusListener5320* @see #addFocusListener5321* @see #getFocusListeners5322* @since JDK1.15323*/5324public synchronized void removeFocusListener(FocusListener l) {5325if (l == null) {5326return;5327}5328focusListener = AWTEventMulticaster.remove(focusListener, l);5329}53305331/**5332* Returns an array of all the focus listeners5333* registered on this component.5334*5335* @return all of this component's <code>FocusListener</code>s5336* or an empty array if no component5337* listeners are currently registered5338*5339* @see #addFocusListener5340* @see #removeFocusListener5341* @since 1.45342*/5343public synchronized FocusListener[] getFocusListeners() {5344return getListeners(FocusListener.class);5345}53465347/**5348* Adds the specified hierarchy listener to receive hierarchy changed5349* events from this component when the hierarchy to which this container5350* belongs changes.5351* If listener <code>l</code> is <code>null</code>,5352* no exception is thrown and no action is performed.5353* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5354* >AWT Threading Issues</a> for details on AWT's threading model.5355*5356* @param l the hierarchy listener5357* @see java.awt.event.HierarchyEvent5358* @see java.awt.event.HierarchyListener5359* @see #removeHierarchyListener5360* @see #getHierarchyListeners5361* @since 1.35362*/5363public void addHierarchyListener(HierarchyListener l) {5364if (l == null) {5365return;5366}5367boolean notifyAncestors;5368synchronized (this) {5369notifyAncestors =5370(hierarchyListener == null &&5371(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);5372hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);5373notifyAncestors = (notifyAncestors && hierarchyListener != null);5374newEventsOnly = true;5375}5376if (notifyAncestors) {5377synchronized (getTreeLock()) {5378adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,53791);5380}5381}5382}53835384/**5385* Removes the specified hierarchy listener so that it no longer5386* receives hierarchy changed events from this component. This method5387* performs no function, nor does it throw an exception, if the listener5388* specified by the argument was not previously added to this component.5389* If listener <code>l</code> is <code>null</code>,5390* no exception is thrown and no action is performed.5391* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5392* >AWT Threading Issues</a> for details on AWT's threading model.5393*5394* @param l the hierarchy listener5395* @see java.awt.event.HierarchyEvent5396* @see java.awt.event.HierarchyListener5397* @see #addHierarchyListener5398* @see #getHierarchyListeners5399* @since 1.35400*/5401public void removeHierarchyListener(HierarchyListener l) {5402if (l == null) {5403return;5404}5405boolean notifyAncestors;5406synchronized (this) {5407notifyAncestors =5408(hierarchyListener != null &&5409(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);5410hierarchyListener =5411AWTEventMulticaster.remove(hierarchyListener, l);5412notifyAncestors = (notifyAncestors && hierarchyListener == null);5413}5414if (notifyAncestors) {5415synchronized (getTreeLock()) {5416adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,5417-1);5418}5419}5420}54215422/**5423* Returns an array of all the hierarchy listeners5424* registered on this component.5425*5426* @return all of this component's <code>HierarchyListener</code>s5427* or an empty array if no hierarchy5428* listeners are currently registered5429*5430* @see #addHierarchyListener5431* @see #removeHierarchyListener5432* @since 1.45433*/5434public synchronized HierarchyListener[] getHierarchyListeners() {5435return getListeners(HierarchyListener.class);5436}54375438/**5439* Adds the specified hierarchy bounds listener to receive hierarchy5440* bounds events from this component when the hierarchy to which this5441* container belongs changes.5442* If listener <code>l</code> is <code>null</code>,5443* no exception is thrown and no action is performed.5444* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5445* >AWT Threading Issues</a> for details on AWT's threading model.5446*5447* @param l the hierarchy bounds listener5448* @see java.awt.event.HierarchyEvent5449* @see java.awt.event.HierarchyBoundsListener5450* @see #removeHierarchyBoundsListener5451* @see #getHierarchyBoundsListeners5452* @since 1.35453*/5454public void addHierarchyBoundsListener(HierarchyBoundsListener l) {5455if (l == null) {5456return;5457}5458boolean notifyAncestors;5459synchronized (this) {5460notifyAncestors =5461(hierarchyBoundsListener == null &&5462(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);5463hierarchyBoundsListener =5464AWTEventMulticaster.add(hierarchyBoundsListener, l);5465notifyAncestors = (notifyAncestors &&5466hierarchyBoundsListener != null);5467newEventsOnly = true;5468}5469if (notifyAncestors) {5470synchronized (getTreeLock()) {5471adjustListeningChildrenOnParent(5472AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);5473}5474}5475}54765477/**5478* Removes the specified hierarchy bounds listener so that it no longer5479* receives hierarchy bounds events from this component. This method5480* performs no function, nor does it throw an exception, if the listener5481* specified by the argument was not previously added to this component.5482* If listener <code>l</code> is <code>null</code>,5483* no exception is thrown and no action is performed.5484* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5485* >AWT Threading Issues</a> for details on AWT's threading model.5486*5487* @param l the hierarchy bounds listener5488* @see java.awt.event.HierarchyEvent5489* @see java.awt.event.HierarchyBoundsListener5490* @see #addHierarchyBoundsListener5491* @see #getHierarchyBoundsListeners5492* @since 1.35493*/5494public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {5495if (l == null) {5496return;5497}5498boolean notifyAncestors;5499synchronized (this) {5500notifyAncestors =5501(hierarchyBoundsListener != null &&5502(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);5503hierarchyBoundsListener =5504AWTEventMulticaster.remove(hierarchyBoundsListener, l);5505notifyAncestors = (notifyAncestors &&5506hierarchyBoundsListener == null);5507}5508if (notifyAncestors) {5509synchronized (getTreeLock()) {5510adjustListeningChildrenOnParent(5511AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1);5512}5513}5514}55155516// Should only be called while holding the tree lock5517int numListening(long mask) {5518// One mask or the other, but not neither or both.5519if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {5520if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) &&5521(mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK))5522{5523eventLog.fine("Assertion failed");5524}5525}5526if ((mask == AWTEvent.HIERARCHY_EVENT_MASK &&5527(hierarchyListener != null ||5528(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) ||5529(mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK &&5530(hierarchyBoundsListener != null ||5531(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) {5532return 1;5533} else {5534return 0;5535}5536}55375538// Should only be called while holding tree lock5539int countHierarchyMembers() {5540return 1;5541}5542// Should only be called while holding the tree lock5543int createHierarchyEvents(int id, Component changed,5544Container changedParent, long changeFlags,5545boolean enabledOnToolkit) {5546switch (id) {5547case HierarchyEvent.HIERARCHY_CHANGED:5548if (hierarchyListener != null ||5549(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||5550enabledOnToolkit) {5551HierarchyEvent e = new HierarchyEvent(this, id, changed,5552changedParent,5553changeFlags);5554dispatchEvent(e);5555return 1;5556}5557break;5558case HierarchyEvent.ANCESTOR_MOVED:5559case HierarchyEvent.ANCESTOR_RESIZED:5560if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {5561if (changeFlags != 0) {5562eventLog.fine("Assertion (changeFlags == 0) failed");5563}5564}5565if (hierarchyBoundsListener != null ||5566(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 ||5567enabledOnToolkit) {5568HierarchyEvent e = new HierarchyEvent(this, id, changed,5569changedParent);5570dispatchEvent(e);5571return 1;5572}5573break;5574default:5575// assert false5576if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {5577eventLog.fine("This code must never be reached");5578}5579break;5580}5581return 0;5582}55835584/**5585* Returns an array of all the hierarchy bounds listeners5586* registered on this component.5587*5588* @return all of this component's <code>HierarchyBoundsListener</code>s5589* or an empty array if no hierarchy bounds5590* listeners are currently registered5591*5592* @see #addHierarchyBoundsListener5593* @see #removeHierarchyBoundsListener5594* @since 1.45595*/5596public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {5597return getListeners(HierarchyBoundsListener.class);5598}55995600/*5601* Should only be called while holding the tree lock.5602* It's added only for overriding in java.awt.Window5603* because parent in Window is owner.5604*/5605void adjustListeningChildrenOnParent(long mask, int num) {5606if (parent != null) {5607parent.adjustListeningChildren(mask, num);5608}5609}56105611/**5612* Adds the specified key listener to receive key events from5613* this component.5614* If l is null, no exception is thrown and no action is performed.5615* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5616* >AWT Threading Issues</a> for details on AWT's threading model.5617*5618* @param l the key listener.5619* @see java.awt.event.KeyEvent5620* @see java.awt.event.KeyListener5621* @see #removeKeyListener5622* @see #getKeyListeners5623* @since JDK1.15624*/5625public synchronized void addKeyListener(KeyListener l) {5626if (l == null) {5627return;5628}5629keyListener = AWTEventMulticaster.add(keyListener, l);5630newEventsOnly = true;56315632// if this is a lightweight component, enable key events5633// in the native container.5634if (peer instanceof LightweightPeer) {5635parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);5636}5637}56385639/**5640* Removes the specified key listener so that it no longer5641* receives key events from this component. This method performs5642* no function, nor does it throw an exception, if the listener5643* specified by the argument was not previously added to this component.5644* If listener <code>l</code> is <code>null</code>,5645* no exception is thrown and no action is performed.5646* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5647* >AWT Threading Issues</a> for details on AWT's threading model.5648*5649* @param l the key listener5650* @see java.awt.event.KeyEvent5651* @see java.awt.event.KeyListener5652* @see #addKeyListener5653* @see #getKeyListeners5654* @since JDK1.15655*/5656public synchronized void removeKeyListener(KeyListener l) {5657if (l == null) {5658return;5659}5660keyListener = AWTEventMulticaster.remove(keyListener, l);5661}56625663/**5664* Returns an array of all the key listeners5665* registered on this component.5666*5667* @return all of this component's <code>KeyListener</code>s5668* or an empty array if no key5669* listeners are currently registered5670*5671* @see #addKeyListener5672* @see #removeKeyListener5673* @since 1.45674*/5675public synchronized KeyListener[] getKeyListeners() {5676return getListeners(KeyListener.class);5677}56785679/**5680* Adds the specified mouse listener to receive mouse events from5681* this component.5682* If listener <code>l</code> is <code>null</code>,5683* no exception is thrown and no action is performed.5684* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5685* >AWT Threading Issues</a> for details on AWT's threading model.5686*5687* @param l the mouse listener5688* @see java.awt.event.MouseEvent5689* @see java.awt.event.MouseListener5690* @see #removeMouseListener5691* @see #getMouseListeners5692* @since JDK1.15693*/5694public synchronized void addMouseListener(MouseListener l) {5695if (l == null) {5696return;5697}5698mouseListener = AWTEventMulticaster.add(mouseListener,l);5699newEventsOnly = true;57005701// if this is a lightweight component, enable mouse events5702// in the native container.5703if (peer instanceof LightweightPeer) {5704parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);5705}5706}57075708/**5709* Removes the specified mouse listener so that it no longer5710* receives mouse events from this component. This method performs5711* no function, nor does it throw an exception, if the listener5712* specified by the argument was not previously added to this component.5713* If listener <code>l</code> is <code>null</code>,5714* no exception is thrown and no action is performed.5715* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5716* >AWT Threading Issues</a> for details on AWT's threading model.5717*5718* @param l the mouse listener5719* @see java.awt.event.MouseEvent5720* @see java.awt.event.MouseListener5721* @see #addMouseListener5722* @see #getMouseListeners5723* @since JDK1.15724*/5725public synchronized void removeMouseListener(MouseListener l) {5726if (l == null) {5727return;5728}5729mouseListener = AWTEventMulticaster.remove(mouseListener, l);5730}57315732/**5733* Returns an array of all the mouse listeners5734* registered on this component.5735*5736* @return all of this component's <code>MouseListener</code>s5737* or an empty array if no mouse5738* listeners are currently registered5739*5740* @see #addMouseListener5741* @see #removeMouseListener5742* @since 1.45743*/5744public synchronized MouseListener[] getMouseListeners() {5745return getListeners(MouseListener.class);5746}57475748/**5749* Adds the specified mouse motion listener to receive mouse motion5750* events from this component.5751* If listener <code>l</code> is <code>null</code>,5752* no exception is thrown and no action is performed.5753* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5754* >AWT Threading Issues</a> for details on AWT's threading model.5755*5756* @param l the mouse motion listener5757* @see java.awt.event.MouseEvent5758* @see java.awt.event.MouseMotionListener5759* @see #removeMouseMotionListener5760* @see #getMouseMotionListeners5761* @since JDK1.15762*/5763public synchronized void addMouseMotionListener(MouseMotionListener l) {5764if (l == null) {5765return;5766}5767mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);5768newEventsOnly = true;57695770// if this is a lightweight component, enable mouse events5771// in the native container.5772if (peer instanceof LightweightPeer) {5773parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);5774}5775}57765777/**5778* Removes the specified mouse motion listener so that it no longer5779* receives mouse motion events from this component. This method performs5780* no function, nor does it throw an exception, if the listener5781* specified by the argument was not previously added to this component.5782* If listener <code>l</code> is <code>null</code>,5783* no exception is thrown and no action is performed.5784* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5785* >AWT Threading Issues</a> for details on AWT's threading model.5786*5787* @param l the mouse motion listener5788* @see java.awt.event.MouseEvent5789* @see java.awt.event.MouseMotionListener5790* @see #addMouseMotionListener5791* @see #getMouseMotionListeners5792* @since JDK1.15793*/5794public synchronized void removeMouseMotionListener(MouseMotionListener l) {5795if (l == null) {5796return;5797}5798mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);5799}58005801/**5802* Returns an array of all the mouse motion listeners5803* registered on this component.5804*5805* @return all of this component's <code>MouseMotionListener</code>s5806* or an empty array if no mouse motion5807* listeners are currently registered5808*5809* @see #addMouseMotionListener5810* @see #removeMouseMotionListener5811* @since 1.45812*/5813public synchronized MouseMotionListener[] getMouseMotionListeners() {5814return getListeners(MouseMotionListener.class);5815}58165817/**5818* Adds the specified mouse wheel listener to receive mouse wheel events5819* from this component. Containers also receive mouse wheel events from5820* sub-components.5821* <p>5822* For information on how mouse wheel events are dispatched, see5823* the class description for {@link MouseWheelEvent}.5824* <p>5825* If l is <code>null</code>, no exception is thrown and no5826* action is performed.5827* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5828* >AWT Threading Issues</a> for details on AWT's threading model.5829*5830* @param l the mouse wheel listener5831* @see java.awt.event.MouseWheelEvent5832* @see java.awt.event.MouseWheelListener5833* @see #removeMouseWheelListener5834* @see #getMouseWheelListeners5835* @since 1.45836*/5837public synchronized void addMouseWheelListener(MouseWheelListener l) {5838if (l == null) {5839return;5840}5841mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);5842newEventsOnly = true;58435844// if this is a lightweight component, enable mouse events5845// in the native container.5846if (peer instanceof LightweightPeer) {5847parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK);5848}5849}58505851/**5852* Removes the specified mouse wheel listener so that it no longer5853* receives mouse wheel events from this component. This method performs5854* no function, nor does it throw an exception, if the listener5855* specified by the argument was not previously added to this component.5856* If l is null, no exception is thrown and no action is performed.5857* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5858* >AWT Threading Issues</a> for details on AWT's threading model.5859*5860* @param l the mouse wheel listener.5861* @see java.awt.event.MouseWheelEvent5862* @see java.awt.event.MouseWheelListener5863* @see #addMouseWheelListener5864* @see #getMouseWheelListeners5865* @since 1.45866*/5867public synchronized void removeMouseWheelListener(MouseWheelListener l) {5868if (l == null) {5869return;5870}5871mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);5872}58735874/**5875* Returns an array of all the mouse wheel listeners5876* registered on this component.5877*5878* @return all of this component's <code>MouseWheelListener</code>s5879* or an empty array if no mouse wheel5880* listeners are currently registered5881*5882* @see #addMouseWheelListener5883* @see #removeMouseWheelListener5884* @since 1.45885*/5886public synchronized MouseWheelListener[] getMouseWheelListeners() {5887return getListeners(MouseWheelListener.class);5888}58895890/**5891* Adds the specified input method listener to receive5892* input method events from this component. A component will5893* only receive input method events from input methods5894* if it also overrides <code>getInputMethodRequests</code> to return an5895* <code>InputMethodRequests</code> instance.5896* If listener <code>l</code> is <code>null</code>,5897* no exception is thrown and no action is performed.5898* <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"5899* >AWT Threading Issues</a> for details on AWT's threading model.5900*5901* @param l the input method listener5902* @see java.awt.event.InputMethodEvent5903* @see java.awt.event.InputMethodListener5904* @see #removeInputMethodListener5905* @see #getInputMethodListeners5906* @see #getInputMethodRequests5907* @since 1.25908*/5909public synchronized void addInputMethodListener(InputMethodListener l) {5910if (l == null) {5911return;5912}5913inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);5914newEventsOnly = true;5915}59165917/**5918* Removes the specified input method listener so that it no longer5919* receives input method events from this component. This method performs5920* no function, nor does it throw an exception, if the listener5921* specified by the argument was not previously added to this component.5922* If listener <code>l</code> is <code>null</code>,5923* no exception is thrown and no action is performed.5924* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"5925* >AWT Threading Issues</a> for details on AWT's threading model.5926*5927* @param l the input method listener5928* @see java.awt.event.InputMethodEvent5929* @see java.awt.event.InputMethodListener5930* @see #addInputMethodListener5931* @see #getInputMethodListeners5932* @since 1.25933*/5934public synchronized void removeInputMethodListener(InputMethodListener l) {5935if (l == null) {5936return;5937}5938inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);5939}59405941/**5942* Returns an array of all the input method listeners5943* registered on this component.5944*5945* @return all of this component's <code>InputMethodListener</code>s5946* or an empty array if no input method5947* listeners are currently registered5948*5949* @see #addInputMethodListener5950* @see #removeInputMethodListener5951* @since 1.45952*/5953public synchronized InputMethodListener[] getInputMethodListeners() {5954return getListeners(InputMethodListener.class);5955}59565957/**5958* Returns an array of all the objects currently registered5959* as <code><em>Foo</em>Listener</code>s5960* upon this <code>Component</code>.5961* <code><em>Foo</em>Listener</code>s are registered using the5962* <code>add<em>Foo</em>Listener</code> method.5963*5964* <p>5965* You can specify the <code>listenerType</code> argument5966* with a class literal, such as5967* <code><em>Foo</em>Listener.class</code>.5968* For example, you can query a5969* <code>Component</code> <code>c</code>5970* for its mouse listeners with the following code:5971*5972* <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>5973*5974* If no such listeners exist, this method returns an empty array.5975*5976* @param listenerType the type of listeners requested; this parameter5977* should specify an interface that descends from5978* <code>java.util.EventListener</code>5979* @return an array of all objects registered as5980* <code><em>Foo</em>Listener</code>s on this component,5981* or an empty array if no such listeners have been added5982* @exception ClassCastException if <code>listenerType</code>5983* doesn't specify a class or interface that implements5984* <code>java.util.EventListener</code>5985* @throws NullPointerException if {@code listenerType} is {@code null}5986* @see #getComponentListeners5987* @see #getFocusListeners5988* @see #getHierarchyListeners5989* @see #getHierarchyBoundsListeners5990* @see #getKeyListeners5991* @see #getMouseListeners5992* @see #getMouseMotionListeners5993* @see #getMouseWheelListeners5994* @see #getInputMethodListeners5995* @see #getPropertyChangeListeners5996*5997* @since 1.35998*/5999@SuppressWarnings("unchecked")6000public <T extends EventListener> T[] getListeners(Class<T> listenerType) {6001EventListener l = null;6002if (listenerType == ComponentListener.class) {6003l = componentListener;6004} else if (listenerType == FocusListener.class) {6005l = focusListener;6006} else if (listenerType == HierarchyListener.class) {6007l = hierarchyListener;6008} else if (listenerType == HierarchyBoundsListener.class) {6009l = hierarchyBoundsListener;6010} else if (listenerType == KeyListener.class) {6011l = keyListener;6012} else if (listenerType == MouseListener.class) {6013l = mouseListener;6014} else if (listenerType == MouseMotionListener.class) {6015l = mouseMotionListener;6016} else if (listenerType == MouseWheelListener.class) {6017l = mouseWheelListener;6018} else if (listenerType == InputMethodListener.class) {6019l = inputMethodListener;6020} else if (listenerType == PropertyChangeListener.class) {6021return (T[])getPropertyChangeListeners();6022}6023return AWTEventMulticaster.getListeners(l, listenerType);6024}60256026/**6027* Gets the input method request handler which supports6028* requests from input methods for this component. A component6029* that supports on-the-spot text input must override this6030* method to return an <code>InputMethodRequests</code> instance.6031* At the same time, it also has to handle input method events.6032*6033* @return the input method request handler for this component,6034* <code>null</code> by default6035* @see #addInputMethodListener6036* @since 1.26037*/6038public InputMethodRequests getInputMethodRequests() {6039return null;6040}60416042/**6043* Gets the input context used by this component for handling6044* the communication with input methods when text is entered6045* in this component. By default, the input context used for6046* the parent component is returned. Components may6047* override this to return a private input context.6048*6049* @return the input context used by this component;6050* <code>null</code> if no context can be determined6051* @since 1.26052*/6053public InputContext getInputContext() {6054Container parent = this.parent;6055if (parent == null) {6056return null;6057} else {6058return parent.getInputContext();6059}6060}60616062/**6063* Enables the events defined by the specified event mask parameter6064* to be delivered to this component.6065* <p>6066* Event types are automatically enabled when a listener for6067* that event type is added to the component.6068* <p>6069* This method only needs to be invoked by subclasses of6070* <code>Component</code> which desire to have the specified event6071* types delivered to <code>processEvent</code> regardless of whether6072* or not a listener is registered.6073* @param eventsToEnable the event mask defining the event types6074* @see #processEvent6075* @see #disableEvents6076* @see AWTEvent6077* @since JDK1.16078*/6079protected final void enableEvents(long eventsToEnable) {6080long notifyAncestors = 0;6081synchronized (this) {6082if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&6083hierarchyListener == null &&6084(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {6085notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;6086}6087if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&6088hierarchyBoundsListener == null &&6089(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {6090notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;6091}6092eventMask |= eventsToEnable;6093newEventsOnly = true;6094}60956096// if this is a lightweight component, enable mouse events6097// in the native container.6098if (peer instanceof LightweightPeer) {6099parent.proxyEnableEvents(eventMask);6100}6101if (notifyAncestors != 0) {6102synchronized (getTreeLock()) {6103adjustListeningChildrenOnParent(notifyAncestors, 1);6104}6105}6106}61076108/**6109* Disables the events defined by the specified event mask parameter6110* from being delivered to this component.6111* @param eventsToDisable the event mask defining the event types6112* @see #enableEvents6113* @since JDK1.16114*/6115protected final void disableEvents(long eventsToDisable) {6116long notifyAncestors = 0;6117synchronized (this) {6118if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&6119hierarchyListener == null &&6120(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) {6121notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;6122}6123if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 &&6124hierarchyBoundsListener == null &&6125(eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) {6126notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;6127}6128eventMask &= ~eventsToDisable;6129}6130if (notifyAncestors != 0) {6131synchronized (getTreeLock()) {6132adjustListeningChildrenOnParent(notifyAncestors, -1);6133}6134}6135}61366137transient sun.awt.EventQueueItem[] eventCache;61386139/**6140* @see #isCoalescingEnabled6141* @see #checkCoalescing6142*/6143transient private boolean coalescingEnabled = checkCoalescing();61446145/**6146* Weak map of known coalesceEvent overriders.6147* Value indicates whether overriden.6148* Bootstrap classes are not included.6149*/6150private static final Map<Class<?>, Boolean> coalesceMap =6151new java.util.WeakHashMap<Class<?>, Boolean>();61526153/**6154* Indicates whether this class overrides coalesceEvents.6155* It is assumed that all classes that are loaded from the bootstrap6156* do not.6157* The boostrap class loader is assumed to be represented by null.6158* We do not check that the method really overrides6159* (it might be static, private or package private).6160*/6161private boolean checkCoalescing() {6162if (getClass().getClassLoader()==null) {6163return false;6164}6165final Class<? extends Component> clazz = getClass();6166synchronized (coalesceMap) {6167// Check cache.6168Boolean value = coalesceMap.get(clazz);6169if (value != null) {6170return value;6171}61726173// Need to check non-bootstraps.6174Boolean enabled = java.security.AccessController.doPrivileged(6175new java.security.PrivilegedAction<Boolean>() {6176public Boolean run() {6177return isCoalesceEventsOverriden(clazz);6178}6179}6180);6181coalesceMap.put(clazz, enabled);6182return enabled;6183}6184}61856186/**6187* Parameter types of coalesceEvents(AWTEvent,AWTEVent).6188*/6189private static final Class[] coalesceEventsParams = {6190AWTEvent.class, AWTEvent.class6191};61926193/**6194* Indicates whether a class or its superclasses override coalesceEvents.6195* Must be called with lock on coalesceMap and privileged.6196* @see checkCoalescing6197*/6198private static boolean isCoalesceEventsOverriden(Class<?> clazz) {6199assert Thread.holdsLock(coalesceMap);62006201// First check superclass - we may not need to bother ourselves.6202Class<?> superclass = clazz.getSuperclass();6203if (superclass == null) {6204// Only occurs on implementations that6205// do not use null to represent the bootsrap class loader.6206return false;6207}6208if (superclass.getClassLoader() != null) {6209Boolean value = coalesceMap.get(superclass);6210if (value == null) {6211// Not done already - recurse.6212if (isCoalesceEventsOverriden(superclass)) {6213coalesceMap.put(superclass, true);6214return true;6215}6216} else if (value) {6217return true;6218}6219}62206221try {6222// Throws if not overriden.6223clazz.getDeclaredMethod(6224"coalesceEvents", coalesceEventsParams6225);6226return true;6227} catch (NoSuchMethodException e) {6228// Not present in this class.6229return false;6230}6231}62326233/**6234* Indicates whether coalesceEvents may do something.6235*/6236final boolean isCoalescingEnabled() {6237return coalescingEnabled;6238}623962406241/**6242* Potentially coalesce an event being posted with an existing6243* event. This method is called by <code>EventQueue.postEvent</code>6244* if an event with the same ID as the event to be posted is found in6245* the queue (both events must have this component as their source).6246* This method either returns a coalesced event which replaces6247* the existing event (and the new event is then discarded), or6248* <code>null</code> to indicate that no combining should be done6249* (add the second event to the end of the queue). Either event6250* parameter may be modified and returned, as the other one is discarded6251* unless <code>null</code> is returned.6252* <p>6253* This implementation of <code>coalesceEvents</code> coalesces6254* two event types: mouse move (and drag) events,6255* and paint (and update) events.6256* For mouse move events the last event is always returned, causing6257* intermediate moves to be discarded. For paint events, the new6258* event is coalesced into a complex <code>RepaintArea</code> in the peer.6259* The new <code>AWTEvent</code> is always returned.6260*6261* @param existingEvent the event already on the <code>EventQueue</code>6262* @param newEvent the event being posted to the6263* <code>EventQueue</code>6264* @return a coalesced event, or <code>null</code> indicating that no6265* coalescing was done6266*/6267protected AWTEvent coalesceEvents(AWTEvent existingEvent,6268AWTEvent newEvent) {6269return null;6270}62716272/**6273* Processes events occurring on this component. By default this6274* method calls the appropriate6275* <code>process<event type>Event</code>6276* method for the given class of event.6277* <p>Note that if the event parameter is <code>null</code>6278* the behavior is unspecified and may result in an6279* exception.6280*6281* @param e the event6282* @see #processComponentEvent6283* @see #processFocusEvent6284* @see #processKeyEvent6285* @see #processMouseEvent6286* @see #processMouseMotionEvent6287* @see #processInputMethodEvent6288* @see #processHierarchyEvent6289* @see #processMouseWheelEvent6290* @since JDK1.16291*/6292protected void processEvent(AWTEvent e) {6293if (e instanceof FocusEvent) {6294processFocusEvent((FocusEvent)e);62956296} else if (e instanceof MouseEvent) {6297switch(e.getID()) {6298case MouseEvent.MOUSE_PRESSED:6299case MouseEvent.MOUSE_RELEASED:6300case MouseEvent.MOUSE_CLICKED:6301case MouseEvent.MOUSE_ENTERED:6302case MouseEvent.MOUSE_EXITED:6303processMouseEvent((MouseEvent)e);6304break;6305case MouseEvent.MOUSE_MOVED:6306case MouseEvent.MOUSE_DRAGGED:6307processMouseMotionEvent((MouseEvent)e);6308break;6309case MouseEvent.MOUSE_WHEEL:6310processMouseWheelEvent((MouseWheelEvent)e);6311break;6312}63136314} else if (e instanceof KeyEvent) {6315processKeyEvent((KeyEvent)e);63166317} else if (e instanceof ComponentEvent) {6318processComponentEvent((ComponentEvent)e);6319} else if (e instanceof InputMethodEvent) {6320processInputMethodEvent((InputMethodEvent)e);6321} else if (e instanceof HierarchyEvent) {6322switch (e.getID()) {6323case HierarchyEvent.HIERARCHY_CHANGED:6324processHierarchyEvent((HierarchyEvent)e);6325break;6326case HierarchyEvent.ANCESTOR_MOVED:6327case HierarchyEvent.ANCESTOR_RESIZED:6328processHierarchyBoundsEvent((HierarchyEvent)e);6329break;6330}6331}6332}63336334/**6335* Processes component events occurring on this component by6336* dispatching them to any registered6337* <code>ComponentListener</code> objects.6338* <p>6339* This method is not called unless component events are6340* enabled for this component. Component events are enabled6341* when one of the following occurs:6342* <ul>6343* <li>A <code>ComponentListener</code> object is registered6344* via <code>addComponentListener</code>.6345* <li>Component events are enabled via <code>enableEvents</code>.6346* </ul>6347* <p>Note that if the event parameter is <code>null</code>6348* the behavior is unspecified and may result in an6349* exception.6350*6351* @param e the component event6352* @see java.awt.event.ComponentEvent6353* @see java.awt.event.ComponentListener6354* @see #addComponentListener6355* @see #enableEvents6356* @since JDK1.16357*/6358protected void processComponentEvent(ComponentEvent e) {6359ComponentListener listener = componentListener;6360if (listener != null) {6361int id = e.getID();6362switch(id) {6363case ComponentEvent.COMPONENT_RESIZED:6364listener.componentResized(e);6365break;6366case ComponentEvent.COMPONENT_MOVED:6367listener.componentMoved(e);6368break;6369case ComponentEvent.COMPONENT_SHOWN:6370listener.componentShown(e);6371break;6372case ComponentEvent.COMPONENT_HIDDEN:6373listener.componentHidden(e);6374break;6375}6376}6377}63786379/**6380* Processes focus events occurring on this component by6381* dispatching them to any registered6382* <code>FocusListener</code> objects.6383* <p>6384* This method is not called unless focus events are6385* enabled for this component. Focus events are enabled6386* when one of the following occurs:6387* <ul>6388* <li>A <code>FocusListener</code> object is registered6389* via <code>addFocusListener</code>.6390* <li>Focus events are enabled via <code>enableEvents</code>.6391* </ul>6392* <p>6393* If focus events are enabled for a <code>Component</code>,6394* the current <code>KeyboardFocusManager</code> determines6395* whether or not a focus event should be dispatched to6396* registered <code>FocusListener</code> objects. If the6397* events are to be dispatched, the <code>KeyboardFocusManager</code>6398* calls the <code>Component</code>'s <code>dispatchEvent</code>6399* method, which results in a call to the <code>Component</code>'s6400* <code>processFocusEvent</code> method.6401* <p>6402* If focus events are enabled for a <code>Component</code>, calling6403* the <code>Component</code>'s <code>dispatchEvent</code> method6404* with a <code>FocusEvent</code> as the argument will result in a6405* call to the <code>Component</code>'s <code>processFocusEvent</code>6406* method regardless of the current <code>KeyboardFocusManager</code>.6407*6408* <p>Note that if the event parameter is <code>null</code>6409* the behavior is unspecified and may result in an6410* exception.6411*6412* @param e the focus event6413* @see java.awt.event.FocusEvent6414* @see java.awt.event.FocusListener6415* @see java.awt.KeyboardFocusManager6416* @see #addFocusListener6417* @see #enableEvents6418* @see #dispatchEvent6419* @since JDK1.16420*/6421protected void processFocusEvent(FocusEvent e) {6422FocusListener listener = focusListener;6423if (listener != null) {6424int id = e.getID();6425switch(id) {6426case FocusEvent.FOCUS_GAINED:6427listener.focusGained(e);6428break;6429case FocusEvent.FOCUS_LOST:6430listener.focusLost(e);6431break;6432}6433}6434}64356436/**6437* Processes key events occurring on this component by6438* dispatching them to any registered6439* <code>KeyListener</code> objects.6440* <p>6441* This method is not called unless key events are6442* enabled for this component. Key events are enabled6443* when one of the following occurs:6444* <ul>6445* <li>A <code>KeyListener</code> object is registered6446* via <code>addKeyListener</code>.6447* <li>Key events are enabled via <code>enableEvents</code>.6448* </ul>6449*6450* <p>6451* If key events are enabled for a <code>Component</code>,6452* the current <code>KeyboardFocusManager</code> determines6453* whether or not a key event should be dispatched to6454* registered <code>KeyListener</code> objects. The6455* <code>DefaultKeyboardFocusManager</code> will not dispatch6456* key events to a <code>Component</code> that is not the focus6457* owner or is not showing.6458* <p>6459* As of J2SE 1.4, <code>KeyEvent</code>s are redirected to6460* the focus owner. Please see the6461* <a href="doc-files/FocusSpec.html">Focus Specification</a>6462* for further information.6463* <p>6464* Calling a <code>Component</code>'s <code>dispatchEvent</code>6465* method with a <code>KeyEvent</code> as the argument will6466* result in a call to the <code>Component</code>'s6467* <code>processKeyEvent</code> method regardless of the6468* current <code>KeyboardFocusManager</code> as long as the6469* component is showing, focused, and enabled, and key events6470* are enabled on it.6471* <p>If the event parameter is <code>null</code>6472* the behavior is unspecified and may result in an6473* exception.6474*6475* @param e the key event6476* @see java.awt.event.KeyEvent6477* @see java.awt.event.KeyListener6478* @see java.awt.KeyboardFocusManager6479* @see java.awt.DefaultKeyboardFocusManager6480* @see #processEvent6481* @see #dispatchEvent6482* @see #addKeyListener6483* @see #enableEvents6484* @see #isShowing6485* @since JDK1.16486*/6487protected void processKeyEvent(KeyEvent e) {6488KeyListener listener = keyListener;6489if (listener != null) {6490int id = e.getID();6491switch(id) {6492case KeyEvent.KEY_TYPED:6493listener.keyTyped(e);6494break;6495case KeyEvent.KEY_PRESSED:6496listener.keyPressed(e);6497break;6498case KeyEvent.KEY_RELEASED:6499listener.keyReleased(e);6500break;6501}6502}6503}65046505/**6506* Processes mouse events occurring on this component by6507* dispatching them to any registered6508* <code>MouseListener</code> objects.6509* <p>6510* This method is not called unless mouse events are6511* enabled for this component. Mouse events are enabled6512* when one of the following occurs:6513* <ul>6514* <li>A <code>MouseListener</code> object is registered6515* via <code>addMouseListener</code>.6516* <li>Mouse events are enabled via <code>enableEvents</code>.6517* </ul>6518* <p>Note that if the event parameter is <code>null</code>6519* the behavior is unspecified and may result in an6520* exception.6521*6522* @param e the mouse event6523* @see java.awt.event.MouseEvent6524* @see java.awt.event.MouseListener6525* @see #addMouseListener6526* @see #enableEvents6527* @since JDK1.16528*/6529protected void processMouseEvent(MouseEvent e) {6530MouseListener listener = mouseListener;6531if (listener != null) {6532int id = e.getID();6533switch(id) {6534case MouseEvent.MOUSE_PRESSED:6535listener.mousePressed(e);6536break;6537case MouseEvent.MOUSE_RELEASED:6538listener.mouseReleased(e);6539break;6540case MouseEvent.MOUSE_CLICKED:6541listener.mouseClicked(e);6542break;6543case MouseEvent.MOUSE_EXITED:6544listener.mouseExited(e);6545break;6546case MouseEvent.MOUSE_ENTERED:6547listener.mouseEntered(e);6548break;6549}6550}6551}65526553/**6554* Processes mouse motion events occurring on this component by6555* dispatching them to any registered6556* <code>MouseMotionListener</code> objects.6557* <p>6558* This method is not called unless mouse motion events are6559* enabled for this component. Mouse motion events are enabled6560* when one of the following occurs:6561* <ul>6562* <li>A <code>MouseMotionListener</code> object is registered6563* via <code>addMouseMotionListener</code>.6564* <li>Mouse motion events are enabled via <code>enableEvents</code>.6565* </ul>6566* <p>Note that if the event parameter is <code>null</code>6567* the behavior is unspecified and may result in an6568* exception.6569*6570* @param e the mouse motion event6571* @see java.awt.event.MouseEvent6572* @see java.awt.event.MouseMotionListener6573* @see #addMouseMotionListener6574* @see #enableEvents6575* @since JDK1.16576*/6577protected void processMouseMotionEvent(MouseEvent e) {6578MouseMotionListener listener = mouseMotionListener;6579if (listener != null) {6580int id = e.getID();6581switch(id) {6582case MouseEvent.MOUSE_MOVED:6583listener.mouseMoved(e);6584break;6585case MouseEvent.MOUSE_DRAGGED:6586listener.mouseDragged(e);6587break;6588}6589}6590}65916592/**6593* Processes mouse wheel events occurring on this component by6594* dispatching them to any registered6595* <code>MouseWheelListener</code> objects.6596* <p>6597* This method is not called unless mouse wheel events are6598* enabled for this component. Mouse wheel events are enabled6599* when one of the following occurs:6600* <ul>6601* <li>A <code>MouseWheelListener</code> object is registered6602* via <code>addMouseWheelListener</code>.6603* <li>Mouse wheel events are enabled via <code>enableEvents</code>.6604* </ul>6605* <p>6606* For information on how mouse wheel events are dispatched, see6607* the class description for {@link MouseWheelEvent}.6608* <p>6609* Note that if the event parameter is <code>null</code>6610* the behavior is unspecified and may result in an6611* exception.6612*6613* @param e the mouse wheel event6614* @see java.awt.event.MouseWheelEvent6615* @see java.awt.event.MouseWheelListener6616* @see #addMouseWheelListener6617* @see #enableEvents6618* @since 1.46619*/6620protected void processMouseWheelEvent(MouseWheelEvent e) {6621MouseWheelListener listener = mouseWheelListener;6622if (listener != null) {6623int id = e.getID();6624switch(id) {6625case MouseEvent.MOUSE_WHEEL:6626listener.mouseWheelMoved(e);6627break;6628}6629}6630}66316632boolean postsOldMouseEvents() {6633return false;6634}66356636/**6637* Processes input method events occurring on this component by6638* dispatching them to any registered6639* <code>InputMethodListener</code> objects.6640* <p>6641* This method is not called unless input method events6642* are enabled for this component. Input method events are enabled6643* when one of the following occurs:6644* <ul>6645* <li>An <code>InputMethodListener</code> object is registered6646* via <code>addInputMethodListener</code>.6647* <li>Input method events are enabled via <code>enableEvents</code>.6648* </ul>6649* <p>Note that if the event parameter is <code>null</code>6650* the behavior is unspecified and may result in an6651* exception.6652*6653* @param e the input method event6654* @see java.awt.event.InputMethodEvent6655* @see java.awt.event.InputMethodListener6656* @see #addInputMethodListener6657* @see #enableEvents6658* @since 1.26659*/6660protected void processInputMethodEvent(InputMethodEvent e) {6661InputMethodListener listener = inputMethodListener;6662if (listener != null) {6663int id = e.getID();6664switch (id) {6665case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:6666listener.inputMethodTextChanged(e);6667break;6668case InputMethodEvent.CARET_POSITION_CHANGED:6669listener.caretPositionChanged(e);6670break;6671}6672}6673}66746675/**6676* Processes hierarchy events occurring on this component by6677* dispatching them to any registered6678* <code>HierarchyListener</code> objects.6679* <p>6680* This method is not called unless hierarchy events6681* are enabled for this component. Hierarchy events are enabled6682* when one of the following occurs:6683* <ul>6684* <li>An <code>HierarchyListener</code> object is registered6685* via <code>addHierarchyListener</code>.6686* <li>Hierarchy events are enabled via <code>enableEvents</code>.6687* </ul>6688* <p>Note that if the event parameter is <code>null</code>6689* the behavior is unspecified and may result in an6690* exception.6691*6692* @param e the hierarchy event6693* @see java.awt.event.HierarchyEvent6694* @see java.awt.event.HierarchyListener6695* @see #addHierarchyListener6696* @see #enableEvents6697* @since 1.36698*/6699protected void processHierarchyEvent(HierarchyEvent e) {6700HierarchyListener listener = hierarchyListener;6701if (listener != null) {6702int id = e.getID();6703switch (id) {6704case HierarchyEvent.HIERARCHY_CHANGED:6705listener.hierarchyChanged(e);6706break;6707}6708}6709}67106711/**6712* Processes hierarchy bounds events occurring on this component by6713* dispatching them to any registered6714* <code>HierarchyBoundsListener</code> objects.6715* <p>6716* This method is not called unless hierarchy bounds events6717* are enabled for this component. Hierarchy bounds events are enabled6718* when one of the following occurs:6719* <ul>6720* <li>An <code>HierarchyBoundsListener</code> object is registered6721* via <code>addHierarchyBoundsListener</code>.6722* <li>Hierarchy bounds events are enabled via <code>enableEvents</code>.6723* </ul>6724* <p>Note that if the event parameter is <code>null</code>6725* the behavior is unspecified and may result in an6726* exception.6727*6728* @param e the hierarchy event6729* @see java.awt.event.HierarchyEvent6730* @see java.awt.event.HierarchyBoundsListener6731* @see #addHierarchyBoundsListener6732* @see #enableEvents6733* @since 1.36734*/6735protected void processHierarchyBoundsEvent(HierarchyEvent e) {6736HierarchyBoundsListener listener = hierarchyBoundsListener;6737if (listener != null) {6738int id = e.getID();6739switch (id) {6740case HierarchyEvent.ANCESTOR_MOVED:6741listener.ancestorMoved(e);6742break;6743case HierarchyEvent.ANCESTOR_RESIZED:6744listener.ancestorResized(e);6745break;6746}6747}6748}67496750/**6751* @deprecated As of JDK version 1.16752* replaced by processEvent(AWTEvent).6753*/6754@Deprecated6755public boolean handleEvent(Event evt) {6756switch (evt.id) {6757case Event.MOUSE_ENTER:6758return mouseEnter(evt, evt.x, evt.y);67596760case Event.MOUSE_EXIT:6761return mouseExit(evt, evt.x, evt.y);67626763case Event.MOUSE_MOVE:6764return mouseMove(evt, evt.x, evt.y);67656766case Event.MOUSE_DOWN:6767return mouseDown(evt, evt.x, evt.y);67686769case Event.MOUSE_DRAG:6770return mouseDrag(evt, evt.x, evt.y);67716772case Event.MOUSE_UP:6773return mouseUp(evt, evt.x, evt.y);67746775case Event.KEY_PRESS:6776case Event.KEY_ACTION:6777return keyDown(evt, evt.key);67786779case Event.KEY_RELEASE:6780case Event.KEY_ACTION_RELEASE:6781return keyUp(evt, evt.key);67826783case Event.ACTION_EVENT:6784return action(evt, evt.arg);6785case Event.GOT_FOCUS:6786return gotFocus(evt, evt.arg);6787case Event.LOST_FOCUS:6788return lostFocus(evt, evt.arg);6789}6790return false;6791}67926793/**6794* @deprecated As of JDK version 1.1,6795* replaced by processMouseEvent(MouseEvent).6796*/6797@Deprecated6798public boolean mouseDown(Event evt, int x, int y) {6799return false;6800}68016802/**6803* @deprecated As of JDK version 1.1,6804* replaced by processMouseMotionEvent(MouseEvent).6805*/6806@Deprecated6807public boolean mouseDrag(Event evt, int x, int y) {6808return false;6809}68106811/**6812* @deprecated As of JDK version 1.1,6813* replaced by processMouseEvent(MouseEvent).6814*/6815@Deprecated6816public boolean mouseUp(Event evt, int x, int y) {6817return false;6818}68196820/**6821* @deprecated As of JDK version 1.1,6822* replaced by processMouseMotionEvent(MouseEvent).6823*/6824@Deprecated6825public boolean mouseMove(Event evt, int x, int y) {6826return false;6827}68286829/**6830* @deprecated As of JDK version 1.1,6831* replaced by processMouseEvent(MouseEvent).6832*/6833@Deprecated6834public boolean mouseEnter(Event evt, int x, int y) {6835return false;6836}68376838/**6839* @deprecated As of JDK version 1.1,6840* replaced by processMouseEvent(MouseEvent).6841*/6842@Deprecated6843public boolean mouseExit(Event evt, int x, int y) {6844return false;6845}68466847/**6848* @deprecated As of JDK version 1.1,6849* replaced by processKeyEvent(KeyEvent).6850*/6851@Deprecated6852public boolean keyDown(Event evt, int key) {6853return false;6854}68556856/**6857* @deprecated As of JDK version 1.1,6858* replaced by processKeyEvent(KeyEvent).6859*/6860@Deprecated6861public boolean keyUp(Event evt, int key) {6862return false;6863}68646865/**6866* @deprecated As of JDK version 1.1,6867* should register this component as ActionListener on component6868* which fires action events.6869*/6870@Deprecated6871public boolean action(Event evt, Object what) {6872return false;6873}68746875/**6876* Makes this <code>Component</code> displayable by connecting it to a6877* native screen resource.6878* This method is called internally by the toolkit and should6879* not be called directly by programs.6880* <p>6881* This method changes layout-related information, and therefore,6882* invalidates the component hierarchy.6883*6884* @see #isDisplayable6885* @see #removeNotify6886* @see #invalidate6887* @since JDK1.06888*/6889public void addNotify() {6890synchronized (getTreeLock()) {6891ComponentPeer peer = this.peer;6892if (peer == null || peer instanceof LightweightPeer){6893if (peer == null) {6894// Update both the Component's peer variable and the local6895// variable we use for thread safety.6896this.peer = peer = getToolkit().createComponent(this);6897}68986899// This is a lightweight component which means it won't be6900// able to get window-related events by itself. If any6901// have been enabled, then the nearest native container must6902// be enabled.6903if (parent != null) {6904long mask = 0;6905if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) {6906mask |= AWTEvent.MOUSE_EVENT_MASK;6907}6908if ((mouseMotionListener != null) ||6909((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) {6910mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK;6911}6912if ((mouseWheelListener != null ) ||6913((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) {6914mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK;6915}6916if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) {6917mask |= AWTEvent.FOCUS_EVENT_MASK;6918}6919if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) {6920mask |= AWTEvent.KEY_EVENT_MASK;6921}6922if (mask != 0) {6923parent.proxyEnableEvents(mask);6924}6925}6926} else {6927// It's native. If the parent is lightweight it will need some6928// help.6929Container parent = getContainer();6930if (parent != null && parent.isLightweight()) {6931relocateComponent();6932if (!parent.isRecursivelyVisibleUpToHeavyweightContainer())6933{6934peer.setVisible(false);6935}6936}6937}6938invalidate();69396940int npopups = (popups != null? popups.size() : 0);6941for (int i = 0 ; i < npopups ; i++) {6942PopupMenu popup = popups.elementAt(i);6943popup.addNotify();6944}69456946if (dropTarget != null) dropTarget.addNotify(peer);69476948peerFont = getFont();69496950if (getContainer() != null && !isAddNotifyComplete) {6951getContainer().increaseComponentCount(this);6952}695369546955// Update stacking order6956updateZOrder();69576958if (!isAddNotifyComplete) {6959mixOnShowing();6960}69616962isAddNotifyComplete = true;69636964if (hierarchyListener != null ||6965(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||6966Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {6967HierarchyEvent e =6968new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,6969this, parent,6970HierarchyEvent.DISPLAYABILITY_CHANGED |6971((isRecursivelyVisible())6972? HierarchyEvent.SHOWING_CHANGED6973: 0));6974dispatchEvent(e);6975}6976}6977}69786979/**6980* Makes this <code>Component</code> undisplayable by destroying it native6981* screen resource.6982* <p>6983* This method is called by the toolkit internally and should6984* not be called directly by programs. Code overriding6985* this method should call <code>super.removeNotify</code> as6986* the first line of the overriding method.6987*6988* @see #isDisplayable6989* @see #addNotify6990* @since JDK1.06991*/6992public void removeNotify() {6993KeyboardFocusManager.clearMostRecentFocusOwner(this);6994if (KeyboardFocusManager.getCurrentKeyboardFocusManager().6995getPermanentFocusOwner() == this)6996{6997KeyboardFocusManager.getCurrentKeyboardFocusManager().6998setGlobalPermanentFocusOwner(null);6999}70007001synchronized (getTreeLock()) {7002if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {7003transferFocus(true);7004}70057006if (getContainer() != null && isAddNotifyComplete) {7007getContainer().decreaseComponentCount(this);7008}70097010int npopups = (popups != null? popups.size() : 0);7011for (int i = 0 ; i < npopups ; i++) {7012PopupMenu popup = popups.elementAt(i);7013popup.removeNotify();7014}7015// If there is any input context for this component, notify7016// that this component is being removed. (This has to be done7017// before hiding peer.)7018if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {7019InputContext inputContext = getInputContext();7020if (inputContext != null) {7021inputContext.removeNotify(this);7022}7023}70247025ComponentPeer p = peer;7026if (p != null) {7027boolean isLightweight = isLightweight();70287029if (bufferStrategy instanceof FlipBufferStrategy) {7030((FlipBufferStrategy)bufferStrategy).destroyBuffers();7031}70327033if (dropTarget != null) dropTarget.removeNotify(peer);70347035// Hide peer first to stop system events such as cursor moves.7036if (visible) {7037p.setVisible(false);7038}70397040peer = null; // Stop peer updates.7041peerFont = null;70427043Toolkit.getEventQueue().removeSourceEvents(this, false);7044KeyboardFocusManager.getCurrentKeyboardFocusManager().7045discardKeyEvents(this);70467047p.dispose();70487049mixOnHiding(isLightweight);70507051isAddNotifyComplete = false;7052// Nullifying compoundShape means that the component has normal shape7053// (or has no shape at all).7054this.compoundShape = null;7055}70567057if (hierarchyListener != null ||7058(eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||7059Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {7060HierarchyEvent e =7061new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,7062this, parent,7063HierarchyEvent.DISPLAYABILITY_CHANGED |7064((isRecursivelyVisible())7065? HierarchyEvent.SHOWING_CHANGED7066: 0));7067dispatchEvent(e);7068}7069}7070}70717072/**7073* @deprecated As of JDK version 1.1,7074* replaced by processFocusEvent(FocusEvent).7075*/7076@Deprecated7077public boolean gotFocus(Event evt, Object what) {7078return false;7079}70807081/**7082* @deprecated As of JDK version 1.1,7083* replaced by processFocusEvent(FocusEvent).7084*/7085@Deprecated7086public boolean lostFocus(Event evt, Object what) {7087return false;7088}70897090/**7091* Returns whether this <code>Component</code> can become the focus7092* owner.7093*7094* @return <code>true</code> if this <code>Component</code> is7095* focusable; <code>false</code> otherwise7096* @see #setFocusable7097* @since JDK1.17098* @deprecated As of 1.4, replaced by <code>isFocusable()</code>.7099*/7100@Deprecated7101public boolean isFocusTraversable() {7102if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {7103isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;7104}7105return focusable;7106}71077108/**7109* Returns whether this Component can be focused.7110*7111* @return <code>true</code> if this Component is focusable;7112* <code>false</code> otherwise.7113* @see #setFocusable7114* @since 1.47115*/7116public boolean isFocusable() {7117return isFocusTraversable();7118}71197120/**7121* Sets the focusable state of this Component to the specified value. This7122* value overrides the Component's default focusability.7123*7124* @param focusable indicates whether this Component is focusable7125* @see #isFocusable7126* @since 1.47127* @beaninfo7128* bound: true7129*/7130public void setFocusable(boolean focusable) {7131boolean oldFocusable;7132synchronized (this) {7133oldFocusable = this.focusable;7134this.focusable = focusable;7135}7136isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET;71377138firePropertyChange("focusable", oldFocusable, focusable);7139if (oldFocusable && !focusable) {7140if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {7141transferFocus(true);7142}7143KeyboardFocusManager.clearMostRecentFocusOwner(this);7144}7145}71467147final boolean isFocusTraversableOverridden() {7148return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT);7149}71507151/**7152* Sets the focus traversal keys for a given traversal operation for this7153* Component.7154* <p>7155* The default values for a Component's focus traversal keys are7156* implementation-dependent. Sun recommends that all implementations for a7157* particular native platform use the same default values. The7158* recommendations for Windows and Unix are listed below. These7159* recommendations are used in the Sun AWT implementations.7160*7161* <table border=1 summary="Recommended default values for a Component's focus traversal keys">7162* <tr>7163* <th>Identifier</th>7164* <th>Meaning</th>7165* <th>Default</th>7166* </tr>7167* <tr>7168* <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td>7169* <td>Normal forward keyboard traversal</td>7170* <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td>7171* </tr>7172* <tr>7173* <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td>7174* <td>Normal reverse keyboard traversal</td>7175* <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td>7176* </tr>7177* <tr>7178* <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td>7179* <td>Go up one focus traversal cycle</td>7180* <td>none</td>7181* </tr>7182* </table>7183*7184* To disable a traversal key, use an empty Set; Collections.EMPTY_SET is7185* recommended.7186* <p>7187* Using the AWTKeyStroke API, client code can specify on which of two7188* specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal7189* operation will occur. Regardless of which KeyEvent is specified,7190* however, all KeyEvents related to the focus traversal key, including the7191* associated KEY_TYPED event, will be consumed, and will not be dispatched7192* to any Component. It is a runtime error to specify a KEY_TYPED event as7193* mapping to a focus traversal operation, or to map the same event to7194* multiple default focus traversal operations.7195* <p>7196* If a value of null is specified for the Set, this Component inherits the7197* Set from its parent. If all ancestors of this Component have null7198* specified for the Set, then the current KeyboardFocusManager's default7199* Set is used.7200* <p>7201* This method may throw a {@code ClassCastException} if any {@code Object}7202* in {@code keystrokes} is not an {@code AWTKeyStroke}.7203*7204* @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7205* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7206* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS7207* @param keystrokes the Set of AWTKeyStroke for the specified operation7208* @see #getFocusTraversalKeys7209* @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS7210* @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS7211* @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS7212* @throws IllegalArgumentException if id is not one of7213* KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7214* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7215* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes7216* contains null, or if any keystroke represents a KEY_TYPED event,7217* or if any keystroke already maps to another focus traversal7218* operation for this Component7219* @since 1.47220* @beaninfo7221* bound: true7222*/7223public void setFocusTraversalKeys(int id,7224Set<? extends AWTKeyStroke> keystrokes)7225{7226if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {7227throw new IllegalArgumentException("invalid focus traversal key identifier");7228}72297230setFocusTraversalKeys_NoIDCheck(id, keystrokes);7231}72327233/**7234* Returns the Set of focus traversal keys for a given traversal operation7235* for this Component. (See7236* <code>setFocusTraversalKeys</code> for a full description of each key.)7237* <p>7238* If a Set of traversal keys has not been explicitly defined for this7239* Component, then this Component's parent's Set is returned. If no Set7240* has been explicitly defined for any of this Component's ancestors, then7241* the current KeyboardFocusManager's default Set is returned.7242*7243* @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7244* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7245* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS7246* @return the Set of AWTKeyStrokes for the specified operation. The Set7247* will be unmodifiable, and may be empty. null will never be7248* returned.7249* @see #setFocusTraversalKeys7250* @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS7251* @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS7252* @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS7253* @throws IllegalArgumentException if id is not one of7254* KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7255* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7256* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS7257* @since 1.47258*/7259public Set<AWTKeyStroke> getFocusTraversalKeys(int id) {7260if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {7261throw new IllegalArgumentException("invalid focus traversal key identifier");7262}72637264return getFocusTraversalKeys_NoIDCheck(id);7265}72667267// We define these methods so that Container does not need to repeat this7268// code. Container cannot call super.<method> because Container allows7269// DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method7270// would erroneously generate an IllegalArgumentException for7271// DOWN_CYCLE_TRAVERSAL_KEY.7272final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) {7273Set<AWTKeyStroke> oldKeys;72747275synchronized (this) {7276if (focusTraversalKeys == null) {7277initializeFocusTraversalKeys();7278}72797280if (keystrokes != null) {7281for (AWTKeyStroke keystroke : keystrokes ) {72827283if (keystroke == null) {7284throw new IllegalArgumentException("cannot set null focus traversal key");7285}72867287if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) {7288throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events");7289}72907291for (int i = 0; i < focusTraversalKeys.length; i++) {7292if (i == id) {7293continue;7294}72957296if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke))7297{7298throw new IllegalArgumentException("focus traversal keys must be unique for a Component");7299}7300}7301}7302}73037304oldKeys = focusTraversalKeys[id];7305focusTraversalKeys[id] = (keystrokes != null)7306? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes))7307: null;7308}73097310firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys,7311keystrokes);7312}7313final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) {7314// Okay to return Set directly because it is an unmodifiable view7315@SuppressWarnings("unchecked")7316Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)7317? focusTraversalKeys[id]7318: null;73197320if (keystrokes != null) {7321return keystrokes;7322} else {7323Container parent = this.parent;7324if (parent != null) {7325return parent.getFocusTraversalKeys(id);7326} else {7327return KeyboardFocusManager.getCurrentKeyboardFocusManager().7328getDefaultFocusTraversalKeys(id);7329}7330}7331}73327333/**7334* Returns whether the Set of focus traversal keys for the given focus7335* traversal operation has been explicitly defined for this Component. If7336* this method returns <code>false</code>, this Component is inheriting the7337* Set from an ancestor, or from the current KeyboardFocusManager.7338*7339* @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7340* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7341* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS7342* @return <code>true</code> if the the Set of focus traversal keys for the7343* given focus traversal operation has been explicitly defined for7344* this Component; <code>false</code> otherwise.7345* @throws IllegalArgumentException if id is not one of7346* KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,7347* KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or7348* KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS7349* @since 1.47350*/7351public boolean areFocusTraversalKeysSet(int id) {7352if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {7353throw new IllegalArgumentException("invalid focus traversal key identifier");7354}73557356return (focusTraversalKeys != null && focusTraversalKeys[id] != null);7357}73587359/**7360* Sets whether focus traversal keys are enabled for this Component.7361* Components for which focus traversal keys are disabled receive key7362* events for focus traversal keys. Components for which focus traversal7363* keys are enabled do not see these events; instead, the events are7364* automatically converted to traversal operations.7365*7366* @param focusTraversalKeysEnabled whether focus traversal keys are7367* enabled for this Component7368* @see #getFocusTraversalKeysEnabled7369* @see #setFocusTraversalKeys7370* @see #getFocusTraversalKeys7371* @since 1.47372* @beaninfo7373* bound: true7374*/7375public void setFocusTraversalKeysEnabled(boolean7376focusTraversalKeysEnabled) {7377boolean oldFocusTraversalKeysEnabled;7378synchronized (this) {7379oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled;7380this.focusTraversalKeysEnabled = focusTraversalKeysEnabled;7381}7382firePropertyChange("focusTraversalKeysEnabled",7383oldFocusTraversalKeysEnabled,7384focusTraversalKeysEnabled);7385}73867387/**7388* Returns whether focus traversal keys are enabled for this Component.7389* Components for which focus traversal keys are disabled receive key7390* events for focus traversal keys. Components for which focus traversal7391* keys are enabled do not see these events; instead, the events are7392* automatically converted to traversal operations.7393*7394* @return whether focus traversal keys are enabled for this Component7395* @see #setFocusTraversalKeysEnabled7396* @see #setFocusTraversalKeys7397* @see #getFocusTraversalKeys7398* @since 1.47399*/7400public boolean getFocusTraversalKeysEnabled() {7401return focusTraversalKeysEnabled;7402}74037404/**7405* Requests that this Component get the input focus, and that this7406* Component's top-level ancestor become the focused Window. This7407* component must be displayable, focusable, visible and all of7408* its ancestors (with the exception of the top-level Window) must7409* be visible for the request to be granted. Every effort will be7410* made to honor the request; however, in some cases it may be7411* impossible to do so. Developers must never assume that this7412* Component is the focus owner until this Component receives a7413* FOCUS_GAINED event. If this request is denied because this7414* Component's top-level Window cannot become the focused Window,7415* the request will be remembered and will be granted when the7416* Window is later focused by the user.7417* <p>7418* This method cannot be used to set the focus owner to no Component at7419* all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>7420* instead.7421* <p>7422* Because the focus behavior of this method is platform-dependent,7423* developers are strongly encouraged to use7424* <code>requestFocusInWindow</code> when possible.7425*7426* <p>Note: Not all focus transfers result from invoking this method. As7427* such, a component may receive focus without this or any of the other7428* {@code requestFocus} methods of {@code Component} being invoked.7429*7430* @see #requestFocusInWindow7431* @see java.awt.event.FocusEvent7432* @see #addFocusListener7433* @see #isFocusable7434* @see #isDisplayable7435* @see KeyboardFocusManager#clearGlobalFocusOwner7436* @since JDK1.07437*/7438public void requestFocus() {7439requestFocusHelper(false, true);7440}74417442boolean requestFocus(CausedFocusEvent.Cause cause) {7443return requestFocusHelper(false, true, cause);7444}74457446/**7447* Requests that this <code>Component</code> get the input focus,7448* and that this <code>Component</code>'s top-level ancestor7449* become the focused <code>Window</code>. This component must be7450* displayable, focusable, visible and all of its ancestors (with7451* the exception of the top-level Window) must be visible for the7452* request to be granted. Every effort will be made to honor the7453* request; however, in some cases it may be impossible to do7454* so. Developers must never assume that this component is the7455* focus owner until this component receives a FOCUS_GAINED7456* event. If this request is denied because this component's7457* top-level window cannot become the focused window, the request7458* will be remembered and will be granted when the window is later7459* focused by the user.7460* <p>7461* This method returns a boolean value. If <code>false</code> is returned,7462* the request is <b>guaranteed to fail</b>. If <code>true</code> is7463* returned, the request will succeed <b>unless</b> it is vetoed, or an7464* extraordinary event, such as disposal of the component's peer, occurs7465* before the request can be granted by the native windowing system. Again,7466* while a return value of <code>true</code> indicates that the request is7467* likely to succeed, developers must never assume that this component is7468* the focus owner until this component receives a FOCUS_GAINED event.7469* <p>7470* This method cannot be used to set the focus owner to no component at7471* all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>7472* instead.7473* <p>7474* Because the focus behavior of this method is platform-dependent,7475* developers are strongly encouraged to use7476* <code>requestFocusInWindow</code> when possible.7477* <p>7478* Every effort will be made to ensure that <code>FocusEvent</code>s7479* generated as a7480* result of this request will have the specified temporary value. However,7481* because specifying an arbitrary temporary state may not be implementable7482* on all native windowing systems, correct behavior for this method can be7483* guaranteed only for lightweight <code>Component</code>s.7484* This method is not intended7485* for general use, but exists instead as a hook for lightweight component7486* libraries, such as Swing.7487*7488* <p>Note: Not all focus transfers result from invoking this method. As7489* such, a component may receive focus without this or any of the other7490* {@code requestFocus} methods of {@code Component} being invoked.7491*7492* @param temporary true if the focus change is temporary,7493* such as when the window loses the focus; for7494* more information on temporary focus changes see the7495*<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>7496* @return <code>false</code> if the focus change request is guaranteed to7497* fail; <code>true</code> if it is likely to succeed7498* @see java.awt.event.FocusEvent7499* @see #addFocusListener7500* @see #isFocusable7501* @see #isDisplayable7502* @see KeyboardFocusManager#clearGlobalFocusOwner7503* @since 1.47504*/7505protected boolean requestFocus(boolean temporary) {7506return requestFocusHelper(temporary, true);7507}75087509boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {7510return requestFocusHelper(temporary, true, cause);7511}7512/**7513* Requests that this Component get the input focus, if this7514* Component's top-level ancestor is already the focused7515* Window. This component must be displayable, focusable, visible7516* and all of its ancestors (with the exception of the top-level7517* Window) must be visible for the request to be granted. Every7518* effort will be made to honor the request; however, in some7519* cases it may be impossible to do so. Developers must never7520* assume that this Component is the focus owner until this7521* Component receives a FOCUS_GAINED event.7522* <p>7523* This method returns a boolean value. If <code>false</code> is returned,7524* the request is <b>guaranteed to fail</b>. If <code>true</code> is7525* returned, the request will succeed <b>unless</b> it is vetoed, or an7526* extraordinary event, such as disposal of the Component's peer, occurs7527* before the request can be granted by the native windowing system. Again,7528* while a return value of <code>true</code> indicates that the request is7529* likely to succeed, developers must never assume that this Component is7530* the focus owner until this Component receives a FOCUS_GAINED event.7531* <p>7532* This method cannot be used to set the focus owner to no Component at7533* all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>7534* instead.7535* <p>7536* The focus behavior of this method can be implemented uniformly across7537* platforms, and thus developers are strongly encouraged to use this7538* method over <code>requestFocus</code> when possible. Code which relies7539* on <code>requestFocus</code> may exhibit different focus behavior on7540* different platforms.7541*7542* <p>Note: Not all focus transfers result from invoking this method. As7543* such, a component may receive focus without this or any of the other7544* {@code requestFocus} methods of {@code Component} being invoked.7545*7546* @return <code>false</code> if the focus change request is guaranteed to7547* fail; <code>true</code> if it is likely to succeed7548* @see #requestFocus7549* @see java.awt.event.FocusEvent7550* @see #addFocusListener7551* @see #isFocusable7552* @see #isDisplayable7553* @see KeyboardFocusManager#clearGlobalFocusOwner7554* @since 1.47555*/7556public boolean requestFocusInWindow() {7557return requestFocusHelper(false, false);7558}75597560boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {7561return requestFocusHelper(false, false, cause);7562}75637564/**7565* Requests that this <code>Component</code> get the input focus,7566* if this <code>Component</code>'s top-level ancestor is already7567* the focused <code>Window</code>. This component must be7568* displayable, focusable, visible and all of its ancestors (with7569* the exception of the top-level Window) must be visible for the7570* request to be granted. Every effort will be made to honor the7571* request; however, in some cases it may be impossible to do7572* so. Developers must never assume that this component is the7573* focus owner until this component receives a FOCUS_GAINED event.7574* <p>7575* This method returns a boolean value. If <code>false</code> is returned,7576* the request is <b>guaranteed to fail</b>. If <code>true</code> is7577* returned, the request will succeed <b>unless</b> it is vetoed, or an7578* extraordinary event, such as disposal of the component's peer, occurs7579* before the request can be granted by the native windowing system. Again,7580* while a return value of <code>true</code> indicates that the request is7581* likely to succeed, developers must never assume that this component is7582* the focus owner until this component receives a FOCUS_GAINED event.7583* <p>7584* This method cannot be used to set the focus owner to no component at7585* all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>7586* instead.7587* <p>7588* The focus behavior of this method can be implemented uniformly across7589* platforms, and thus developers are strongly encouraged to use this7590* method over <code>requestFocus</code> when possible. Code which relies7591* on <code>requestFocus</code> may exhibit different focus behavior on7592* different platforms.7593* <p>7594* Every effort will be made to ensure that <code>FocusEvent</code>s7595* generated as a7596* result of this request will have the specified temporary value. However,7597* because specifying an arbitrary temporary state may not be implementable7598* on all native windowing systems, correct behavior for this method can be7599* guaranteed only for lightweight components. This method is not intended7600* for general use, but exists instead as a hook for lightweight component7601* libraries, such as Swing.7602*7603* <p>Note: Not all focus transfers result from invoking this method. As7604* such, a component may receive focus without this or any of the other7605* {@code requestFocus} methods of {@code Component} being invoked.7606*7607* @param temporary true if the focus change is temporary,7608* such as when the window loses the focus; for7609* more information on temporary focus changes see the7610*<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>7611* @return <code>false</code> if the focus change request is guaranteed to7612* fail; <code>true</code> if it is likely to succeed7613* @see #requestFocus7614* @see java.awt.event.FocusEvent7615* @see #addFocusListener7616* @see #isFocusable7617* @see #isDisplayable7618* @see KeyboardFocusManager#clearGlobalFocusOwner7619* @since 1.47620*/7621protected boolean requestFocusInWindow(boolean temporary) {7622return requestFocusHelper(temporary, false);7623}76247625boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {7626return requestFocusHelper(temporary, false, cause);7627}76287629final boolean requestFocusHelper(boolean temporary,7630boolean focusedWindowChangeAllowed) {7631return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);7632}76337634final boolean requestFocusHelper(boolean temporary,7635boolean focusedWindowChangeAllowed,7636CausedFocusEvent.Cause cause)7637{7638// 1) Check if the event being dispatched is a system-generated mouse event.7639AWTEvent currentEvent = EventQueue.getCurrentEvent();7640if (currentEvent instanceof MouseEvent &&7641SunToolkit.isSystemGenerated(currentEvent))7642{7643// 2) Sanity check: if the mouse event component source belongs to the same containing window.7644Component source = ((MouseEvent)currentEvent).getComponent();7645if (source == null || source.getContainingWindow() == getContainingWindow()) {7646focusLog.finest("requesting focus by mouse event \"in window\"");76477648// If both the conditions are fulfilled the focus request should be strictly7649// bounded by the toplevel window. It's assumed that the mouse event activates7650// the window (if it wasn't active) and this makes it possible for a focus7651// request with a strong in-window requirement to change focus in the bounds7652// of the toplevel. If, by any means, due to asynchronous nature of the event7653// dispatching mechanism, the window happens to be natively inactive by the time7654// this focus request is eventually handled, it should not re-activate the7655// toplevel. Otherwise the result may not meet user expectations. See 6981400.7656focusedWindowChangeAllowed = false;7657}7658}7659if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) {7660if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7661focusLog.finest("requestFocus is not accepted");7662}7663return false;7664}7665// Update most-recent map7666KeyboardFocusManager.setMostRecentFocusOwner(this);76677668Component window = this;7669while ( (window != null) && !(window instanceof Window)) {7670if (!window.isVisible()) {7671if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7672focusLog.finest("component is recurively invisible");7673}7674return false;7675}7676window = window.parent;7677}76787679ComponentPeer peer = this.peer;7680Component heavyweight = (peer instanceof LightweightPeer)7681? getNativeContainer() : this;7682if (heavyweight == null || !heavyweight.isVisible()) {7683if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7684focusLog.finest("Component is not a part of visible hierarchy");7685}7686return false;7687}7688peer = heavyweight.peer;7689if (peer == null) {7690if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7691focusLog.finest("Peer is null");7692}7693return false;7694}76957696// Focus this Component7697long time = 0;7698if (EventQueue.isDispatchThread()) {7699time = Toolkit.getEventQueue().getMostRecentKeyEventTime();7700} else {7701// A focus request made from outside EDT should not be associated with any event7702// and so its time stamp is simply set to the current time.7703time = System.currentTimeMillis();7704}77057706boolean success = peer.requestFocus7707(this, temporary, focusedWindowChangeAllowed, time, cause);7708if (!success) {7709KeyboardFocusManager.getCurrentKeyboardFocusManager7710(appContext).dequeueKeyEvents(time, this);7711if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7712focusLog.finest("Peer request failed");7713}7714} else {7715if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7716focusLog.finest("Pass for " + this);7717}7718}7719return success;7720}77217722private boolean isRequestFocusAccepted(boolean temporary,7723boolean focusedWindowChangeAllowed,7724CausedFocusEvent.Cause cause)7725{7726if (!isFocusable() || !isVisible()) {7727if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7728focusLog.finest("Not focusable or not visible");7729}7730return false;7731}77327733ComponentPeer peer = this.peer;7734if (peer == null) {7735if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7736focusLog.finest("peer is null");7737}7738return false;7739}77407741Window window = getContainingWindow();7742if (window == null || !window.isFocusableWindow()) {7743if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7744focusLog.finest("Component doesn't have toplevel");7745}7746return false;7747}77487749// We have passed all regular checks for focus request,7750// now let's call RequestFocusController and see what it says.7751Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window);7752if (focusOwner == null) {7753// sometimes most recent focus owner may be null, but focus owner is not7754// e.g. we reset most recent focus owner if user removes focus owner7755focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();7756if (focusOwner != null && focusOwner.getContainingWindow() != window) {7757focusOwner = null;7758}7759}77607761if (focusOwner == this || focusOwner == null) {7762// Controller is supposed to verify focus transfers and for this it7763// should know both from and to components. And it shouldn't verify7764// transfers from when these components are equal.7765if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7766focusLog.finest("focus owner is null or this");7767}7768return true;7769}77707771if (CausedFocusEvent.Cause.ACTIVATION == cause) {7772// we shouldn't call RequestFocusController in case we are7773// in activation. We do request focus on component which7774// has got temporary focus lost and then on component which is7775// most recent focus owner. But most recent focus owner can be7776// changed by requestFocsuXXX() call only, so this transfer has7777// been already approved.7778if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7779focusLog.finest("cause is activation");7780}7781return true;7782}77837784boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner,7785this,7786temporary,7787focusedWindowChangeAllowed,7788cause);7789if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) {7790focusLog.finest("RequestFocusController returns {0}", ret);7791}77927793return ret;7794}77957796private static RequestFocusController requestFocusController = new DummyRequestFocusController();77977798// Swing access this method through reflection to implement InputVerifier's functionality.7799// Perhaps, we should make this method public (later ;)7800private static class DummyRequestFocusController implements RequestFocusController {7801public boolean acceptRequestFocus(Component from, Component to,7802boolean temporary, boolean focusedWindowChangeAllowed,7803CausedFocusEvent.Cause cause)7804{7805return true;7806}7807};78087809synchronized static void setRequestFocusController(RequestFocusController requestController)7810{7811if (requestController == null) {7812requestFocusController = new DummyRequestFocusController();7813} else {7814requestFocusController = requestController;7815}7816}78177818/**7819* Returns the Container which is the focus cycle root of this Component's7820* focus traversal cycle. Each focus traversal cycle has only a single7821* focus cycle root and each Component which is not a Container belongs to7822* only a single focus traversal cycle. Containers which are focus cycle7823* roots belong to two cycles: one rooted at the Container itself, and one7824* rooted at the Container's nearest focus-cycle-root ancestor. For such7825* Containers, this method will return the Container's nearest focus-cycle-7826* root ancestor.7827*7828* @return this Component's nearest focus-cycle-root ancestor7829* @see Container#isFocusCycleRoot()7830* @since 1.47831*/7832public Container getFocusCycleRootAncestor() {7833Container rootAncestor = this.parent;7834while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {7835rootAncestor = rootAncestor.parent;7836}7837return rootAncestor;7838}78397840/**7841* Returns whether the specified Container is the focus cycle root of this7842* Component's focus traversal cycle. Each focus traversal cycle has only7843* a single focus cycle root and each Component which is not a Container7844* belongs to only a single focus traversal cycle.7845*7846* @param container the Container to be tested7847* @return <code>true</code> if the specified Container is a focus-cycle-7848* root of this Component; <code>false</code> otherwise7849* @see Container#isFocusCycleRoot()7850* @since 1.47851*/7852public boolean isFocusCycleRoot(Container container) {7853Container rootAncestor = getFocusCycleRootAncestor();7854return (rootAncestor == container);7855}78567857Container getTraversalRoot() {7858return getFocusCycleRootAncestor();7859}78607861/**7862* Transfers the focus to the next component, as though this Component were7863* the focus owner.7864* @see #requestFocus()7865* @since JDK1.17866*/7867public void transferFocus() {7868nextFocus();7869}78707871/**7872* @deprecated As of JDK version 1.1,7873* replaced by transferFocus().7874*/7875@Deprecated7876public void nextFocus() {7877transferFocus(false);7878}78797880boolean transferFocus(boolean clearOnFailure) {7881if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7882focusLog.finer("clearOnFailure = " + clearOnFailure);7883}7884Component toFocus = getNextFocusCandidate();7885boolean res = false;7886if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) {7887res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD);7888}7889if (clearOnFailure && !res) {7890if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7891focusLog.finer("clear global focus owner");7892}7893KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();7894}7895if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7896focusLog.finer("returning result: " + res);7897}7898return res;7899}79007901final Component getNextFocusCandidate() {7902Container rootAncestor = getTraversalRoot();7903Component comp = this;7904while (rootAncestor != null &&7905!(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))7906{7907comp = rootAncestor;7908rootAncestor = comp.getFocusCycleRootAncestor();7909}7910if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7911focusLog.finer("comp = " + comp + ", root = " + rootAncestor);7912}7913Component candidate = null;7914if (rootAncestor != null) {7915FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();7916Component toFocus = policy.getComponentAfter(rootAncestor, comp);7917if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7918focusLog.finer("component after is " + toFocus);7919}7920if (toFocus == null) {7921toFocus = policy.getDefaultComponent(rootAncestor);7922if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7923focusLog.finer("default component is " + toFocus);7924}7925}7926if (toFocus == null) {7927Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this);7928if (applet != null) {7929toFocus = applet;7930}7931}7932candidate = toFocus;7933}7934if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7935focusLog.finer("Focus transfer candidate: " + candidate);7936}7937return candidate;7938}79397940/**7941* Transfers the focus to the previous component, as though this Component7942* were the focus owner.7943* @see #requestFocus()7944* @since 1.47945*/7946public void transferFocusBackward() {7947transferFocusBackward(false);7948}79497950boolean transferFocusBackward(boolean clearOnFailure) {7951Container rootAncestor = getTraversalRoot();7952Component comp = this;7953while (rootAncestor != null &&7954!(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner()))7955{7956comp = rootAncestor;7957rootAncestor = comp.getFocusCycleRootAncestor();7958}7959boolean res = false;7960if (rootAncestor != null) {7961FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();7962Component toFocus = policy.getComponentBefore(rootAncestor, comp);7963if (toFocus == null) {7964toFocus = policy.getDefaultComponent(rootAncestor);7965}7966if (toFocus != null) {7967res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD);7968}7969}7970if (clearOnFailure && !res) {7971if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7972focusLog.finer("clear global focus owner");7973}7974KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv();7975}7976if (focusLog.isLoggable(PlatformLogger.Level.FINER)) {7977focusLog.finer("returning result: " + res);7978}7979return res;7980}79817982/**7983* Transfers the focus up one focus traversal cycle. Typically, the focus7984* owner is set to this Component's focus cycle root, and the current focus7985* cycle root is set to the new focus owner's focus cycle root. If,7986* however, this Component's focus cycle root is a Window, then the focus7987* owner is set to the focus cycle root's default Component to focus, and7988* the current focus cycle root is unchanged.7989*7990* @see #requestFocus()7991* @see Container#isFocusCycleRoot()7992* @see Container#setFocusCycleRoot(boolean)7993* @since 1.47994*/7995public void transferFocusUpCycle() {7996Container rootAncestor;7997for (rootAncestor = getFocusCycleRootAncestor();7998rootAncestor != null && !(rootAncestor.isShowing() &&7999rootAncestor.isFocusable() &&8000rootAncestor.isEnabled());8001rootAncestor = rootAncestor.getFocusCycleRootAncestor()) {8002}80038004if (rootAncestor != null) {8005Container rootAncestorRootAncestor =8006rootAncestor.getFocusCycleRootAncestor();8007Container fcr = (rootAncestorRootAncestor != null) ?8008rootAncestorRootAncestor : rootAncestor;80098010KeyboardFocusManager.getCurrentKeyboardFocusManager().8011setGlobalCurrentFocusCycleRootPriv(fcr);8012rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);8013} else {8014Window window = getContainingWindow();80158016if (window != null) {8017Component toFocus = window.getFocusTraversalPolicy().8018getDefaultComponent(window);8019if (toFocus != null) {8020KeyboardFocusManager.getCurrentKeyboardFocusManager().8021setGlobalCurrentFocusCycleRootPriv(window);8022toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);8023}8024}8025}8026}80278028/**8029* Returns <code>true</code> if this <code>Component</code> is the8030* focus owner. This method is obsolete, and has been replaced by8031* <code>isFocusOwner()</code>.8032*8033* @return <code>true</code> if this <code>Component</code> is the8034* focus owner; <code>false</code> otherwise8035* @since 1.28036*/8037public boolean hasFocus() {8038return (KeyboardFocusManager.getCurrentKeyboardFocusManager().8039getFocusOwner() == this);8040}80418042/**8043* Returns <code>true</code> if this <code>Component</code> is the8044* focus owner.8045*8046* @return <code>true</code> if this <code>Component</code> is the8047* focus owner; <code>false</code> otherwise8048* @since 1.48049*/8050public boolean isFocusOwner() {8051return hasFocus();8052}80538054/*8055* Used to disallow auto-focus-transfer on disposal of the focus owner8056* in the process of disposing its parent container.8057*/8058private boolean autoFocusTransferOnDisposal = true;80598060void setAutoFocusTransferOnDisposal(boolean value) {8061autoFocusTransferOnDisposal = value;8062}80638064boolean isAutoFocusTransferOnDisposal() {8065return autoFocusTransferOnDisposal;8066}80678068/**8069* Adds the specified popup menu to the component.8070* @param popup the popup menu to be added to the component.8071* @see #remove(MenuComponent)8072* @exception NullPointerException if {@code popup} is {@code null}8073* @since JDK1.18074*/8075public void add(PopupMenu popup) {8076synchronized (getTreeLock()) {8077if (popup.parent != null) {8078popup.parent.remove(popup);8079}8080if (popups == null) {8081popups = new Vector<PopupMenu>();8082}8083popups.addElement(popup);8084popup.parent = this;80858086if (peer != null) {8087if (popup.peer == null) {8088popup.addNotify();8089}8090}8091}8092}80938094/**8095* Removes the specified popup menu from the component.8096* @param popup the popup menu to be removed8097* @see #add(PopupMenu)8098* @since JDK1.18099*/8100@SuppressWarnings("unchecked")8101public void remove(MenuComponent popup) {8102synchronized (getTreeLock()) {8103if (popups == null) {8104return;8105}8106int index = popups.indexOf(popup);8107if (index >= 0) {8108PopupMenu pmenu = (PopupMenu)popup;8109if (pmenu.peer != null) {8110pmenu.removeNotify();8111}8112pmenu.parent = null;8113popups.removeElementAt(index);8114if (popups.size() == 0) {8115popups = null;8116}8117}8118}8119}81208121/**8122* Returns a string representing the state of this component. This8123* method is intended to be used only for debugging purposes, and the8124* content and format of the returned string may vary between8125* implementations. The returned string may be empty but may not be8126* <code>null</code>.8127*8128* @return a string representation of this component's state8129* @since JDK1.08130*/8131protected String paramString() {8132final String thisName = Objects.toString(getName(), "");8133final String invalid = isValid() ? "" : ",invalid";8134final String hidden = visible ? "" : ",hidden";8135final String disabled = enabled ? "" : ",disabled";8136return thisName + ',' + x + ',' + y + ',' + width + 'x' + height8137+ invalid + hidden + disabled;8138}81398140/**8141* Returns a string representation of this component and its values.8142* @return a string representation of this component8143* @since JDK1.08144*/8145public String toString() {8146return getClass().getName() + '[' + paramString() + ']';8147}81488149/**8150* Prints a listing of this component to the standard system output8151* stream <code>System.out</code>.8152* @see java.lang.System#out8153* @since JDK1.08154*/8155public void list() {8156list(System.out, 0);8157}81588159/**8160* Prints a listing of this component to the specified output8161* stream.8162* @param out a print stream8163* @throws NullPointerException if {@code out} is {@code null}8164* @since JDK1.08165*/8166public void list(PrintStream out) {8167list(out, 0);8168}81698170/**8171* Prints out a list, starting at the specified indentation, to the8172* specified print stream.8173* @param out a print stream8174* @param indent number of spaces to indent8175* @see java.io.PrintStream#println(java.lang.Object)8176* @throws NullPointerException if {@code out} is {@code null}8177* @since JDK1.08178*/8179public void list(PrintStream out, int indent) {8180for (int i = 0 ; i < indent ; i++) {8181out.print(" ");8182}8183out.println(this);8184}81858186/**8187* Prints a listing to the specified print writer.8188* @param out the print writer to print to8189* @throws NullPointerException if {@code out} is {@code null}8190* @since JDK1.18191*/8192public void list(PrintWriter out) {8193list(out, 0);8194}81958196/**8197* Prints out a list, starting at the specified indentation, to8198* the specified print writer.8199* @param out the print writer to print to8200* @param indent the number of spaces to indent8201* @throws NullPointerException if {@code out} is {@code null}8202* @see java.io.PrintStream#println(java.lang.Object)8203* @since JDK1.18204*/8205public void list(PrintWriter out, int indent) {8206for (int i = 0 ; i < indent ; i++) {8207out.print(" ");8208}8209out.println(this);8210}82118212/*8213* Fetches the native container somewhere higher up in the component8214* tree that contains this component.8215*/8216final Container getNativeContainer() {8217Container p = getContainer();8218while (p != null && p.peer instanceof LightweightPeer) {8219p = p.getContainer();8220}8221return p;8222}82238224/**8225* Adds a PropertyChangeListener to the listener list. The listener is8226* registered for all bound properties of this class, including the8227* following:8228* <ul>8229* <li>this Component's font ("font")</li>8230* <li>this Component's background color ("background")</li>8231* <li>this Component's foreground color ("foreground")</li>8232* <li>this Component's focusability ("focusable")</li>8233* <li>this Component's focus traversal keys enabled state8234* ("focusTraversalKeysEnabled")</li>8235* <li>this Component's Set of FORWARD_TRAVERSAL_KEYS8236* ("forwardFocusTraversalKeys")</li>8237* <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS8238* ("backwardFocusTraversalKeys")</li>8239* <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS8240* ("upCycleFocusTraversalKeys")</li>8241* <li>this Component's preferred size ("preferredSize")</li>8242* <li>this Component's minimum size ("minimumSize")</li>8243* <li>this Component's maximum size ("maximumSize")</li>8244* <li>this Component's name ("name")</li>8245* </ul>8246* Note that if this <code>Component</code> is inheriting a bound property, then no8247* event will be fired in response to a change in the inherited property.8248* <p>8249* If <code>listener</code> is <code>null</code>,8250* no exception is thrown and no action is performed.8251*8252* @param listener the property change listener to be added8253*8254* @see #removePropertyChangeListener8255* @see #getPropertyChangeListeners8256* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8257*/8258public void addPropertyChangeListener(8259PropertyChangeListener listener) {8260synchronized (getObjectLock()) {8261if (listener == null) {8262return;8263}8264if (changeSupport == null) {8265changeSupport = new PropertyChangeSupport(this);8266}8267changeSupport.addPropertyChangeListener(listener);8268}8269}82708271/**8272* Removes a PropertyChangeListener from the listener list. This method8273* should be used to remove PropertyChangeListeners that were registered8274* for all bound properties of this class.8275* <p>8276* If listener is null, no exception is thrown and no action is performed.8277*8278* @param listener the PropertyChangeListener to be removed8279*8280* @see #addPropertyChangeListener8281* @see #getPropertyChangeListeners8282* @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)8283*/8284public void removePropertyChangeListener(8285PropertyChangeListener listener) {8286synchronized (getObjectLock()) {8287if (listener == null || changeSupport == null) {8288return;8289}8290changeSupport.removePropertyChangeListener(listener);8291}8292}82938294/**8295* Returns an array of all the property change listeners8296* registered on this component.8297*8298* @return all of this component's <code>PropertyChangeListener</code>s8299* or an empty array if no property change8300* listeners are currently registered8301*8302* @see #addPropertyChangeListener8303* @see #removePropertyChangeListener8304* @see #getPropertyChangeListeners(java.lang.String)8305* @see java.beans.PropertyChangeSupport#getPropertyChangeListeners8306* @since 1.48307*/8308public PropertyChangeListener[] getPropertyChangeListeners() {8309synchronized (getObjectLock()) {8310if (changeSupport == null) {8311return new PropertyChangeListener[0];8312}8313return changeSupport.getPropertyChangeListeners();8314}8315}83168317/**8318* Adds a PropertyChangeListener to the listener list for a specific8319* property. The specified property may be user-defined, or one of the8320* following:8321* <ul>8322* <li>this Component's font ("font")</li>8323* <li>this Component's background color ("background")</li>8324* <li>this Component's foreground color ("foreground")</li>8325* <li>this Component's focusability ("focusable")</li>8326* <li>this Component's focus traversal keys enabled state8327* ("focusTraversalKeysEnabled")</li>8328* <li>this Component's Set of FORWARD_TRAVERSAL_KEYS8329* ("forwardFocusTraversalKeys")</li>8330* <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS8331* ("backwardFocusTraversalKeys")</li>8332* <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS8333* ("upCycleFocusTraversalKeys")</li>8334* </ul>8335* Note that if this <code>Component</code> is inheriting a bound property, then no8336* event will be fired in response to a change in the inherited property.8337* <p>8338* If <code>propertyName</code> or <code>listener</code> is <code>null</code>,8339* no exception is thrown and no action is taken.8340*8341* @param propertyName one of the property names listed above8342* @param listener the property change listener to be added8343*8344* @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8345* @see #getPropertyChangeListeners(java.lang.String)8346* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8347*/8348public void addPropertyChangeListener(8349String propertyName,8350PropertyChangeListener listener) {8351synchronized (getObjectLock()) {8352if (listener == null) {8353return;8354}8355if (changeSupport == null) {8356changeSupport = new PropertyChangeSupport(this);8357}8358changeSupport.addPropertyChangeListener(propertyName, listener);8359}8360}83618362/**8363* Removes a <code>PropertyChangeListener</code> from the listener8364* list for a specific property. This method should be used to remove8365* <code>PropertyChangeListener</code>s8366* that were registered for a specific bound property.8367* <p>8368* If <code>propertyName</code> or <code>listener</code> is <code>null</code>,8369* no exception is thrown and no action is taken.8370*8371* @param propertyName a valid property name8372* @param listener the PropertyChangeListener to be removed8373*8374* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8375* @see #getPropertyChangeListeners(java.lang.String)8376* @see #removePropertyChangeListener(java.beans.PropertyChangeListener)8377*/8378public void removePropertyChangeListener(8379String propertyName,8380PropertyChangeListener listener) {8381synchronized (getObjectLock()) {8382if (listener == null || changeSupport == null) {8383return;8384}8385changeSupport.removePropertyChangeListener(propertyName, listener);8386}8387}83888389/**8390* Returns an array of all the listeners which have been associated8391* with the named property.8392*8393* @return all of the <code>PropertyChangeListener</code>s associated with8394* the named property; if no such listeners have been added or8395* if <code>propertyName</code> is <code>null</code>, an empty8396* array is returned8397*8398* @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8399* @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)8400* @see #getPropertyChangeListeners8401* @since 1.48402*/8403public PropertyChangeListener[] getPropertyChangeListeners(8404String propertyName) {8405synchronized (getObjectLock()) {8406if (changeSupport == null) {8407return new PropertyChangeListener[0];8408}8409return changeSupport.getPropertyChangeListeners(propertyName);8410}8411}84128413/**8414* Support for reporting bound property changes for Object properties.8415* This method can be called when a bound property has changed and it will8416* send the appropriate PropertyChangeEvent to any registered8417* PropertyChangeListeners.8418*8419* @param propertyName the property whose value has changed8420* @param oldValue the property's previous value8421* @param newValue the property's new value8422*/8423protected void firePropertyChange(String propertyName,8424Object oldValue, Object newValue) {8425PropertyChangeSupport changeSupport;8426synchronized (getObjectLock()) {8427changeSupport = this.changeSupport;8428}8429if (changeSupport == null ||8430(oldValue != null && newValue != null && oldValue.equals(newValue))) {8431return;8432}8433changeSupport.firePropertyChange(propertyName, oldValue, newValue);8434}84358436/**8437* Support for reporting bound property changes for boolean properties.8438* This method can be called when a bound property has changed and it will8439* send the appropriate PropertyChangeEvent to any registered8440* PropertyChangeListeners.8441*8442* @param propertyName the property whose value has changed8443* @param oldValue the property's previous value8444* @param newValue the property's new value8445* @since 1.48446*/8447protected void firePropertyChange(String propertyName,8448boolean oldValue, boolean newValue) {8449PropertyChangeSupport changeSupport = this.changeSupport;8450if (changeSupport == null || oldValue == newValue) {8451return;8452}8453changeSupport.firePropertyChange(propertyName, oldValue, newValue);8454}84558456/**8457* Support for reporting bound property changes for integer properties.8458* This method can be called when a bound property has changed and it will8459* send the appropriate PropertyChangeEvent to any registered8460* PropertyChangeListeners.8461*8462* @param propertyName the property whose value has changed8463* @param oldValue the property's previous value8464* @param newValue the property's new value8465* @since 1.48466*/8467protected void firePropertyChange(String propertyName,8468int oldValue, int newValue) {8469PropertyChangeSupport changeSupport = this.changeSupport;8470if (changeSupport == null || oldValue == newValue) {8471return;8472}8473changeSupport.firePropertyChange(propertyName, oldValue, newValue);8474}84758476/**8477* Reports a bound property change.8478*8479* @param propertyName the programmatic name of the property8480* that was changed8481* @param oldValue the old value of the property (as a byte)8482* @param newValue the new value of the property (as a byte)8483* @see #firePropertyChange(java.lang.String, java.lang.Object,8484* java.lang.Object)8485* @since 1.58486*/8487public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {8488if (changeSupport == null || oldValue == newValue) {8489return;8490}8491firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue));8492}84938494/**8495* Reports a bound property change.8496*8497* @param propertyName the programmatic name of the property8498* that was changed8499* @param oldValue the old value of the property (as a char)8500* @param newValue the new value of the property (as a char)8501* @see #firePropertyChange(java.lang.String, java.lang.Object,8502* java.lang.Object)8503* @since 1.58504*/8505public void firePropertyChange(String propertyName, char oldValue, char newValue) {8506if (changeSupport == null || oldValue == newValue) {8507return;8508}8509firePropertyChange(propertyName, new Character(oldValue), new Character(newValue));8510}85118512/**8513* Reports a bound property change.8514*8515* @param propertyName the programmatic name of the property8516* that was changed8517* @param oldValue the old value of the property (as a short)8518* @param newValue the old value of the property (as a short)8519* @see #firePropertyChange(java.lang.String, java.lang.Object,8520* java.lang.Object)8521* @since 1.58522*/8523public void firePropertyChange(String propertyName, short oldValue, short newValue) {8524if (changeSupport == null || oldValue == newValue) {8525return;8526}8527firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue));8528}852985308531/**8532* Reports a bound property change.8533*8534* @param propertyName the programmatic name of the property8535* that was changed8536* @param oldValue the old value of the property (as a long)8537* @param newValue the new value of the property (as a long)8538* @see #firePropertyChange(java.lang.String, java.lang.Object,8539* java.lang.Object)8540* @since 1.58541*/8542public void firePropertyChange(String propertyName, long oldValue, long newValue) {8543if (changeSupport == null || oldValue == newValue) {8544return;8545}8546firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue));8547}85488549/**8550* Reports a bound property change.8551*8552* @param propertyName the programmatic name of the property8553* that was changed8554* @param oldValue the old value of the property (as a float)8555* @param newValue the new value of the property (as a float)8556* @see #firePropertyChange(java.lang.String, java.lang.Object,8557* java.lang.Object)8558* @since 1.58559*/8560public void firePropertyChange(String propertyName, float oldValue, float newValue) {8561if (changeSupport == null || oldValue == newValue) {8562return;8563}8564firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue));8565}85668567/**8568* Reports a bound property change.8569*8570* @param propertyName the programmatic name of the property8571* that was changed8572* @param oldValue the old value of the property (as a double)8573* @param newValue the new value of the property (as a double)8574* @see #firePropertyChange(java.lang.String, java.lang.Object,8575* java.lang.Object)8576* @since 1.58577*/8578public void firePropertyChange(String propertyName, double oldValue, double newValue) {8579if (changeSupport == null || oldValue == newValue) {8580return;8581}8582firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));8583}858485858586// Serialization support.85878588/**8589* Component Serialized Data Version.8590*8591* @serial8592*/8593private int componentSerializedDataVersion = 4;85948595/**8596* This hack is for Swing serialization. It will invoke8597* the Swing package private method <code>compWriteObjectNotify</code>.8598*/8599private void doSwingSerialization() {8600Package swingPackage = Package.getPackage("javax.swing");8601// For Swing serialization to correctly work Swing needs to8602// be notified before Component does it's serialization. This8603// hack accomodates this.8604//8605// Swing classes MUST be loaded by the bootstrap class loader,8606// otherwise we don't consider them.8607for (Class<?> klass = Component.this.getClass(); klass != null;8608klass = klass.getSuperclass()) {8609if (klass.getPackage() == swingPackage &&8610klass.getClassLoader() == null) {8611final Class<?> swingClass = klass;8612// Find the first override of the compWriteObjectNotify method8613Method[] methods = AccessController.doPrivileged(8614new PrivilegedAction<Method[]>() {8615public Method[] run() {8616return swingClass.getDeclaredMethods();8617}8618});8619for (int counter = methods.length - 1; counter >= 0;8620counter--) {8621final Method method = methods[counter];8622if (method.getName().equals("compWriteObjectNotify")){8623// We found it, use doPrivileged to make it accessible8624// to use.8625AccessController.doPrivileged(new PrivilegedAction<Void>() {8626public Void run() {8627method.setAccessible(true);8628return null;8629}8630});8631// Invoke the method8632try {8633method.invoke(this, (Object[]) null);8634} catch (IllegalAccessException iae) {8635} catch (InvocationTargetException ite) {8636}8637// We're done, bail.8638return;8639}8640}8641}8642}8643}86448645/**8646* Writes default serializable fields to stream. Writes8647* a variety of serializable listeners as optional data.8648* The non-serializable listeners are detected and8649* no attempt is made to serialize them.8650*8651* @param s the <code>ObjectOutputStream</code> to write8652* @serialData <code>null</code> terminated sequence of8653* 0 or more pairs; the pair consists of a <code>String</code>8654* and an <code>Object</code>; the <code>String</code> indicates8655* the type of object and is one of the following (as of 1.4):8656* <code>componentListenerK</code> indicating an8657* <code>ComponentListener</code> object;8658* <code>focusListenerK</code> indicating an8659* <code>FocusListener</code> object;8660* <code>keyListenerK</code> indicating an8661* <code>KeyListener</code> object;8662* <code>mouseListenerK</code> indicating an8663* <code>MouseListener</code> object;8664* <code>mouseMotionListenerK</code> indicating an8665* <code>MouseMotionListener</code> object;8666* <code>inputMethodListenerK</code> indicating an8667* <code>InputMethodListener</code> object;8668* <code>hierarchyListenerK</code> indicating an8669* <code>HierarchyListener</code> object;8670* <code>hierarchyBoundsListenerK</code> indicating an8671* <code>HierarchyBoundsListener</code> object;8672* <code>mouseWheelListenerK</code> indicating an8673* <code>MouseWheelListener</code> object8674* @serialData an optional <code>ComponentOrientation</code>8675* (after <code>inputMethodListener</code>, as of 1.2)8676*8677* @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)8678* @see #componentListenerK8679* @see #focusListenerK8680* @see #keyListenerK8681* @see #mouseListenerK8682* @see #mouseMotionListenerK8683* @see #inputMethodListenerK8684* @see #hierarchyListenerK8685* @see #hierarchyBoundsListenerK8686* @see #mouseWheelListenerK8687* @see #readObject(ObjectInputStream)8688*/8689private void writeObject(ObjectOutputStream s)8690throws IOException8691{8692doSwingSerialization();86938694s.defaultWriteObject();86958696AWTEventMulticaster.save(s, componentListenerK, componentListener);8697AWTEventMulticaster.save(s, focusListenerK, focusListener);8698AWTEventMulticaster.save(s, keyListenerK, keyListener);8699AWTEventMulticaster.save(s, mouseListenerK, mouseListener);8700AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);8701AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);87028703s.writeObject(null);8704s.writeObject(componentOrientation);87058706AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);8707AWTEventMulticaster.save(s, hierarchyBoundsListenerK,8708hierarchyBoundsListener);8709s.writeObject(null);87108711AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);8712s.writeObject(null);87138714}87158716/**8717* Reads the <code>ObjectInputStream</code> and if it isn't8718* <code>null</code> adds a listener to receive a variety8719* of events fired by the component.8720* Unrecognized keys or values will be ignored.8721*8722* @param s the <code>ObjectInputStream</code> to read8723* @see #writeObject(ObjectOutputStream)8724*/8725private void readObject(ObjectInputStream s)8726throws ClassNotFoundException, IOException8727{8728objectLock = new Object();87298730acc = AccessController.getContext();87318732s.defaultReadObject();87338734appContext = AppContext.getAppContext();8735coalescingEnabled = checkCoalescing();8736if (componentSerializedDataVersion < 4) {8737// These fields are non-transient and rely on default8738// serialization. However, the default values are insufficient,8739// so we need to set them explicitly for object data streams prior8740// to 1.4.8741focusable = true;8742isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;8743initializeFocusTraversalKeys();8744focusTraversalKeysEnabled = true;8745}87468747Object keyOrNull;8748while(null != (keyOrNull = s.readObject())) {8749String key = ((String)keyOrNull).intern();87508751if (componentListenerK == key)8752addComponentListener((ComponentListener)(s.readObject()));87538754else if (focusListenerK == key)8755addFocusListener((FocusListener)(s.readObject()));87568757else if (keyListenerK == key)8758addKeyListener((KeyListener)(s.readObject()));87598760else if (mouseListenerK == key)8761addMouseListener((MouseListener)(s.readObject()));87628763else if (mouseMotionListenerK == key)8764addMouseMotionListener((MouseMotionListener)(s.readObject()));87658766else if (inputMethodListenerK == key)8767addInputMethodListener((InputMethodListener)(s.readObject()));87688769else // skip value for unrecognized key8770s.readObject();87718772}87738774// Read the component's orientation if it's present8775Object orient = null;87768777try {8778orient = s.readObject();8779} catch (java.io.OptionalDataException e) {8780// JDK 1.1 instances will not have this optional data.8781// e.eof will be true to indicate that there is no more8782// data available for this object.8783// If e.eof is not true, throw the exception as it8784// might have been caused by reasons unrelated to8785// componentOrientation.87868787if (!e.eof) {8788throw (e);8789}8790}87918792if (orient != null) {8793componentOrientation = (ComponentOrientation)orient;8794} else {8795componentOrientation = ComponentOrientation.UNKNOWN;8796}87978798try {8799while(null != (keyOrNull = s.readObject())) {8800String key = ((String)keyOrNull).intern();88018802if (hierarchyListenerK == key) {8803addHierarchyListener((HierarchyListener)(s.readObject()));8804}8805else if (hierarchyBoundsListenerK == key) {8806addHierarchyBoundsListener((HierarchyBoundsListener)8807(s.readObject()));8808}8809else {8810// skip value for unrecognized key8811s.readObject();8812}8813}8814} catch (java.io.OptionalDataException e) {8815// JDK 1.1/1.2 instances will not have this optional data.8816// e.eof will be true to indicate that there is no more8817// data available for this object.8818// If e.eof is not true, throw the exception as it8819// might have been caused by reasons unrelated to8820// hierarchy and hierarchyBounds listeners.88218822if (!e.eof) {8823throw (e);8824}8825}88268827try {8828while (null != (keyOrNull = s.readObject())) {8829String key = ((String)keyOrNull).intern();88308831if (mouseWheelListenerK == key) {8832addMouseWheelListener((MouseWheelListener)(s.readObject()));8833}8834else {8835// skip value for unrecognized key8836s.readObject();8837}8838}8839} catch (java.io.OptionalDataException e) {8840// pre-1.3 instances will not have this optional data.8841// e.eof will be true to indicate that there is no more8842// data available for this object.8843// If e.eof is not true, throw the exception as it8844// might have been caused by reasons unrelated to8845// mouse wheel listeners88468847if (!e.eof) {8848throw (e);8849}8850}88518852if (popups != null) {8853int npopups = popups.size();8854for (int i = 0 ; i < npopups ; i++) {8855PopupMenu popup = popups.elementAt(i);8856popup.parent = this;8857}8858}8859}88608861/**8862* Sets the language-sensitive orientation that is to be used to order8863* the elements or text within this component. Language-sensitive8864* <code>LayoutManager</code> and <code>Component</code>8865* subclasses will use this property to8866* determine how to lay out and draw components.8867* <p>8868* At construction time, a component's orientation is set to8869* <code>ComponentOrientation.UNKNOWN</code>,8870* indicating that it has not been specified8871* explicitly. The UNKNOWN orientation behaves the same as8872* <code>ComponentOrientation.LEFT_TO_RIGHT</code>.8873* <p>8874* To set the orientation of a single component, use this method.8875* To set the orientation of an entire component8876* hierarchy, use8877* {@link #applyComponentOrientation applyComponentOrientation}.8878* <p>8879* This method changes layout-related information, and therefore,8880* invalidates the component hierarchy.8881*8882*8883* @see ComponentOrientation8884* @see #invalidate8885*8886* @author Laura Werner, IBM8887* @beaninfo8888* bound: true8889*/8890public void setComponentOrientation(ComponentOrientation o) {8891ComponentOrientation oldValue = componentOrientation;8892componentOrientation = o;88938894// This is a bound property, so report the change to8895// any registered listeners. (Cheap if there are none.)8896firePropertyChange("componentOrientation", oldValue, o);88978898// This could change the preferred size of the Component.8899invalidateIfValid();8900}89018902/**8903* Retrieves the language-sensitive orientation that is to be used to order8904* the elements or text within this component. <code>LayoutManager</code>8905* and <code>Component</code>8906* subclasses that wish to respect orientation should call this method to8907* get the component's orientation before performing layout or drawing.8908*8909* @see ComponentOrientation8910*8911* @author Laura Werner, IBM8912*/8913public ComponentOrientation getComponentOrientation() {8914return componentOrientation;8915}89168917/**8918* Sets the <code>ComponentOrientation</code> property of this component8919* and all components contained within it.8920* <p>8921* This method changes layout-related information, and therefore,8922* invalidates the component hierarchy.8923*8924*8925* @param orientation the new component orientation of this component and8926* the components contained within it.8927* @exception NullPointerException if <code>orientation</code> is null.8928* @see #setComponentOrientation8929* @see #getComponentOrientation8930* @see #invalidate8931* @since 1.48932*/8933public void applyComponentOrientation(ComponentOrientation orientation) {8934if (orientation == null) {8935throw new NullPointerException();8936}8937setComponentOrientation(orientation);8938}89398940final boolean canBeFocusOwner() {8941// It is enabled, visible, focusable.8942if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {8943return true;8944}8945return false;8946}89478948/**8949* Checks that this component meets the prerequesites to be focus owner:8950* - it is enabled, visible, focusable8951* - it's parents are all enabled and showing8952* - top-level window is focusable8953* - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts8954* this component as focus owner8955* @since 1.58956*/8957final boolean canBeFocusOwnerRecursively() {8958// - it is enabled, visible, focusable8959if (!canBeFocusOwner()) {8960return false;8961}89628963// - it's parents are all enabled and showing8964synchronized(getTreeLock()) {8965if (parent != null) {8966return parent.canContainFocusOwner(this);8967}8968}8969return true;8970}89718972/**8973* Fix the location of the HW component in a LW container hierarchy.8974*/8975final void relocateComponent() {8976synchronized (getTreeLock()) {8977if (peer == null) {8978return;8979}8980int nativeX = x;8981int nativeY = y;8982for (Component cont = getContainer();8983cont != null && cont.isLightweight();8984cont = cont.getContainer())8985{8986nativeX += cont.x;8987nativeY += cont.y;8988}8989peer.setBounds(nativeX, nativeY, width, height,8990ComponentPeer.SET_LOCATION);8991}8992}89938994/**8995* Returns the <code>Window</code> ancestor of the component.8996* @return Window ancestor of the component or component by itself if it is Window;8997* null, if component is not a part of window hierarchy8998*/8999Window getContainingWindow() {9000return SunToolkit.getContainingWindow(this);9001}90029003/**9004* Initialize JNI field and method IDs9005*/9006private static native void initIDs();90079008/*9009* --- Accessibility Support ---9010*9011* Component will contain all of the methods in interface Accessible,9012* though it won't actually implement the interface - that will be up9013* to the individual objects which extend Component.9014*/90159016/**9017* The {@code AccessibleContext} associated with this {@code Component}.9018*/9019protected AccessibleContext accessibleContext = null;90209021/**9022* Gets the <code>AccessibleContext</code> associated9023* with this <code>Component</code>.9024* The method implemented by this base9025* class returns null. Classes that extend <code>Component</code>9026* should implement this method to return the9027* <code>AccessibleContext</code> associated with the subclass.9028*9029*9030* @return the <code>AccessibleContext</code> of this9031* <code>Component</code>9032* @since 1.39033*/9034public AccessibleContext getAccessibleContext() {9035return accessibleContext;9036}90379038/**9039* Inner class of Component used to provide default support for9040* accessibility. This class is not meant to be used directly by9041* application developers, but is instead meant only to be9042* subclassed by component developers.9043* <p>9044* The class used to obtain the accessible role for this object.9045* @since 1.39046*/9047protected abstract class AccessibleAWTComponent extends AccessibleContext9048implements Serializable, AccessibleComponent {90499050private static final long serialVersionUID = 642321655757800191L;90519052/**9053* Though the class is abstract, this should be called by9054* all sub-classes.9055*/9056protected AccessibleAWTComponent() {9057}90589059/**9060* Number of PropertyChangeListener objects registered. It's used9061* to add/remove ComponentListener and FocusListener to track9062* target Component's state.9063*/9064private volatile transient int propertyListenersCount = 0;90659066protected ComponentListener accessibleAWTComponentHandler = null;9067protected FocusListener accessibleAWTFocusHandler = null;90689069/**9070* Fire PropertyChange listener, if one is registered,9071* when shown/hidden..9072* @since 1.39073*/9074protected class AccessibleAWTComponentHandler implements ComponentListener {9075public void componentHidden(ComponentEvent e) {9076if (accessibleContext != null) {9077accessibleContext.firePropertyChange(9078AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9079AccessibleState.VISIBLE, null);9080}9081}90829083public void componentShown(ComponentEvent e) {9084if (accessibleContext != null) {9085accessibleContext.firePropertyChange(9086AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9087null, AccessibleState.VISIBLE);9088}9089}90909091public void componentMoved(ComponentEvent e) {9092}90939094public void componentResized(ComponentEvent e) {9095}9096} // inner class AccessibleAWTComponentHandler909790989099/**9100* Fire PropertyChange listener, if one is registered,9101* when focus events happen9102* @since 1.39103*/9104protected class AccessibleAWTFocusHandler implements FocusListener {9105public void focusGained(FocusEvent event) {9106if (accessibleContext != null) {9107accessibleContext.firePropertyChange(9108AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9109null, AccessibleState.FOCUSED);9110}9111}9112public void focusLost(FocusEvent event) {9113if (accessibleContext != null) {9114accessibleContext.firePropertyChange(9115AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9116AccessibleState.FOCUSED, null);9117}9118}9119} // inner class AccessibleAWTFocusHandler912091219122/**9123* Adds a <code>PropertyChangeListener</code> to the listener list.9124*9125* @param listener the property change listener to be added9126*/9127public void addPropertyChangeListener(PropertyChangeListener listener) {9128if (accessibleAWTComponentHandler == null) {9129accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();9130}9131if (accessibleAWTFocusHandler == null) {9132accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();9133}9134if (propertyListenersCount++ == 0) {9135Component.this.addComponentListener(accessibleAWTComponentHandler);9136Component.this.addFocusListener(accessibleAWTFocusHandler);9137}9138super.addPropertyChangeListener(listener);9139}91409141/**9142* Remove a PropertyChangeListener from the listener list.9143* This removes a PropertyChangeListener that was registered9144* for all properties.9145*9146* @param listener The PropertyChangeListener to be removed9147*/9148public void removePropertyChangeListener(PropertyChangeListener listener) {9149if (--propertyListenersCount == 0) {9150Component.this.removeComponentListener(accessibleAWTComponentHandler);9151Component.this.removeFocusListener(accessibleAWTFocusHandler);9152}9153super.removePropertyChangeListener(listener);9154}91559156// AccessibleContext methods9157//9158/**9159* Gets the accessible name of this object. This should almost never9160* return <code>java.awt.Component.getName()</code>,9161* as that generally isn't a localized name,9162* and doesn't have meaning for the user. If the9163* object is fundamentally a text object (e.g. a menu item), the9164* accessible name should be the text of the object (e.g. "save").9165* If the object has a tooltip, the tooltip text may also be an9166* appropriate String to return.9167*9168* @return the localized name of the object -- can be9169* <code>null</code> if this9170* object does not have a name9171* @see javax.accessibility.AccessibleContext#setAccessibleName9172*/9173public String getAccessibleName() {9174return accessibleName;9175}91769177/**9178* Gets the accessible description of this object. This should be9179* a concise, localized description of what this object is - what9180* is its meaning to the user. If the object has a tooltip, the9181* tooltip text may be an appropriate string to return, assuming9182* it contains a concise description of the object (instead of just9183* the name of the object - e.g. a "Save" icon on a toolbar that9184* had "save" as the tooltip text shouldn't return the tooltip9185* text as the description, but something like "Saves the current9186* text document" instead).9187*9188* @return the localized description of the object -- can be9189* <code>null</code> if this object does not have a description9190* @see javax.accessibility.AccessibleContext#setAccessibleDescription9191*/9192public String getAccessibleDescription() {9193return accessibleDescription;9194}91959196/**9197* Gets the role of this object.9198*9199* @return an instance of <code>AccessibleRole</code>9200* describing the role of the object9201* @see javax.accessibility.AccessibleRole9202*/9203public AccessibleRole getAccessibleRole() {9204return AccessibleRole.AWT_COMPONENT;9205}92069207/**9208* Gets the state of this object.9209*9210* @return an instance of <code>AccessibleStateSet</code>9211* containing the current state set of the object9212* @see javax.accessibility.AccessibleState9213*/9214public AccessibleStateSet getAccessibleStateSet() {9215return Component.this.getAccessibleStateSet();9216}92179218/**9219* Gets the <code>Accessible</code> parent of this object.9220* If the parent of this object implements <code>Accessible</code>,9221* this method should simply return <code>getParent</code>.9222*9223* @return the <code>Accessible</code> parent of this9224* object -- can be <code>null</code> if this9225* object does not have an <code>Accessible</code> parent9226*/9227public Accessible getAccessibleParent() {9228if (accessibleParent != null) {9229return accessibleParent;9230} else {9231Container parent = getParent();9232if (parent instanceof Accessible) {9233return (Accessible) parent;9234}9235}9236return null;9237}92389239/**9240* Gets the index of this object in its accessible parent.9241*9242* @return the index of this object in its parent; or -1 if this9243* object does not have an accessible parent9244* @see #getAccessibleParent9245*/9246public int getAccessibleIndexInParent() {9247return Component.this.getAccessibleIndexInParent();9248}92499250/**9251* Returns the number of accessible children in the object. If all9252* of the children of this object implement <code>Accessible</code>,9253* then this method should return the number of children of this object.9254*9255* @return the number of accessible children in the object9256*/9257public int getAccessibleChildrenCount() {9258return 0; // Components don't have children9259}92609261/**9262* Returns the nth <code>Accessible</code> child of the object.9263*9264* @param i zero-based index of child9265* @return the nth <code>Accessible</code> child of the object9266*/9267public Accessible getAccessibleChild(int i) {9268return null; // Components don't have children9269}92709271/**9272* Returns the locale of this object.9273*9274* @return the locale of this object9275*/9276public Locale getLocale() {9277return Component.this.getLocale();9278}92799280/**9281* Gets the <code>AccessibleComponent</code> associated9282* with this object if one exists.9283* Otherwise return <code>null</code>.9284*9285* @return the component9286*/9287public AccessibleComponent getAccessibleComponent() {9288return this;9289}929092919292// AccessibleComponent methods9293//9294/**9295* Gets the background color of this object.9296*9297* @return the background color, if supported, of the object;9298* otherwise, <code>null</code>9299*/9300public Color getBackground() {9301return Component.this.getBackground();9302}93039304/**9305* Sets the background color of this object.9306* (For transparency, see <code>isOpaque</code>.)9307*9308* @param c the new <code>Color</code> for the background9309* @see Component#isOpaque9310*/9311public void setBackground(Color c) {9312Component.this.setBackground(c);9313}93149315/**9316* Gets the foreground color of this object.9317*9318* @return the foreground color, if supported, of the object;9319* otherwise, <code>null</code>9320*/9321public Color getForeground() {9322return Component.this.getForeground();9323}93249325/**9326* Sets the foreground color of this object.9327*9328* @param c the new <code>Color</code> for the foreground9329*/9330public void setForeground(Color c) {9331Component.this.setForeground(c);9332}93339334/**9335* Gets the <code>Cursor</code> of this object.9336*9337* @return the <code>Cursor</code>, if supported,9338* of the object; otherwise, <code>null</code>9339*/9340public Cursor getCursor() {9341return Component.this.getCursor();9342}93439344/**9345* Sets the <code>Cursor</code> of this object.9346* <p>9347* The method may have no visual effect if the Java platform9348* implementation and/or the native system do not support9349* changing the mouse cursor shape.9350* @param cursor the new <code>Cursor</code> for the object9351*/9352public void setCursor(Cursor cursor) {9353Component.this.setCursor(cursor);9354}93559356/**9357* Gets the <code>Font</code> of this object.9358*9359* @return the <code>Font</code>, if supported,9360* for the object; otherwise, <code>null</code>9361*/9362public Font getFont() {9363return Component.this.getFont();9364}93659366/**9367* Sets the <code>Font</code> of this object.9368*9369* @param f the new <code>Font</code> for the object9370*/9371public void setFont(Font f) {9372Component.this.setFont(f);9373}93749375/**9376* Gets the <code>FontMetrics</code> of this object.9377*9378* @param f the <code>Font</code>9379* @return the <code>FontMetrics</code>, if supported,9380* the object; otherwise, <code>null</code>9381* @see #getFont9382*/9383public FontMetrics getFontMetrics(Font f) {9384if (f == null) {9385return null;9386} else {9387return Component.this.getFontMetrics(f);9388}9389}93909391/**9392* Determines if the object is enabled.9393*9394* @return true if object is enabled; otherwise, false9395*/9396public boolean isEnabled() {9397return Component.this.isEnabled();9398}93999400/**9401* Sets the enabled state of the object.9402*9403* @param b if true, enables this object; otherwise, disables it9404*/9405public void setEnabled(boolean b) {9406boolean old = Component.this.isEnabled();9407Component.this.setEnabled(b);9408if (b != old) {9409if (accessibleContext != null) {9410if (b) {9411accessibleContext.firePropertyChange(9412AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9413null, AccessibleState.ENABLED);9414} else {9415accessibleContext.firePropertyChange(9416AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9417AccessibleState.ENABLED, null);9418}9419}9420}9421}94229423/**9424* Determines if the object is visible. Note: this means that the9425* object intends to be visible; however, it may not in fact be9426* showing on the screen because one of the objects that this object9427* is contained by is not visible. To determine if an object is9428* showing on the screen, use <code>isShowing</code>.9429*9430* @return true if object is visible; otherwise, false9431*/9432public boolean isVisible() {9433return Component.this.isVisible();9434}94359436/**9437* Sets the visible state of the object.9438*9439* @param b if true, shows this object; otherwise, hides it9440*/9441public void setVisible(boolean b) {9442boolean old = Component.this.isVisible();9443Component.this.setVisible(b);9444if (b != old) {9445if (accessibleContext != null) {9446if (b) {9447accessibleContext.firePropertyChange(9448AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9449null, AccessibleState.VISIBLE);9450} else {9451accessibleContext.firePropertyChange(9452AccessibleContext.ACCESSIBLE_STATE_PROPERTY,9453AccessibleState.VISIBLE, null);9454}9455}9456}9457}94589459/**9460* Determines if the object is showing. This is determined by checking9461* the visibility of the object and ancestors of the object. Note:9462* this will return true even if the object is obscured by another9463* (for example, it happens to be underneath a menu that was pulled9464* down).9465*9466* @return true if object is showing; otherwise, false9467*/9468public boolean isShowing() {9469return Component.this.isShowing();9470}94719472/**9473* Checks whether the specified point is within this object's bounds,9474* where the point's x and y coordinates are defined to be relative to9475* the coordinate system of the object.9476*9477* @param p the <code>Point</code> relative to the9478* coordinate system of the object9479* @return true if object contains <code>Point</code>; otherwise false9480*/9481public boolean contains(Point p) {9482return Component.this.contains(p);9483}94849485/**9486* Returns the location of the object on the screen.9487*9488* @return location of object on screen -- can be9489* <code>null</code> if this object is not on the screen9490*/9491public Point getLocationOnScreen() {9492synchronized (Component.this.getTreeLock()) {9493if (Component.this.isShowing()) {9494return Component.this.getLocationOnScreen();9495} else {9496return null;9497}9498}9499}95009501/**9502* Gets the location of the object relative to the parent in the form9503* of a point specifying the object's top-left corner in the screen's9504* coordinate space.9505*9506* @return an instance of Point representing the top-left corner of9507* the object's bounds in the coordinate space of the screen;9508* <code>null</code> if this object or its parent are not on the screen9509*/9510public Point getLocation() {9511return Component.this.getLocation();9512}95139514/**9515* Sets the location of the object relative to the parent.9516* @param p the coordinates of the object9517*/9518public void setLocation(Point p) {9519Component.this.setLocation(p);9520}95219522/**9523* Gets the bounds of this object in the form of a Rectangle object.9524* The bounds specify this object's width, height, and location9525* relative to its parent.9526*9527* @return a rectangle indicating this component's bounds;9528* <code>null</code> if this object is not on the screen9529*/9530public Rectangle getBounds() {9531return Component.this.getBounds();9532}95339534/**9535* Sets the bounds of this object in the form of a9536* <code>Rectangle</code> object.9537* The bounds specify this object's width, height, and location9538* relative to its parent.9539*9540* @param r a rectangle indicating this component's bounds9541*/9542public void setBounds(Rectangle r) {9543Component.this.setBounds(r);9544}95459546/**9547* Returns the size of this object in the form of a9548* <code>Dimension</code> object. The height field of the9549* <code>Dimension</code> object contains this objects's9550* height, and the width field of the <code>Dimension</code>9551* object contains this object's width.9552*9553* @return a <code>Dimension</code> object that indicates9554* the size of this component; <code>null</code> if9555* this object is not on the screen9556*/9557public Dimension getSize() {9558return Component.this.getSize();9559}95609561/**9562* Resizes this object so that it has width and height.9563*9564* @param d - the dimension specifying the new size of the object9565*/9566public void setSize(Dimension d) {9567Component.this.setSize(d);9568}95699570/**9571* Returns the <code>Accessible</code> child,9572* if one exists, contained at the local9573* coordinate <code>Point</code>. Otherwise returns9574* <code>null</code>.9575*9576* @param p the point defining the top-left corner of9577* the <code>Accessible</code>, given in the9578* coordinate space of the object's parent9579* @return the <code>Accessible</code>, if it exists,9580* at the specified location; else <code>null</code>9581*/9582public Accessible getAccessibleAt(Point p) {9583return null; // Components don't have children9584}95859586/**9587* Returns whether this object can accept focus or not.9588*9589* @return true if object can accept focus; otherwise false9590*/9591public boolean isFocusTraversable() {9592return Component.this.isFocusTraversable();9593}95949595/**9596* Requests focus for this object.9597*/9598public void requestFocus() {9599Component.this.requestFocus();9600}96019602/**9603* Adds the specified focus listener to receive focus events from this9604* component.9605*9606* @param l the focus listener9607*/9608public void addFocusListener(FocusListener l) {9609Component.this.addFocusListener(l);9610}96119612/**9613* Removes the specified focus listener so it no longer receives focus9614* events from this component.9615*9616* @param l the focus listener9617*/9618public void removeFocusListener(FocusListener l) {9619Component.this.removeFocusListener(l);9620}96219622} // inner class AccessibleAWTComponent962396249625/**9626* Gets the index of this object in its accessible parent.9627* If this object does not have an accessible parent, returns9628* -1.9629*9630* @return the index of this object in its accessible parent9631*/9632int getAccessibleIndexInParent() {9633synchronized (getTreeLock()) {9634int index = -1;9635Container parent = this.getParent();9636if (parent != null && parent instanceof Accessible) {9637Component ca[] = parent.getComponents();9638for (int i = 0; i < ca.length; i++) {9639if (ca[i] instanceof Accessible) {9640index++;9641}9642if (this.equals(ca[i])) {9643return index;9644}9645}9646}9647return -1;9648}9649}96509651/**9652* Gets the current state set of this object.9653*9654* @return an instance of <code>AccessibleStateSet</code>9655* containing the current state set of the object9656* @see AccessibleState9657*/9658AccessibleStateSet getAccessibleStateSet() {9659synchronized (getTreeLock()) {9660AccessibleStateSet states = new AccessibleStateSet();9661if (this.isEnabled()) {9662states.add(AccessibleState.ENABLED);9663}9664if (this.isFocusTraversable()) {9665states.add(AccessibleState.FOCUSABLE);9666}9667if (this.isVisible()) {9668states.add(AccessibleState.VISIBLE);9669}9670if (this.isShowing()) {9671states.add(AccessibleState.SHOWING);9672}9673if (this.isFocusOwner()) {9674states.add(AccessibleState.FOCUSED);9675}9676if (this instanceof Accessible) {9677AccessibleContext ac = ((Accessible) this).getAccessibleContext();9678if (ac != null) {9679Accessible ap = ac.getAccessibleParent();9680if (ap != null) {9681AccessibleContext pac = ap.getAccessibleContext();9682if (pac != null) {9683AccessibleSelection as = pac.getAccessibleSelection();9684if (as != null) {9685states.add(AccessibleState.SELECTABLE);9686int i = ac.getAccessibleIndexInParent();9687if (i >= 0) {9688if (as.isAccessibleChildSelected(i)) {9689states.add(AccessibleState.SELECTED);9690}9691}9692}9693}9694}9695}9696}9697if (Component.isInstanceOf(this, "javax.swing.JComponent")) {9698if (((javax.swing.JComponent) this).isOpaque()) {9699states.add(AccessibleState.OPAQUE);9700}9701}9702return states;9703}9704}97059706/**9707* Checks that the given object is instance of the given class.9708* @param obj Object to be checked9709* @param className The name of the class. Must be fully-qualified class name.9710* @return true, if this object is instanceof given class,9711* false, otherwise, or if obj or className is null9712*/9713static boolean isInstanceOf(Object obj, String className) {9714if (obj == null) return false;9715if (className == null) return false;97169717Class<?> cls = obj.getClass();9718while (cls != null) {9719if (cls.getName().equals(className)) {9720return true;9721}9722cls = cls.getSuperclass();9723}9724return false;9725}972697279728// ************************** MIXING CODE *******************************97299730/**9731* Check whether we can trust the current bounds of the component.9732* The return value of false indicates that the container of the9733* component is invalid, and therefore needs to be layed out, which would9734* probably mean changing the bounds of its children.9735* Null-layout of the container or absence of the container mean9736* the bounds of the component are final and can be trusted.9737*/9738final boolean areBoundsValid() {9739Container cont = getContainer();9740return cont == null || cont.isValid() || cont.getLayout() == null;9741}97429743/**9744* Applies the shape to the component9745* @param shape Shape to be applied to the component9746*/9747void applyCompoundShape(Region shape) {9748checkTreeLock();97499750if (!areBoundsValid()) {9751if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9752mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());9753}9754return;9755}97569757if (!isLightweight()) {9758ComponentPeer peer = getPeer();9759if (peer != null) {9760// The Region class has some optimizations. That's why9761// we should manually check whether it's empty and9762// substitute the object ourselves. Otherwise we end up9763// with some incorrect Region object with loX being9764// greater than the hiX for instance.9765if (shape.isEmpty()) {9766shape = Region.EMPTY_REGION;9767}976897699770// Note: the shape is not really copied/cloned. We create9771// the Region object ourselves, so there's no any possibility9772// to modify the object outside of the mixing code.9773// Nullifying compoundShape means that the component has normal shape9774// (or has no shape at all).9775if (shape.equals(getNormalShape())) {9776if (this.compoundShape == null) {9777return;9778}9779this.compoundShape = null;9780peer.applyShape(null);9781} else {9782if (shape.equals(getAppliedShape())) {9783return;9784}9785this.compoundShape = shape;9786Point compAbsolute = getLocationOnWindow();9787if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) {9788mixingLog.fine("this = " + this +9789"; compAbsolute=" + compAbsolute + "; shape=" + shape);9790}9791peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y));9792}9793}9794}9795}97969797/**9798* Returns the shape previously set with applyCompoundShape().9799* If the component is LW or no shape was applied yet,9800* the method returns the normal shape.9801*/9802private Region getAppliedShape() {9803checkTreeLock();9804//XXX: if we allow LW components to have a shape, this must be changed9805return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape;9806}98079808Point getLocationOnWindow() {9809checkTreeLock();9810Point curLocation = getLocation();98119812for (Container parent = getContainer();9813parent != null && !(parent instanceof Window);9814parent = parent.getContainer())9815{9816curLocation.x += parent.getX();9817curLocation.y += parent.getY();9818}98199820return curLocation;9821}98229823/**9824* Returns the full shape of the component located in window coordinates9825*/9826final Region getNormalShape() {9827checkTreeLock();9828//XXX: we may take into account a user-specified shape for this component9829Point compAbsolute = getLocationOnWindow();9830return9831Region.getInstanceXYWH(9832compAbsolute.x,9833compAbsolute.y,9834getWidth(),9835getHeight()9836);9837}98389839/**9840* Returns the "opaque shape" of the component.9841*9842* The opaque shape of a lightweight components is the actual shape that9843* needs to be cut off of the heavyweight components in order to mix this9844* lightweight component correctly with them.9845*9846* The method is overriden in the java.awt.Container to handle non-opaque9847* containers containing opaque children.9848*9849* See 6637655 for details.9850*/9851Region getOpaqueShape() {9852checkTreeLock();9853if (mixingCutoutRegion != null) {9854return mixingCutoutRegion;9855} else {9856return getNormalShape();9857}9858}98599860final int getSiblingIndexAbove() {9861checkTreeLock();9862Container parent = getContainer();9863if (parent == null) {9864return -1;9865}98669867int nextAbove = parent.getComponentZOrder(this) - 1;98689869return nextAbove < 0 ? -1 : nextAbove;9870}98719872final ComponentPeer getHWPeerAboveMe() {9873checkTreeLock();98749875Container cont = getContainer();9876int indexAbove = getSiblingIndexAbove();98779878while (cont != null) {9879for (int i = indexAbove; i > -1; i--) {9880Component comp = cont.getComponent(i);9881if (comp != null && comp.isDisplayable() && !comp.isLightweight()) {9882return comp.getPeer();9883}9884}9885// traversing the hierarchy up to the closest HW container;9886// further traversing may return a component that is not actually9887// a native sibling of this component and this kind of z-order9888// request may not be allowed by the underlying system (6852051).9889if (!cont.isLightweight()) {9890break;9891}98929893indexAbove = cont.getSiblingIndexAbove();9894cont = cont.getContainer();9895}98969897return null;9898}98999900final int getSiblingIndexBelow() {9901checkTreeLock();9902Container parent = getContainer();9903if (parent == null) {9904return -1;9905}99069907int nextBelow = parent.getComponentZOrder(this) + 1;99089909return nextBelow >= parent.getComponentCount() ? -1 : nextBelow;9910}99119912final boolean isNonOpaqueForMixing() {9913return mixingCutoutRegion != null &&9914mixingCutoutRegion.isEmpty();9915}99169917private Region calculateCurrentShape() {9918checkTreeLock();9919Region s = getNormalShape();99209921if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9922mixingLog.fine("this = " + this + "; normalShape=" + s);9923}99249925if (getContainer() != null) {9926Component comp = this;9927Container cont = comp.getContainer();99289929while (cont != null) {9930for (int index = comp.getSiblingIndexAbove(); index != -1; --index) {9931/* It is assumed that:9932*9933* getComponent(getContainer().getComponentZOrder(comp)) == comp9934*9935* The assumption has been made according to the current9936* implementation of the Container class.9937*/9938Component c = cont.getComponent(index);9939if (c.isLightweight() && c.isShowing()) {9940s = s.getDifference(c.getOpaqueShape());9941}9942}99439944if (cont.isLightweight()) {9945s = s.getIntersection(cont.getNormalShape());9946} else {9947break;9948}99499950comp = cont;9951cont = cont.getContainer();9952}9953}99549955if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9956mixingLog.fine("currentShape=" + s);9957}99589959return s;9960}99619962void applyCurrentShape() {9963checkTreeLock();9964if (!areBoundsValid()) {9965if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9966mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());9967}9968return; // Because applyCompoundShape() ignores such components anyway9969}9970if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9971mixingLog.fine("this = " + this);9972}9973applyCompoundShape(calculateCurrentShape());9974}99759976final void subtractAndApplyShape(Region s) {9977checkTreeLock();99789979if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {9980mixingLog.fine("this = " + this + "; s=" + s);9981}99829983applyCompoundShape(getAppliedShape().getDifference(s));9984}99859986private final void applyCurrentShapeBelowMe() {9987checkTreeLock();9988Container parent = getContainer();9989if (parent != null && parent.isShowing()) {9990// First, reapply shapes of my siblings9991parent.recursiveApplyCurrentShape(getSiblingIndexBelow());99929993// Second, if my container is non-opaque, reapply shapes of siblings of my container9994Container parent2 = parent.getContainer();9995while (!parent.isOpaque() && parent2 != null) {9996parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow());99979998parent = parent2;9999parent2 = parent.getContainer();10000}10001}10002}1000310004final void subtractAndApplyShapeBelowMe() {10005checkTreeLock();10006Container parent = getContainer();10007if (parent != null && isShowing()) {10008Region opaqueShape = getOpaqueShape();1000910010// First, cut my siblings10011parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow());1001210013// Second, if my container is non-opaque, cut siblings of my container10014Container parent2 = parent.getContainer();10015while (!parent.isOpaque() && parent2 != null) {10016parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow());1001710018parent = parent2;10019parent2 = parent.getContainer();10020}10021}10022}1002310024void mixOnShowing() {10025synchronized (getTreeLock()) {10026if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10027mixingLog.fine("this = " + this);10028}10029if (!isMixingNeeded()) {10030return;10031}10032if (isLightweight()) {10033subtractAndApplyShapeBelowMe();10034} else {10035applyCurrentShape();10036}10037}10038}1003910040void mixOnHiding(boolean isLightweight) {10041// We cannot be sure that the peer exists at this point, so we need the argument10042// to find out whether the hiding component is (well, actually was) a LW or a HW.10043synchronized (getTreeLock()) {10044if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10045mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight);10046}10047if (!isMixingNeeded()) {10048return;10049}10050if (isLightweight) {10051applyCurrentShapeBelowMe();10052}10053}10054}1005510056void mixOnReshaping() {10057synchronized (getTreeLock()) {10058if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10059mixingLog.fine("this = " + this);10060}10061if (!isMixingNeeded()) {10062return;10063}10064if (isLightweight()) {10065applyCurrentShapeBelowMe();10066} else {10067applyCurrentShape();10068}10069}10070}1007110072void mixOnZOrderChanging(int oldZorder, int newZorder) {10073synchronized (getTreeLock()) {10074boolean becameHigher = newZorder < oldZorder;10075Container parent = getContainer();1007610077if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10078mixingLog.fine("this = " + this +10079"; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent);10080}10081if (!isMixingNeeded()) {10082return;10083}10084if (isLightweight()) {10085if (becameHigher) {10086if (parent != null && isShowing()) {10087parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder);10088}10089} else {10090if (parent != null) {10091parent.recursiveApplyCurrentShape(oldZorder, newZorder);10092}10093}10094} else {10095if (becameHigher) {10096applyCurrentShape();10097} else {10098if (parent != null) {10099Region shape = getAppliedShape();1010010101for (int index = oldZorder; index < newZorder; index++) {10102Component c = parent.getComponent(index);10103if (c.isLightweight() && c.isShowing()) {10104shape = shape.getDifference(c.getOpaqueShape());10105}10106}10107applyCompoundShape(shape);10108}10109}10110}10111}10112}1011310114void mixOnValidating() {10115// This method gets overriden in the Container. Obviously, a plain10116// non-container components don't need to handle validation.10117}1011810119final boolean isMixingNeeded() {10120if (SunToolkit.getSunAwtDisableMixing()) {10121if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) {10122mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing");10123}10124return false;10125}10126if (!areBoundsValid()) {10127if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10128mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid());10129}10130return false;10131}10132Window window = getContainingWindow();10133if (window != null) {10134if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) {10135if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10136mixingLog.fine("containing window = " + window +10137"; has h/w descendants = " + window.hasHeavyweightDescendants() +10138"; has l/w descendants = " + window.hasLightweightDescendants() +10139"; disposing = " + window.isDisposing());10140}10141return false;10142}10143} else {10144if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) {10145mixingLog.fine("this = " + this + "; containing window is null");10146}10147return false;10148}10149return true;10150}1015110152// ****************** END OF MIXING CODE ********************************1015310154// Note that the method is overriden in the Window class,10155// a window doesn't need to be updated in the Z-order.10156void updateZOrder() {10157peer.setZOrder(getHWPeerAboveMe());10158}1015910160}101611016210163