72 import sun.awt.EmbeddedFrame;
73 import sun.awt.dnd.SunDropTargetEvent;
74 import sun.awt.im.CompositionArea;
75 import sun.font.FontManager;
76 import sun.font.FontManagerFactory;
77 import sun.font.SunFontManager;
78 import sun.java2d.SunGraphics2D;
79 import sun.java2d.pipe.Region;
80 import sun.awt.image.VSyncedBSManager;
81 import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
82 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
83 import sun.awt.RequestFocusController;
84 import sun.java2d.SunGraphicsEnvironment;
85 import sun.util.logging.PlatformLogger;
86
87 /**
88 * A <em>component</em> is an object having a graphical representation
89 * that can be displayed on the screen and that can interact with the
90 * user. Examples of components are the buttons, checkboxes, and scrollbars
91 * of a typical graphical user interface. <p>
92 * The <code>Component</code> class is the abstract superclass of
93 * the nonmenu-related Abstract Window Toolkit components. Class
94 * <code>Component</code> can also be extended directly to create a
95 * lightweight component. A lightweight component is a component that is
96 * not associated with a native window. On the contrary, a heavyweight
97 * component is associated with a native window. The {@link #isLightweight()}
98 * method may be used to distinguish between the two kinds of the components.
99 * <p>
100 * Lightweight and heavyweight components may be mixed in a single component
101 * hierarchy. However, for correct operating of such a mixed hierarchy of
102 * components, the whole hierarchy must be valid. When the hierarchy gets
103 * invalidated, like after changing the bounds of components, or
104 * adding/removing components to/from containers, the whole hierarchy must be
105 * validated afterwards by means of the {@link Container#validate()} method
106 * invoked on the top-most invalid container of the hierarchy.
107 *
108 * <h3>Serialization</h3>
109 * It is important to note that only AWT listeners which conform
110 * to the <code>Serializable</code> protocol will be saved when
111 * the object is stored. If an AWT object has listeners that
112 * aren't marked serializable, they will be dropped at
113 * <code>writeObject</code> time. Developers will need, as always,
114 * to consider the implications of making an object serializable.
115 * One situation to watch out for is this:
116 * <pre>
117 * import java.awt.*;
118 * import java.awt.event.*;
119 * import java.io.Serializable;
120 *
121 * class MyApp implements ActionListener, Serializable
122 * {
123 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
124 * Button aButton = new Button();
125 *
126 * MyApp()
127 * {
128 * // Oops, now aButton has a listener with a reference
129 * // to bigOne!
130 * aButton.addActionListener(this);
131 * }
132 *
133 * public void actionPerformed(ActionEvent e)
134 * {
135 * System.out.println("Hello There");
136 * }
137 * }
138 * </pre>
139 * In this example, serializing <code>aButton</code> by itself
140 * will cause <code>MyApp</code> and everything it refers to
141 * to be serialized as well. The problem is that the listener
142 * is serializable by coincidence, not by design. To separate
143 * the decisions about <code>MyApp</code> and the
144 * <code>ActionListener</code> being serializable one can use a
145 * nested class, as in the following example:
146 * <pre>
147 * import java.awt.*;
148 * import java.awt.event.*;
149 * import java.io.Serializable;
150 *
151 * class MyApp implements java.io.Serializable
152 * {
153 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
154 * Button aButton = new Button();
155 *
156 * static class MyActionListener implements ActionListener
157 * {
158 * public void actionPerformed(ActionEvent e)
159 * {
160 * System.out.println("Hello There");
161 * }
162 * }
163 *
164 * MyApp()
177 * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
178 * How to Use the Focus Subsystem</a>,
179 * a section in <em>The Java Tutorial</em>, and the
180 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
181 * for more information.
182 *
183 * @author Arthur van Hoff
184 * @author Sami Shaio
185 */
186 public abstract class Component implements ImageObserver, MenuContainer,
187 Serializable
188 {
189
190 private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");
191 private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");
192 private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");
193 private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");
194
195 /**
196 * The peer of the component. The peer implements the component's
197 * behavior. The peer is set when the <code>Component</code> is
198 * added to a container that also is a peer.
199 * @see #addNotify
200 * @see #removeNotify
201 */
202 transient volatile ComponentPeer peer;
203
204 /**
205 * The parent of the object. It may be <code>null</code>
206 * for top-level components.
207 * @see #getParent
208 */
209 transient Container parent;
210
211 /**
212 * The <code>AppContext</code> of the component. Applets/Plugin may
213 * change the AppContext.
214 */
215 transient AppContext appContext;
216
217 /**
218 * The x position of the component in the parent's coordinate system.
219 *
220 * @serial
221 * @see #getLocation
222 */
223 int x;
224
225 /**
226 * The y position of the component in the parent's coordinate system.
227 *
228 * @serial
229 * @see #getLocation
230 */
231 int y;
232
233 /**
234 * The width of the component.
235 *
236 * @serial
237 * @see #getSize
238 */
239 int width;
240
241 /**
242 * The height of the component.
243 *
244 * @serial
245 * @see #getSize
246 */
247 int height;
248
249 /**
250 * The foreground color for this component.
251 * <code>foreground</code> can be <code>null</code>.
252 *
253 * @serial
254 * @see #getForeground
255 * @see #setForeground
256 */
257 Color foreground;
258
259 /**
260 * The background color for this component.
261 * <code>background</code> can be <code>null</code>.
262 *
263 * @serial
264 * @see #getBackground
265 * @see #setBackground
266 */
267 Color background;
268
269 /**
270 * The font used by this component.
271 * The <code>font</code> can be <code>null</code>.
272 *
273 * @serial
274 * @see #getFont
275 * @see #setFont
276 */
277 volatile Font font;
278
279 /**
280 * The font which the peer is currently using.
281 * (<code>null</code> if no peer exists.)
282 */
283 Font peerFont;
284
285 /**
286 * The cursor displayed when pointer is over this component.
287 * This value can be <code>null</code>.
288 *
289 * @serial
290 * @see #getCursor
291 * @see #setCursor
292 */
293 Cursor cursor;
294
295 /**
296 * The locale for the component.
297 *
298 * @serial
299 * @see #getLocale
300 * @see #setLocale
301 */
302 Locale locale;
303
304 /**
305 * A reference to a <code>GraphicsConfiguration</code> object
306 * used to describe the characteristics of a graphics
307 * destination.
308 * This value can be <code>null</code>.
309 *
310 * @since 1.3
311 * @serial
312 * @see GraphicsConfiguration
313 * @see #getGraphicsConfiguration
314 */
315 private transient GraphicsConfiguration graphicsConfig = null;
316
317 /**
318 * A reference to a <code>BufferStrategy</code> object
319 * used to manipulate the buffers on this component.
320 *
321 * @since 1.4
322 * @see java.awt.image.BufferStrategy
323 * @see #getBufferStrategy()
324 */
325 transient BufferStrategy bufferStrategy = null;
326
327 /**
328 * True when the object should ignore all repaint events.
329 *
330 * @since 1.4
331 * @serial
332 * @see #setIgnoreRepaint
333 * @see #getIgnoreRepaint
334 */
335 boolean ignoreRepaint = false;
336
337 /**
338 * True when the object is visible. An object that is not
350 *
351 * @serial
352 * @see #isEnabled
353 * @see #setEnabled
354 */
355 boolean enabled = true;
356
357 /**
358 * True when the object is valid. An invalid object needs to
359 * be laid out. This flag is set to false when the object
360 * size is changed.
361 *
362 * @serial
363 * @see #isValid
364 * @see #validate
365 * @see #invalidate
366 */
367 private volatile boolean valid = false;
368
369 /**
370 * The <code>DropTarget</code> associated with this component.
371 *
372 * @since 1.2
373 * @serial
374 * @see #setDropTarget
375 * @see #getDropTarget
376 */
377 DropTarget dropTarget;
378
379 /**
380 * @serial
381 * @see #add
382 */
383 Vector<PopupMenu> popups;
384
385 /**
386 * A component's name.
387 * This field can be <code>null</code>.
388 *
389 * @serial
390 * @see #getName
391 * @see #setName(String)
392 */
393 private String name;
394
395 /**
396 * A bool to determine whether the name has
397 * been set explicitly. <code>nameExplicitlySet</code> will
398 * be false if the name has not been set and
399 * true if it has.
400 *
401 * @serial
402 * @see #getName
403 * @see #setName(String)
404 */
405 private boolean nameExplicitlySet = false;
406
407 /**
408 * Indicates whether this Component can be focused.
409 *
410 * @serial
411 * @see #setFocusable
412 * @see #isFocusable
413 * @since 1.4
414 */
415 private boolean focusable = true;
416
417 private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
506 * Maximum size
507 *
508 * @serial
509 */
510 Dimension maxSize;
511
512 /**
513 * Whether or not setMaximumSize has been invoked with a non-null value.
514 */
515 boolean maxSizeSet;
516
517 /**
518 * The orientation for this component.
519 * @see #getComponentOrientation
520 * @see #setComponentOrientation
521 */
522 transient ComponentOrientation componentOrientation
523 = ComponentOrientation.UNKNOWN;
524
525 /**
526 * <code>newEventsOnly</code> will be true if the event is
527 * one of the event types enabled for the component.
528 * It will then allow for normal processing to
529 * continue. If it is false the event is passed
530 * to the component's parent and up the ancestor
531 * tree until the event has been consumed.
532 *
533 * @serial
534 * @see #dispatchEvent
535 */
536 boolean newEventsOnly = false;
537 transient ComponentListener componentListener;
538 transient FocusListener focusListener;
539 transient HierarchyListener hierarchyListener;
540 transient HierarchyBoundsListener hierarchyBoundsListener;
541 transient KeyListener keyListener;
542 transient MouseListener mouseListener;
543 transient MouseMotionListener mouseMotionListener;
544 transient MouseWheelListener mouseWheelListener;
545 transient InputMethodListener inputMethodListener;
546
548 static final String actionListenerK = "actionL";
549 static final String adjustmentListenerK = "adjustmentL";
550 static final String componentListenerK = "componentL";
551 static final String containerListenerK = "containerL";
552 static final String focusListenerK = "focusL";
553 static final String itemListenerK = "itemL";
554 static final String keyListenerK = "keyL";
555 static final String mouseListenerK = "mouseL";
556 static final String mouseMotionListenerK = "mouseMotionL";
557 static final String mouseWheelListenerK = "mouseWheelL";
558 static final String textListenerK = "textL";
559 static final String ownedWindowK = "ownedL";
560 static final String windowListenerK = "windowL";
561 static final String inputMethodListenerK = "inputMethodL";
562 static final String hierarchyListenerK = "hierarchyL";
563 static final String hierarchyBoundsListenerK = "hierarchyBoundsL";
564 static final String windowStateListenerK = "windowStateL";
565 static final String windowFocusListenerK = "windowFocusL";
566
567 /**
568 * The <code>eventMask</code> is ONLY set by subclasses via
569 * <code>enableEvents</code>.
570 * The mask should NOT be set when listeners are registered
571 * so that we can distinguish the difference between when
572 * listeners request events and subclasses request them.
573 * One bit is used to indicate whether input methods are
574 * enabled; this bit is set by <code>enableInputMethods</code> and is
575 * on by default.
576 *
577 * @serial
578 * @see #enableInputMethods
579 * @see AWTEvent
580 */
581 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
582
583 /**
584 * Static properties for incremental drawing.
585 * @see #imageUpdate
586 */
587 static boolean isInc;
588 static int incRate;
589 static {
590 /* ensure that the necessary native libraries are loaded */
591 Toolkit.loadLibraries();
592 /* initialize JNI field and method ids */
593 if (!GraphicsEnvironment.isHeadless()) {
594 initIDs();
595 }
596
597 String s = java.security.AccessController.doPrivileged(
598 new GetPropertyAction("awt.image.incrementaldraw"));
599 isInc = (s == null || s.equals("true"));
600
601 s = java.security.AccessController.doPrivileged(
602 new GetPropertyAction("awt.image.redrawrate"));
603 incRate = (s != null) ? Integer.parseInt(s) : 100;
604 }
605
606 /**
607 * Ease-of-use constant for <code>getAlignmentY()</code>.
608 * Specifies an alignment to the top of the component.
609 * @see #getAlignmentY
610 */
611 public static final float TOP_ALIGNMENT = 0.0f;
612
613 /**
614 * Ease-of-use constant for <code>getAlignmentY</code> and
615 * <code>getAlignmentX</code>. Specifies an alignment to
616 * the center of the component
617 * @see #getAlignmentX
618 * @see #getAlignmentY
619 */
620 public static final float CENTER_ALIGNMENT = 0.5f;
621
622 /**
623 * Ease-of-use constant for <code>getAlignmentY</code>.
624 * Specifies an alignment to the bottom of the component.
625 * @see #getAlignmentY
626 */
627 public static final float BOTTOM_ALIGNMENT = 1.0f;
628
629 /**
630 * Ease-of-use constant for <code>getAlignmentX</code>.
631 * Specifies an alignment to the left side of the component.
632 * @see #getAlignmentX
633 */
634 public static final float LEFT_ALIGNMENT = 0.0f;
635
636 /**
637 * Ease-of-use constant for <code>getAlignmentX</code>.
638 * Specifies an alignment to the right side of the component.
639 * @see #getAlignmentX
640 */
641 public static final float RIGHT_ALIGNMENT = 1.0f;
642
643 /*
644 * JDK 1.1 serialVersionUID
645 */
646 private static final long serialVersionUID = -7644114512714619750L;
647
648 /**
649 * If any <code>PropertyChangeListeners</code> have been registered,
650 * the <code>changeSupport</code> field describes them.
651 *
652 * @serial
653 * @since 1.2
654 * @see #addPropertyChangeListener
655 * @see #removePropertyChangeListener
656 * @see #firePropertyChange
657 */
658 private PropertyChangeSupport changeSupport;
659
660 /*
661 * In some cases using "this" as an object to synchronize by
662 * can lead to a deadlock if client code also uses synchronization
663 * by a component object. For every such situation revealed we should
664 * consider possibility of replacing "this" with the package private
665 * objectLock object introduced below. So far there are 3 issues known:
666 * - CR 6708322 (the getName/setName methods);
667 * - CR 6608764 (the PropertyChangeListener machinery);
668 * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods).
669 *
670 * Note: this field is considered final, though readObject() prohibits
688 boolean isPacked = false;
689
690 /**
691 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
692 * to signal setBounds what's changing. Should be used under TreeLock.
693 * This is only needed due to the inability to change the cross-calling
694 * order of public and deprecated methods.
695 */
696 private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
697
698 /**
699 * Enumeration of the common ways the baseline of a component can
700 * change as the size changes. The baseline resize behavior is
701 * primarily for layout managers that need to know how the
702 * position of the baseline changes as the component size changes.
703 * In general the baseline resize behavior will be valid for sizes
704 * greater than or equal to the minimum size (the actual minimum
705 * size; not a developer specified minimum size). For sizes
706 * smaller than the minimum size the baseline may change in a way
707 * other than the baseline resize behavior indicates. Similarly,
708 * as the size approaches <code>Integer.MAX_VALUE</code> and/or
709 * <code>Short.MAX_VALUE</code> the baseline may change in a way
710 * other than the baseline resize behavior indicates.
711 *
712 * @see #getBaselineResizeBehavior
713 * @see #getBaseline(int,int)
714 * @since 1.6
715 */
716 public enum BaselineResizeBehavior {
717 /**
718 * Indicates the baseline remains fixed relative to the
719 * y-origin. That is, <code>getBaseline</code> returns
720 * the same value regardless of the height or width. For example, a
721 * <code>JLabel</code> containing non-empty text with a
722 * vertical alignment of <code>TOP</code> should have a
723 * baseline type of <code>CONSTANT_ASCENT</code>.
724 */
725 CONSTANT_ASCENT,
726
727 /**
728 * Indicates the baseline remains fixed relative to the height
729 * and does not change as the width is varied. That is, for
730 * any height H the difference between H and
731 * <code>getBaseline(w, H)</code> is the same. For example, a
732 * <code>JLabel</code> containing non-empty text with a
733 * vertical alignment of <code>BOTTOM</code> should have a
734 * baseline type of <code>CONSTANT_DESCENT</code>.
735 */
736 CONSTANT_DESCENT,
737
738 /**
739 * Indicates the baseline remains a fixed distance from
740 * the center of the component. That is, for any height H the
741 * difference between <code>getBaseline(w, H)</code> and
742 * <code>H / 2</code> is the same (plus or minus one depending upon
743 * rounding error).
744 * <p>
745 * Because of possible rounding errors it is recommended
746 * you ask for the baseline with two consecutive heights and use
747 * the return value to determine if you need to pad calculations
748 * by 1. The following shows how to calculate the baseline for
749 * any height:
750 * <pre>
751 * Dimension preferredSize = component.getPreferredSize();
752 * int baseline = getBaseline(preferredSize.width,
753 * preferredSize.height);
754 * int nextBaseline = getBaseline(preferredSize.width,
755 * preferredSize.height + 1);
756 * // Amount to add to height when calculating where baseline
757 * // lands for a particular height:
758 * int padding = 0;
759 * // Where the baseline is relative to the mid point
760 * int baselineOffset = baseline - height / 2;
761 * if (preferredSize.height % 2 == 0 &&
762 * baseline != nextBaseline) {
971 }
972
973 public void revalidateSynchronously(Component comp) {
974 comp.revalidateSynchronously();
975 }
976
977 @Override
978 public void createBufferStrategy(Component comp, int numBuffers,
979 BufferCapabilities caps) throws AWTException {
980 comp.createBufferStrategy(numBuffers, caps);
981 }
982
983 @Override
984 public BufferStrategy getBufferStrategy(Component comp) {
985 return comp.getBufferStrategy();
986 }
987 });
988 }
989
990 /**
991 * Constructs a new component. Class <code>Component</code> can be
992 * extended directly to create a lightweight component that does not
993 * utilize an opaque native window. A lightweight component must be
994 * hosted by a native container somewhere higher up in the component
995 * tree (for example, by a <code>Frame</code> object).
996 */
997 protected Component() {
998 appContext = AppContext.getAppContext();
999 }
1000
1001 @SuppressWarnings({"rawtypes", "unchecked"})
1002 void initializeFocusTraversalKeys() {
1003 focusTraversalKeys = new Set[3];
1004 }
1005
1006 /**
1007 * Constructs a name for this component. Called by <code>getName</code>
1008 * when the name is <code>null</code>.
1009 */
1010 String constructComponentName() {
1011 return null; // For strict compliance with prior platform versions, a Component
1012 // that doesn't set its name should return null from
1013 // getName()
1014 }
1015
1016 /**
1017 * Gets the name of the component.
1018 * @return this component's name
1019 * @see #setName
1020 * @since 1.1
1021 */
1022 public String getName() {
1023 if (name == null && !nameExplicitlySet) {
1024 synchronized(getObjectLock()) {
1025 if (name == null && !nameExplicitlySet)
1026 name = constructComponentName();
1027 }
1028 }
1054 public Container getParent() {
1055 return getParent_NoClientCode();
1056 }
1057
1058 // NOTE: This method may be called by privileged threads.
1059 // This functionality is implemented in a package-private method
1060 // to insure that it cannot be overridden by client subclasses.
1061 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1062 final Container getParent_NoClientCode() {
1063 return parent;
1064 }
1065
1066 // This method is overridden in the Window class to return null,
1067 // because the parent field of the Window object contains
1068 // the owner of the window, not its parent.
1069 Container getContainer() {
1070 return getParent_NoClientCode();
1071 }
1072
1073 /**
1074 * Associate a <code>DropTarget</code> with this component.
1075 * The <code>Component</code> will receive drops only if it
1076 * is enabled.
1077 *
1078 * @see #isEnabled
1079 * @param dt The DropTarget
1080 */
1081
1082 public synchronized void setDropTarget(DropTarget dt) {
1083 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1084 return;
1085
1086 DropTarget old;
1087
1088 if ((old = dropTarget) != null) {
1089 dropTarget.removeNotify();
1090
1091 DropTarget t = dropTarget;
1092
1093 dropTarget = null;
1094
1095 try {
1102 // if we have a new one, and we have a peer, add it!
1103
1104 if ((dropTarget = dt) != null) {
1105 try {
1106 dropTarget.setComponent(this);
1107 dropTarget.addNotify();
1108 } catch (IllegalArgumentException iae) {
1109 if (old != null) {
1110 try {
1111 old.setComponent(this);
1112 dropTarget.addNotify();
1113 } catch (IllegalArgumentException iae1) {
1114 // ignore it!
1115 }
1116 }
1117 }
1118 }
1119 }
1120
1121 /**
1122 * Gets the <code>DropTarget</code> associated with this
1123 * <code>Component</code>.
1124 *
1125 * @return the drop target
1126 */
1127
1128 public synchronized DropTarget getDropTarget() { return dropTarget; }
1129
1130 /**
1131 * Gets the <code>GraphicsConfiguration</code> associated with this
1132 * <code>Component</code>.
1133 * If the <code>Component</code> has not been assigned a specific
1134 * <code>GraphicsConfiguration</code>,
1135 * the <code>GraphicsConfiguration</code> of the
1136 * <code>Component</code> object's top-level container is
1137 * returned.
1138 * If the <code>Component</code> has been created, but not yet added
1139 * to a <code>Container</code>, this method returns <code>null</code>.
1140 *
1141 * @return the <code>GraphicsConfiguration</code> used by this
1142 * <code>Component</code> or <code>null</code>
1143 * @since 1.3
1144 */
1145 public GraphicsConfiguration getGraphicsConfiguration() {
1146 synchronized(getTreeLock()) {
1147 return getGraphicsConfiguration_NoClientCode();
1148 }
1149 }
1150
1151 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1152 return graphicsConfig;
1153 }
1154
1155 void setGraphicsConfiguration(GraphicsConfiguration gc) {
1156 synchronized(getTreeLock()) {
1157 if (updateGraphicsData(gc)) {
1158 removeNotify();
1159 addNotify();
1160 }
1161 }
1162 }
1163
1164 boolean updateGraphicsData(GraphicsConfiguration gc) {
1165 checkTreeLock();
1166
1167 if (graphicsConfig == gc) {
1168 return false;
1169 }
1170
1171 graphicsConfig = gc;
1172
1173 ComponentPeer peer = this.peer;
1174 if (peer != null) {
1175 return peer.updateGraphicsData(gc);
1176 }
1177 return false;
1178 }
1179
1180 /**
1181 * Checks that this component's <code>GraphicsDevice</code>
1182 * <code>idString</code> matches the string argument.
1183 */
1184 void checkGD(String stringID) {
1185 if (graphicsConfig != null) {
1186 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1187 throw new IllegalArgumentException(
1188 "adding a container to a container on a different GraphicsDevice");
1189 }
1190 }
1191 }
1192
1193 /**
1194 * Gets this component's locking object (the object that owns the thread
1195 * synchronization monitor) for AWT component-tree and layout
1196 * operations.
1197 * @return this component's locking object
1198 */
1199 public final Object getTreeLock() {
1200 return LOCK;
1201 }
1202
1228 return parent.getToolkitImpl();
1229 }
1230 return Toolkit.getDefaultToolkit();
1231 }
1232
1233 final ComponentFactory getComponentFactory() {
1234 final Toolkit toolkit = getToolkit();
1235 if (toolkit instanceof ComponentFactory) {
1236 return (ComponentFactory) toolkit;
1237 }
1238 throw new AWTError("UI components are unsupported by: " + toolkit);
1239 }
1240
1241 /**
1242 * Determines whether this component is valid. A component is valid
1243 * when it is correctly sized and positioned within its parent
1244 * container and all its children are also valid.
1245 * In order to account for peers' size requirements, components are invalidated
1246 * before they are first shown on the screen. By the time the parent container
1247 * is fully realized, all its components will be valid.
1248 * @return <code>true</code> if the component is valid, <code>false</code>
1249 * otherwise
1250 * @see #validate
1251 * @see #invalidate
1252 * @since 1.0
1253 */
1254 public boolean isValid() {
1255 return (peer != null) && valid;
1256 }
1257
1258 /**
1259 * Determines whether this component is displayable. A component is
1260 * displayable when it is connected to a native screen resource.
1261 * <p>
1262 * A component is made displayable either when it is added to
1263 * a displayable containment hierarchy or when its containment
1264 * hierarchy is made displayable.
1265 * A containment hierarchy is made displayable when its ancestor
1266 * window is either packed or made visible.
1267 * <p>
1268 * A component is made undisplayable either when it is removed from
1269 * a displayable containment hierarchy or when its containment hierarchy
1270 * is made undisplayable. A containment hierarchy is made
1271 * undisplayable when its ancestor window is disposed.
1272 *
1273 * @return <code>true</code> if the component is displayable,
1274 * <code>false</code> otherwise
1275 * @see Container#add(Component)
1276 * @see Window#pack
1277 * @see Window#show
1278 * @see Container#remove(Component)
1279 * @see Window#dispose
1280 * @since 1.2
1281 */
1282 public boolean isDisplayable() {
1283 return peer != null;
1284 }
1285
1286 /**
1287 * Determines whether this component should be visible when its
1288 * parent is visible. Components are
1289 * initially visible, with the exception of top level components such
1290 * as <code>Frame</code> objects.
1291 * @return <code>true</code> if the component is visible,
1292 * <code>false</code> otherwise
1293 * @see #setVisible
1294 * @since 1.0
1295 */
1296 @Transient
1297 public boolean isVisible() {
1298 return isVisible_NoClientCode();
1299 }
1300 final boolean isVisible_NoClientCode() {
1301 return visible;
1302 }
1303
1304 /**
1305 * Determines whether this component will be displayed on the screen.
1306 * @return <code>true</code> if the component and all of its ancestors
1307 * until a toplevel window or null parent are visible,
1308 * <code>false</code> otherwise
1309 */
1310 boolean isRecursivelyVisible() {
1311 return visible && (parent == null || parent.isRecursivelyVisible());
1312 }
1313
1314 /**
1315 * Determines the bounds of a visible part of the component relative to its
1316 * parent.
1317 *
1318 * @return the visible part of bounds
1319 */
1320 private Rectangle getRecursivelyVisibleBounds() {
1321 final Component container = getContainer();
1322 final Rectangle bounds = getBounds();
1323 if (container == null) {
1324 // we are top level window or haven't a container, return our bounds
1325 return bounds;
1326 }
1327 // translate the container's bounds to our coordinate space
1328 final Rectangle parentsBounds = container.getRecursivelyVisibleBounds();
1353 if (!isShowing()) {
1354 return null;
1355 }
1356 Window win = getContainingWindow();
1357 Toolkit toolkit = Toolkit.getDefaultToolkit();
1358 if (!(toolkit instanceof ComponentFactory)) {
1359 return null;
1360 }
1361 if (!((ComponentFactory) toolkit).getMouseInfoPeer().isWindowUnderMouse(win)) {
1362 return null;
1363 }
1364 final boolean INCLUDE_DISABLED = true;
1365 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1366 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1367 relativeToWindow.y,
1368 INCLUDE_DISABLED);
1369 return inTheSameWindow;
1370 }
1371
1372 /**
1373 * Returns the position of the mouse pointer in this <code>Component</code>'s
1374 * coordinate space if the <code>Component</code> is directly under the mouse
1375 * pointer, otherwise returns <code>null</code>.
1376 * If the <code>Component</code> is not showing on the screen, this method
1377 * returns <code>null</code> even if the mouse pointer is above the area
1378 * where the <code>Component</code> would be displayed.
1379 * If the <code>Component</code> is partially or fully obscured by other
1380 * <code>Component</code>s or native windows, this method returns a non-null
1381 * value only if the mouse pointer is located above the unobscured part of the
1382 * <code>Component</code>.
1383 * <p>
1384 * For <code>Container</code>s it returns a non-null value if the mouse is
1385 * above the <code>Container</code> itself or above any of its descendants.
1386 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1387 * <p>
1388 * Sometimes the exact mouse coordinates are not important, and the only thing
1389 * that matters is whether a specific <code>Component</code> is under the mouse
1390 * pointer. If the return value of this method is <code>null</code>, mouse
1391 * pointer is not directly above the <code>Component</code>.
1392 *
1393 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1394 * @see #isShowing
1395 * @see Container#getMousePosition
1396 * @return mouse coordinates relative to this <code>Component</code>, or null
1397 * @since 1.5
1398 */
1399 public Point getMousePosition() throws HeadlessException {
1400 if (GraphicsEnvironment.isHeadless()) {
1401 throw new HeadlessException();
1402 }
1403
1404 PointerInfo pi = java.security.AccessController.doPrivileged(
1405 new java.security.PrivilegedAction<PointerInfo>() {
1406 public PointerInfo run() {
1407 return MouseInfo.getPointerInfo();
1408 }
1409 }
1410 );
1411
1412 synchronized (getTreeLock()) {
1413 Component inTheSameWindow = findUnderMouseInWindow(pi);
1414 if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1415 return null;
1416 }
1421 /**
1422 * Overridden in Container. Must be called under TreeLock.
1423 */
1424 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1425 return comp == this;
1426 }
1427
1428 /**
1429 * Determines whether this component is showing on screen. This means
1430 * that the component must be visible, and it must be in a container
1431 * that is visible and showing.
1432 * <p>
1433 * <strong>Note:</strong> sometimes there is no way to detect whether the
1434 * {@code Component} is actually visible to the user. This can happen when:
1435 * <ul>
1436 * <li>the component has been added to a visible {@code ScrollPane} but
1437 * the {@code Component} is not currently in the scroll pane's view port.
1438 * <li>the {@code Component} is obscured by another {@code Component} or
1439 * {@code Container}.
1440 * </ul>
1441 * @return <code>true</code> if the component is showing,
1442 * <code>false</code> otherwise
1443 * @see #setVisible
1444 * @since 1.0
1445 */
1446 public boolean isShowing() {
1447 if (visible && (peer != null)) {
1448 Container parent = this.parent;
1449 return (parent == null) || parent.isShowing();
1450 }
1451 return false;
1452 }
1453
1454 /**
1455 * Determines whether this component is enabled. An enabled component
1456 * can respond to user input and generate events. Components are
1457 * enabled initially by default. A component may be enabled or disabled by
1458 * calling its <code>setEnabled</code> method.
1459 * @return <code>true</code> if the component is enabled,
1460 * <code>false</code> otherwise
1461 * @see #setEnabled
1462 * @since 1.0
1463 */
1464 public boolean isEnabled() {
1465 return isEnabledImpl();
1466 }
1467
1468 /*
1469 * This is called by the native code, so client code can't
1470 * be called on the toolkit thread.
1471 */
1472 final boolean isEnabledImpl() {
1473 return enabled;
1474 }
1475
1476 /**
1477 * Enables or disables this component, depending on the value of the
1478 * parameter <code>b</code>. An enabled component can respond to user
1479 * input and generate events. Components are enabled initially by default.
1480 *
1481 * <p>Note: Disabling a lightweight component does not prevent it from
1482 * receiving MouseEvents.
1483 * <p>Note: Disabling a heavyweight container prevents all components
1484 * in this container from receiving any input events. But disabling a
1485 * lightweight container affects only this container.
1486 *
1487 * @param b If <code>true</code>, this component is
1488 * enabled; otherwise this component is disabled
1489 * @see #isEnabled
1490 * @see #isLightweight
1491 * @since 1.1
1492 */
1493 public void setEnabled(boolean b) {
1494 enable(b);
1495 }
1496
1497 /**
1498 * @deprecated As of JDK version 1.1,
1499 * replaced by <code>setEnabled(boolean)</code>.
1500 */
1501 @Deprecated
1502 public void enable() {
1503 if (!enabled) {
1504 synchronized (getTreeLock()) {
1505 enabled = true;
1506 ComponentPeer peer = this.peer;
1507 if (peer != null) {
1508 peer.setEnabled(true);
1509 if (visible && !getRecursivelyVisibleBounds().isEmpty()) {
1510 updateCursorImmediately();
1511 }
1512 }
1513 }
1514 if (accessibleContext != null) {
1515 accessibleContext.firePropertyChange(
1516 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1517 null, AccessibleState.ENABLED);
1518 }
1519 }
1520 }
1521
1522 /**
1523 * Enables or disables this component.
1524 *
1525 * @param b {@code true} to enable this component;
1526 * otherwise {@code false}
1527 *
1528 * @deprecated As of JDK version 1.1,
1529 * replaced by <code>setEnabled(boolean)</code>.
1530 */
1531 @Deprecated
1532 public void enable(boolean b) {
1533 if (b) {
1534 enable();
1535 } else {
1536 disable();
1537 }
1538 }
1539
1540 /**
1541 * @deprecated As of JDK version 1.1,
1542 * replaced by <code>setEnabled(boolean)</code>.
1543 */
1544 @Deprecated
1545 public void disable() {
1546 if (enabled) {
1547 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1548 synchronized (getTreeLock()) {
1549 enabled = false;
1550 // A disabled lw container is allowed to contain a focus owner.
1551 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1552 KeyboardFocusManager.isAutoFocusTransferEnabled())
1553 {
1554 // Don't clear the global focus owner. If transferFocus
1555 // fails, we want the focus to stay on the disabled
1556 // Component so that keyboard traversal, et. al. still
1557 // makes sense to the user.
1558 transferFocus(false);
1559 }
1560 ComponentPeer peer = this.peer;
1561 if (peer != null) {
1562 peer.setEnabled(false);
1612 new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1613 inputContext.dispatchEvent(focusGainedEvent);
1614 }
1615 }
1616
1617 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1618 } else {
1619 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1620 InputContext inputContext = getInputContext();
1621 if (inputContext != null) {
1622 inputContext.endComposition();
1623 inputContext.removeNotify(this);
1624 }
1625 }
1626 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1627 }
1628 }
1629
1630 /**
1631 * Shows or hides this component depending on the value of parameter
1632 * <code>b</code>.
1633 * <p>
1634 * This method changes layout-related information, and therefore,
1635 * invalidates the component hierarchy.
1636 *
1637 * @param b if <code>true</code>, shows this component;
1638 * otherwise, hides this component
1639 * @see #isVisible
1640 * @see #invalidate
1641 * @since 1.1
1642 */
1643 public void setVisible(boolean b) {
1644 show(b);
1645 }
1646
1647 /**
1648 * @deprecated As of JDK version 1.1,
1649 * replaced by <code>setVisible(boolean)</code>.
1650 */
1651 @Deprecated
1652 public void show() {
1653 if (!visible) {
1654 synchronized (getTreeLock()) {
1655 visible = true;
1656 mixOnShowing();
1657 ComponentPeer peer = this.peer;
1658 if (peer != null) {
1659 peer.setVisible(true);
1660 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1661 this, parent,
1662 HierarchyEvent.SHOWING_CHANGED,
1663 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1664 if (peer instanceof LightweightPeer) {
1665 repaint();
1666 }
1667 updateCursorImmediately();
1668 }
1669
1672 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1673 ComponentEvent e = new ComponentEvent(this,
1674 ComponentEvent.COMPONENT_SHOWN);
1675 Toolkit.getEventQueue().postEvent(e);
1676 }
1677 }
1678 Container parent = this.parent;
1679 if (parent != null) {
1680 parent.invalidate();
1681 }
1682 }
1683 }
1684
1685 /**
1686 * Makes this component visible or invisible.
1687 *
1688 * @param b {@code true} to make this component visible;
1689 * otherwise {@code false}
1690 *
1691 * @deprecated As of JDK version 1.1,
1692 * replaced by <code>setVisible(boolean)</code>.
1693 */
1694 @Deprecated
1695 public void show(boolean b) {
1696 if (b) {
1697 show();
1698 } else {
1699 hide();
1700 }
1701 }
1702
1703 boolean containsFocus() {
1704 return isFocusOwner();
1705 }
1706
1707 void clearMostRecentFocusOwnerOnHide() {
1708 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1709 }
1710
1711 void clearCurrentFocusCycleRootOnHide() {
1712 /* do nothing */
1713 }
1714
1715 /**
1716 * @deprecated As of JDK version 1.1,
1717 * replaced by <code>setVisible(boolean)</code>.
1718 */
1719 @Deprecated
1720 public void hide() {
1721 isPacked = false;
1722
1723 if (visible) {
1724 clearCurrentFocusCycleRootOnHide();
1725 clearMostRecentFocusOwnerOnHide();
1726 synchronized (getTreeLock()) {
1727 visible = false;
1728 mixOnHiding(isLightweight());
1729 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
1730 transferFocus(true);
1731 }
1732 ComponentPeer peer = this.peer;
1733 if (peer != null) {
1734 peer.setVisible(false);
1735 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1736 this, parent,
1737 HierarchyEvent.SHOWING_CHANGED,
1762 * not have a foreground color, the foreground color of its parent
1763 * is returned
1764 * @see #setForeground
1765 * @since 1.0
1766 * @beaninfo
1767 * bound: true
1768 */
1769 @Transient
1770 public Color getForeground() {
1771 Color foreground = this.foreground;
1772 if (foreground != null) {
1773 return foreground;
1774 }
1775 Container parent = this.parent;
1776 return (parent != null) ? parent.getForeground() : null;
1777 }
1778
1779 /**
1780 * Sets the foreground color of this component.
1781 * @param c the color to become this component's
1782 * foreground color; if this parameter is <code>null</code>
1783 * then this component will inherit
1784 * the foreground color of its parent
1785 * @see #getForeground
1786 * @since 1.0
1787 */
1788 public void setForeground(Color c) {
1789 Color oldColor = foreground;
1790 ComponentPeer peer = this.peer;
1791 foreground = c;
1792 if (peer != null) {
1793 c = getForeground();
1794 if (c != null) {
1795 peer.setForeground(c);
1796 }
1797 }
1798 // This is a bound property, so report the change to
1799 // any registered listeners. (Cheap if there are none.)
1800 firePropertyChange("foreground", oldColor, c);
1801 }
1802
1803 /**
1804 * Returns whether the foreground color has been explicitly set for this
1805 * Component. If this method returns <code>false</code>, this Component is
1806 * inheriting its foreground color from an ancestor.
1807 *
1808 * @return <code>true</code> if the foreground color has been explicitly
1809 * set for this Component; <code>false</code> otherwise.
1810 * @since 1.4
1811 */
1812 public boolean isForegroundSet() {
1813 return (foreground != null);
1814 }
1815
1816 /**
1817 * Gets the background color of this component.
1818 * @return this component's background color; if this component does
1819 * not have a background color,
1820 * the background color of its parent is returned
1821 * @see #setBackground
1822 * @since 1.0
1823 */
1824 @Transient
1825 public Color getBackground() {
1826 Color background = this.background;
1827 if (background != null) {
1828 return background;
1829 }
1830 Container parent = this.parent;
1831 return (parent != null) ? parent.getBackground() : null;
1832 }
1833
1834 /**
1835 * Sets the background color of this component.
1836 * <p>
1837 * The background color affects each component differently and the
1838 * parts of the component that are affected by the background color
1839 * may differ between operating systems.
1840 *
1841 * @param c the color to become this component's color;
1842 * if this parameter is <code>null</code>, then this
1843 * component will inherit the background color of its parent
1844 * @see #getBackground
1845 * @since 1.0
1846 * @beaninfo
1847 * bound: true
1848 */
1849 public void setBackground(Color c) {
1850 Color oldColor = background;
1851 ComponentPeer peer = this.peer;
1852 background = c;
1853 if (peer != null) {
1854 c = getBackground();
1855 if (c != null) {
1856 peer.setBackground(c);
1857 }
1858 }
1859 // This is a bound property, so report the change to
1860 // any registered listeners. (Cheap if there are none.)
1861 firePropertyChange("background", oldColor, c);
1862 }
1863
1864 /**
1865 * Returns whether the background color has been explicitly set for this
1866 * Component. If this method returns <code>false</code>, this Component is
1867 * inheriting its background color from an ancestor.
1868 *
1869 * @return <code>true</code> if the background color has been explicitly
1870 * set for this Component; <code>false</code> otherwise.
1871 * @since 1.4
1872 */
1873 public boolean isBackgroundSet() {
1874 return (background != null);
1875 }
1876
1877 /**
1878 * Gets the font of this component.
1879 * @return this component's font; if a font has not been set
1880 * for this component, the font of its parent is returned
1881 * @see #setFont
1882 * @since 1.0
1883 */
1884 @Transient
1885 public Font getFont() {
1886 return getFont_NoClientCode();
1887 }
1888
1889 // NOTE: This method may be called by privileged threads.
1890 // This functionality is implemented in a package-private method
1891 // to insure that it cannot be overridden by client subclasses.
1892 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1893 final Font getFont_NoClientCode() {
1894 Font font = this.font;
1895 if (font != null) {
1896 return font;
1897 }
1898 Container parent = this.parent;
1899 return (parent != null) ? parent.getFont_NoClientCode() : null;
1900 }
1901
1902 /**
1903 * Sets the font of this component.
1904 * <p>
1905 * This method changes layout-related information, and therefore,
1906 * invalidates the component hierarchy.
1907 *
1908 * @param f the font to become this component's font;
1909 * if this parameter is <code>null</code> then this
1910 * component will inherit the font of its parent
1911 * @see #getFont
1912 * @see #invalidate
1913 * @since 1.0
1914 * @beaninfo
1915 * bound: true
1916 */
1917 public void setFont(Font f) {
1918 Font oldFont, newFont;
1919 synchronized(getTreeLock()) {
1920 oldFont = font;
1921 newFont = font = f;
1922 ComponentPeer peer = this.peer;
1923 if (peer != null) {
1924 f = getFont();
1925 if (f != null) {
1926 peer.setFont(f);
1927 peerFont = f;
1928 }
1929 }
1930 }
1931 // This is a bound property, so report the change to
1932 // any registered listeners. (Cheap if there are none.)
1933 firePropertyChange("font", oldFont, newFont);
1934
1935 // This could change the preferred size of the Component.
1936 // Fix for 6213660. Should compare old and new fonts and do not
1937 // call invalidate() if they are equal.
1938 if (f != oldFont && (oldFont == null ||
1939 !oldFont.equals(f))) {
1940 invalidateIfValid();
1941 }
1942 }
1943
1944 /**
1945 * Returns whether the font has been explicitly set for this Component. If
1946 * this method returns <code>false</code>, this Component is inheriting its
1947 * font from an ancestor.
1948 *
1949 * @return <code>true</code> if the font has been explicitly set for this
1950 * Component; <code>false</code> otherwise.
1951 * @since 1.4
1952 */
1953 public boolean isFontSet() {
1954 return (font != null);
1955 }
1956
1957 /**
1958 * Gets the locale of this component.
1959 * @return this component's locale; if this component does not
1960 * have a locale, the locale of its parent is returned
1961 * @see #setLocale
1962 * @exception IllegalComponentStateException if the <code>Component</code>
1963 * does not have its own locale and has not yet been added to
1964 * a containment hierarchy such that the locale can be determined
1965 * from the containing parent
1966 * @since 1.1
1967 */
1968 public Locale getLocale() {
1969 Locale locale = this.locale;
1970 if (locale != null) {
1971 return locale;
1972 }
1973 Container parent = this.parent;
1974
1975 if (parent == null) {
1976 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");
1977 } else {
1978 return parent.getLocale();
1979 }
1980 }
1981
1982 /**
1986 * invalidates the component hierarchy.
1987 *
1988 * @param l the locale to become this component's locale
1989 * @see #getLocale
1990 * @see #invalidate
1991 * @since 1.1
1992 */
1993 public void setLocale(Locale l) {
1994 Locale oldValue = locale;
1995 locale = l;
1996
1997 // This is a bound property, so report the change to
1998 // any registered listeners. (Cheap if there are none.)
1999 firePropertyChange("locale", oldValue, l);
2000
2001 // This could change the preferred size of the Component.
2002 invalidateIfValid();
2003 }
2004
2005 /**
2006 * Gets the instance of <code>ColorModel</code> used to display
2007 * the component on the output device.
2008 * @return the color model used by this component
2009 * @see java.awt.image.ColorModel
2010 * @see java.awt.peer.ComponentPeer#getColorModel()
2011 * @see Toolkit#getColorModel()
2012 * @since 1.0
2013 */
2014 public ColorModel getColorModel() {
2015 ComponentPeer peer = this.peer;
2016 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
2017 return peer.getColorModel();
2018 } else if (GraphicsEnvironment.isHeadless()) {
2019 return ColorModel.getRGBdefault();
2020 } // else
2021 return getToolkit().getColorModel();
2022 }
2023
2024 /**
2025 * Gets the location of this component in the form of a
2026 * point specifying the component's top-left corner.
2027 * The location will be relative to the parent's coordinate space.
2028 * <p>
2029 * Due to the asynchronous nature of native event handling, this
2030 * method can return outdated values (for instance, after several calls
2031 * of <code>setLocation()</code> in rapid succession). For this
2032 * reason, the recommended method of obtaining a component's position is
2033 * within <code>java.awt.event.ComponentListener.componentMoved()</code>,
2034 * which is called after the operating system has finished moving the
2035 * component.
2036 * </p>
2037 * @return an instance of <code>Point</code> representing
2038 * the top-left corner of the component's bounds in
2039 * the coordinate space of the component's parent
2040 * @see #setLocation
2041 * @see #getLocationOnScreen
2042 * @since 1.1
2043 */
2044 public Point getLocation() {
2045 return location();
2046 }
2047
2048 /**
2049 * Gets the location of this component in the form of a point
2050 * specifying the component's top-left corner in the screen's
2051 * coordinate space.
2052 * @return an instance of <code>Point</code> representing
2053 * the top-left corner of the component's bounds in the
2054 * coordinate space of the screen
2055 * @throws IllegalComponentStateException if the
2056 * component is not showing on the screen
2057 * @see #setLocation
2058 * @see #getLocation
2059 */
2060 public Point getLocationOnScreen() {
2061 synchronized (getTreeLock()) {
2062 return getLocationOnScreen_NoTreeLock();
2063 }
2064 }
2065
2066 /*
2067 * a package private version of getLocationOnScreen
2068 * used by GlobalCursormanager to update cursor
2069 */
2070 final Point getLocationOnScreen_NoTreeLock() {
2071
2072 if (peer != null && isShowing()) {
2078 for(Component c = this; c != host; c = c.getParent()) {
2079 pt.x += c.x;
2080 pt.y += c.y;
2081 }
2082 return pt;
2083 } else {
2084 Point pt = peer.getLocationOnScreen();
2085 return pt;
2086 }
2087 } else {
2088 throw new IllegalComponentStateException("component must be showing on the screen to determine its location");
2089 }
2090 }
2091
2092
2093 /**
2094 * Returns the location of this component's top left corner.
2095 *
2096 * @return the location of this component's top left corner
2097 * @deprecated As of JDK version 1.1,
2098 * replaced by <code>getLocation()</code>.
2099 */
2100 @Deprecated
2101 public Point location() {
2102 return location_NoClientCode();
2103 }
2104
2105 private Point location_NoClientCode() {
2106 return new Point(x, y);
2107 }
2108
2109 /**
2110 * Moves this component to a new location. The top-left corner of
2111 * the new location is specified by the <code>x</code> and <code>y</code>
2112 * parameters in the coordinate space of this component's parent.
2113 * <p>
2114 * This method changes layout-related information, and therefore,
2115 * invalidates the component hierarchy.
2116 *
2117 * @param x the <i>x</i>-coordinate of the new location's
2118 * top-left corner in the parent's coordinate space
2119 * @param y the <i>y</i>-coordinate of the new location's
2120 * top-left corner in the parent's coordinate space
2121 * @see #getLocation
2122 * @see #setBounds
2123 * @see #invalidate
2124 * @since 1.1
2125 */
2126 public void setLocation(int x, int y) {
2127 move(x, y);
2128 }
2129
2130 /**
2131 * Moves this component to a new location.
2132 *
2133 * @param x the <i>x</i>-coordinate of the new location's
2134 * top-left corner in the parent's coordinate space
2135 * @param y the <i>y</i>-coordinate of the new location's
2136 * top-left corner in the parent's coordinate space
2137 *
2138 * @deprecated As of JDK version 1.1,
2139 * replaced by <code>setLocation(int, int)</code>.
2140 */
2141 @Deprecated
2142 public void move(int x, int y) {
2143 synchronized(getTreeLock()) {
2144 setBoundsOp(ComponentPeer.SET_LOCATION);
2145 setBounds(x, y, width, height);
2146 }
2147 }
2148
2149 /**
2150 * Moves this component to a new location. The top-left corner of
2151 * the new location is specified by point <code>p</code>. Point
2152 * <code>p</code> is given in the parent's coordinate space.
2153 * <p>
2154 * This method changes layout-related information, and therefore,
2155 * invalidates the component hierarchy.
2156 *
2157 * @param p the point defining the top-left corner
2158 * of the new location, given in the coordinate space of this
2159 * component's parent
2160 * @see #getLocation
2161 * @see #setBounds
2162 * @see #invalidate
2163 * @since 1.1
2164 */
2165 public void setLocation(Point p) {
2166 setLocation(p.x, p.y);
2167 }
2168
2169 /**
2170 * Returns the size of this component in the form of a
2171 * <code>Dimension</code> object. The <code>height</code>
2172 * field of the <code>Dimension</code> object contains
2173 * this component's height, and the <code>width</code>
2174 * field of the <code>Dimension</code> object contains
2175 * this component's width.
2176 * @return a <code>Dimension</code> object that indicates the
2177 * size of this component
2178 * @see #setSize
2179 * @since 1.1
2180 */
2181 public Dimension getSize() {
2182 return size();
2183 }
2184
2185 /**
2186 * Returns the size of this component in the form of a
2187 * {@code Dimension} object.
2188 *
2189 * @return the {@code Dimension} object that indicates the
2190 * size of this component
2191 * @deprecated As of JDK version 1.1,
2192 * replaced by <code>getSize()</code>.
2193 */
2194 @Deprecated
2195 public Dimension size() {
2196 return new Dimension(width, height);
2197 }
2198
2199 /**
2200 * Resizes this component so that it has width <code>width</code>
2201 * and height <code>height</code>.
2202 * <p>
2203 * This method changes layout-related information, and therefore,
2204 * invalidates the component hierarchy.
2205 *
2206 * @param width the new width of this component in pixels
2207 * @param height the new height of this component in pixels
2208 * @see #getSize
2209 * @see #setBounds
2210 * @see #invalidate
2211 * @since 1.1
2212 */
2213 public void setSize(int width, int height) {
2214 resize(width, height);
2215 }
2216
2217 /**
2218 * Resizes this component.
2219 *
2220 * @param width the new width of the component
2221 * @param height the new height of the component
2222 * @deprecated As of JDK version 1.1,
2223 * replaced by <code>setSize(int, int)</code>.
2224 */
2225 @Deprecated
2226 public void resize(int width, int height) {
2227 synchronized(getTreeLock()) {
2228 setBoundsOp(ComponentPeer.SET_SIZE);
2229 setBounds(x, y, width, height);
2230 }
2231 }
2232
2233 /**
2234 * Resizes this component so that it has width <code>d.width</code>
2235 * and height <code>d.height</code>.
2236 * <p>
2237 * This method changes layout-related information, and therefore,
2238 * invalidates the component hierarchy.
2239 *
2240 * @param d the dimension specifying the new size
2241 * of this component
2242 * @throws NullPointerException if {@code d} is {@code null}
2243 * @see #setSize
2244 * @see #setBounds
2245 * @see #invalidate
2246 * @since 1.1
2247 */
2248 public void setSize(Dimension d) {
2249 resize(d);
2250 }
2251
2252 /**
2253 * Resizes this component so that it has width {@code d.width}
2254 * and height {@code d.height}.
2255 *
2256 * @param d the new size of this component
2257 * @deprecated As of JDK version 1.1,
2258 * replaced by <code>setSize(Dimension)</code>.
2259 */
2260 @Deprecated
2261 public void resize(Dimension d) {
2262 setSize(d.width, d.height);
2263 }
2264
2265 /**
2266 * Gets the bounds of this component in the form of a
2267 * <code>Rectangle</code> object. The bounds specify this
2268 * component's width, height, and location relative to
2269 * its parent.
2270 * @return a rectangle indicating this component's bounds
2271 * @see #setBounds
2272 * @see #getLocation
2273 * @see #getSize
2274 */
2275 public Rectangle getBounds() {
2276 return bounds();
2277 }
2278
2279 /**
2280 * Returns the bounding rectangle of this component.
2281 *
2282 * @return the bounding rectangle for this component
2283 * @deprecated As of JDK version 1.1,
2284 * replaced by <code>getBounds()</code>.
2285 */
2286 @Deprecated
2287 public Rectangle bounds() {
2288 return new Rectangle(x, y, width, height);
2289 }
2290
2291 /**
2292 * Moves and resizes this component. The new location of the top-left
2293 * corner is specified by <code>x</code> and <code>y</code>, and the
2294 * new size is specified by <code>width</code> and <code>height</code>.
2295 * <p>
2296 * This method changes layout-related information, and therefore,
2297 * invalidates the component hierarchy.
2298 *
2299 * @param x the new <i>x</i>-coordinate of this component
2300 * @param y the new <i>y</i>-coordinate of this component
2301 * @param width the new <code>width</code> of this component
2302 * @param height the new <code>height</code> of this
2303 * component
2304 * @see #getBounds
2305 * @see #setLocation(int, int)
2306 * @see #setLocation(Point)
2307 * @see #setSize(int, int)
2308 * @see #setSize(Dimension)
2309 * @see #invalidate
2310 * @since 1.1
2311 */
2312 public void setBounds(int x, int y, int width, int height) {
2313 reshape(x, y, width, height);
2314 }
2315
2316 /**
2317 * Reshapes the bounding rectangle for this component.
2318 *
2319 * @param x the <i>x</i> coordinate of the upper left corner of the rectangle
2320 * @param y the <i>y</i> coordinate of the upper left corner of the rectangle
2321 * @param width the width of the rectangle
2322 * @param height the height of the rectangle
2323 *
2324 * @deprecated As of JDK version 1.1,
2325 * replaced by <code>setBounds(int, int, int, int)</code>.
2326 */
2327 @Deprecated
2328 public void reshape(int x, int y, int width, int height) {
2329 synchronized (getTreeLock()) {
2330 try {
2331 setBoundsOp(ComponentPeer.SET_BOUNDS);
2332 boolean resized = (this.width != width) || (this.height != height);
2333 boolean moved = (this.x != x) || (this.y != y);
2334 if (!resized && !moved) {
2335 return;
2336 }
2337 int oldX = this.x;
2338 int oldY = this.y;
2339 int oldWidth = this.width;
2340 int oldHeight = this.height;
2341 this.x = x;
2342 this.y = y;
2343 this.width = width;
2344 this.height = height;
2345
2425 }
2426 } else {
2427 if (this instanceof Container && ((Container)this).countComponents() > 0) {
2428 boolean enabledOnToolkit =
2429 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
2430 if (resized) {
2431
2432 ((Container)this).createChildHierarchyEvents(
2433 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);
2434 }
2435 if (moved) {
2436 ((Container)this).createChildHierarchyEvents(
2437 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);
2438 }
2439 }
2440 }
2441 }
2442
2443 /**
2444 * Moves and resizes this component to conform to the new
2445 * bounding rectangle <code>r</code>. This component's new
2446 * position is specified by <code>r.x</code> and <code>r.y</code>,
2447 * and its new size is specified by <code>r.width</code> and
2448 * <code>r.height</code>
2449 * <p>
2450 * This method changes layout-related information, and therefore,
2451 * invalidates the component hierarchy.
2452 *
2453 * @param r the new bounding rectangle for this component
2454 * @throws NullPointerException if {@code r} is {@code null}
2455 * @see #getBounds
2456 * @see #setLocation(int, int)
2457 * @see #setLocation(Point)
2458 * @see #setSize(int, int)
2459 * @see #setSize(Dimension)
2460 * @see #invalidate
2461 * @since 1.1
2462 */
2463 public void setBounds(Rectangle r) {
2464 setBounds(r.x, r.y, r.width, r.height);
2465 }
2466
2467
2468 /**
2469 * Returns the current x coordinate of the components origin.
2470 * This method is preferable to writing
2471 * <code>component.getBounds().x</code>,
2472 * or <code>component.getLocation().x</code> because it doesn't
2473 * cause any heap allocations.
2474 *
2475 * @return the current x coordinate of the components origin
2476 * @since 1.2
2477 */
2478 public int getX() {
2479 return x;
2480 }
2481
2482
2483 /**
2484 * Returns the current y coordinate of the components origin.
2485 * This method is preferable to writing
2486 * <code>component.getBounds().y</code>,
2487 * or <code>component.getLocation().y</code> because it
2488 * doesn't cause any heap allocations.
2489 *
2490 * @return the current y coordinate of the components origin
2491 * @since 1.2
2492 */
2493 public int getY() {
2494 return y;
2495 }
2496
2497
2498 /**
2499 * Returns the current width of this component.
2500 * This method is preferable to writing
2501 * <code>component.getBounds().width</code>,
2502 * or <code>component.getSize().width</code> because it
2503 * doesn't cause any heap allocations.
2504 *
2505 * @return the current width of this component
2506 * @since 1.2
2507 */
2508 public int getWidth() {
2509 return width;
2510 }
2511
2512
2513 /**
2514 * Returns the current height of this component.
2515 * This method is preferable to writing
2516 * <code>component.getBounds().height</code>,
2517 * or <code>component.getSize().height</code> because it
2518 * doesn't cause any heap allocations.
2519 *
2520 * @return the current height of this component
2521 * @since 1.2
2522 */
2523 public int getHeight() {
2524 return height;
2525 }
2526
2527 /**
2528 * Stores the bounds of this component into "return value" <b>rv</b> and
2529 * return <b>rv</b>. If rv is <code>null</code> a new
2530 * <code>Rectangle</code> is allocated.
2531 * This version of <code>getBounds</code> is useful if the caller
2532 * wants to avoid allocating a new <code>Rectangle</code> object
2533 * on the heap.
2534 *
2535 * @param rv the return value, modified to the components bounds
2536 * @return rv
2537 */
2538 public Rectangle getBounds(Rectangle rv) {
2539 if (rv == null) {
2540 return new Rectangle(getX(), getY(), getWidth(), getHeight());
2541 }
2542 else {
2543 rv.setBounds(getX(), getY(), getWidth(), getHeight());
2544 return rv;
2545 }
2546 }
2547
2548 /**
2549 * Stores the width/height of this component into "return value" <b>rv</b>
2550 * and return <b>rv</b>. If rv is <code>null</code> a new
2551 * <code>Dimension</code> object is allocated. This version of
2552 * <code>getSize</code> is useful if the caller wants to avoid
2553 * allocating a new <code>Dimension</code> object on the heap.
2554 *
2555 * @param rv the return value, modified to the components size
2556 * @return rv
2557 */
2558 public Dimension getSize(Dimension rv) {
2559 if (rv == null) {
2560 return new Dimension(getWidth(), getHeight());
2561 }
2562 else {
2563 rv.setSize(getWidth(), getHeight());
2564 return rv;
2565 }
2566 }
2567
2568 /**
2569 * Stores the x,y origin of this component into "return value" <b>rv</b>
2570 * and return <b>rv</b>. If rv is <code>null</code> a new
2571 * <code>Point</code> is allocated.
2572 * This version of <code>getLocation</code> is useful if the
2573 * caller wants to avoid allocating a new <code>Point</code>
2574 * object on the heap.
2575 *
2576 * @param rv the return value, modified to the components location
2577 * @return rv
2578 */
2579 public Point getLocation(Point rv) {
2580 if (rv == null) {
2581 return new Point(getX(), getY());
2582 }
2583 else {
2584 rv.setLocation(getX(), getY());
2585 return rv;
2586 }
2587 }
2588
2589 /**
2590 * Returns true if this component is completely opaque, returns
2591 * false by default.
2592 * <p>
2593 * An opaque component paints every pixel within its
2598 * <p>
2599 * Subclasses that guarantee to always completely paint their
2600 * contents should override this method and return true.
2601 *
2602 * @return true if this component is completely opaque
2603 * @see #isLightweight
2604 * @since 1.2
2605 */
2606 public boolean isOpaque() {
2607 if (peer == null) {
2608 return false;
2609 }
2610 else {
2611 return !isLightweight();
2612 }
2613 }
2614
2615
2616 /**
2617 * A lightweight component doesn't have a native toolkit peer.
2618 * Subclasses of <code>Component</code> and <code>Container</code>,
2619 * other than the ones defined in this package like <code>Button</code>
2620 * or <code>Scrollbar</code>, are lightweight.
2621 * All of the Swing components are lightweights.
2622 * <p>
2623 * This method will always return <code>false</code> if this component
2624 * is not displayable because it is impossible to determine the
2625 * weight of an undisplayable component.
2626 *
2627 * @return true if this component has a lightweight peer; false if
2628 * it has a native peer or no peer
2629 * @see #isDisplayable
2630 * @since 1.2
2631 */
2632 public boolean isLightweight() {
2633 return peer instanceof LightweightPeer;
2634 }
2635
2636
2637 /**
2638 * Sets the preferred size of this component to a constant
2639 * value. Subsequent calls to <code>getPreferredSize</code> will always
2640 * return this value. Setting the preferred size to <code>null</code>
2641 * restores the default behavior.
2642 *
2643 * @param preferredSize The new preferred size, or null
2644 * @see #getPreferredSize
2645 * @see #isPreferredSizeSet
2646 * @since 1.5
2647 */
2648 public void setPreferredSize(Dimension preferredSize) {
2649 Dimension old;
2650 // If the preferred size was set, use it as the old value, otherwise
2651 // use null to indicate we didn't previously have a set preferred
2652 // size.
2653 if (prefSizeSet) {
2654 old = this.prefSize;
2655 }
2656 else {
2657 old = null;
2658 }
2659 this.prefSize = preferredSize;
2660 prefSizeSet = (preferredSize != null);
2661 firePropertyChange("preferredSize", old, preferredSize);
2662 }
2663
2664
2665 /**
2666 * Returns true if the preferred size has been set to a
2667 * non-<code>null</code> value otherwise returns false.
2668 *
2669 * @return true if <code>setPreferredSize</code> has been invoked
2670 * with a non-null value.
2671 * @since 1.5
2672 */
2673 public boolean isPreferredSizeSet() {
2674 return prefSizeSet;
2675 }
2676
2677
2678 /**
2679 * Gets the preferred size of this component.
2680 * @return a dimension object indicating this component's preferred size
2681 * @see #getMinimumSize
2682 * @see LayoutManager
2683 */
2684 public Dimension getPreferredSize() {
2685 return preferredSize();
2686 }
2687
2688
2689 /**
2690 * Returns the component's preferred size.
2691 *
2692 * @return the component's preferred size
2693 * @deprecated As of JDK version 1.1,
2694 * replaced by <code>getPreferredSize()</code>.
2695 */
2696 @Deprecated
2697 public Dimension preferredSize() {
2698 /* Avoid grabbing the lock if a reasonable cached size value
2699 * is available.
2700 */
2701 Dimension dim = prefSize;
2702 if (dim == null || !(isPreferredSizeSet() || isValid())) {
2703 synchronized (getTreeLock()) {
2704 prefSize = (peer != null) ?
2705 peer.getPreferredSize() :
2706 getMinimumSize();
2707 dim = prefSize;
2708 }
2709 }
2710 return new Dimension(dim);
2711 }
2712
2713 /**
2714 * Sets the minimum size of this component to a constant
2715 * value. Subsequent calls to <code>getMinimumSize</code> will always
2716 * return this value. Setting the minimum size to <code>null</code>
2717 * restores the default behavior.
2718 *
2719 * @param minimumSize the new minimum size of this component
2720 * @see #getMinimumSize
2721 * @see #isMinimumSizeSet
2722 * @since 1.5
2723 */
2724 public void setMinimumSize(Dimension minimumSize) {
2725 Dimension old;
2726 // If the minimum size was set, use it as the old value, otherwise
2727 // use null to indicate we didn't previously have a set minimum
2728 // size.
2729 if (minSizeSet) {
2730 old = this.minSize;
2731 }
2732 else {
2733 old = null;
2734 }
2735 this.minSize = minimumSize;
2736 minSizeSet = (minimumSize != null);
2737 firePropertyChange("minimumSize", old, minimumSize);
2738 }
2739
2740 /**
2741 * Returns whether or not <code>setMinimumSize</code> has been
2742 * invoked with a non-null value.
2743 *
2744 * @return true if <code>setMinimumSize</code> has been invoked with a
2745 * non-null value.
2746 * @since 1.5
2747 */
2748 public boolean isMinimumSizeSet() {
2749 return minSizeSet;
2750 }
2751
2752 /**
2753 * Gets the minimum size of this component.
2754 * @return a dimension object indicating this component's minimum size
2755 * @see #getPreferredSize
2756 * @see LayoutManager
2757 */
2758 public Dimension getMinimumSize() {
2759 return minimumSize();
2760 }
2761
2762 /**
2763 * Returns the minimum size of this component.
2764 *
2765 * @return the minimum size of this component
2766 * @deprecated As of JDK version 1.1,
2767 * replaced by <code>getMinimumSize()</code>.
2768 */
2769 @Deprecated
2770 public Dimension minimumSize() {
2771 /* Avoid grabbing the lock if a reasonable cached size value
2772 * is available.
2773 */
2774 Dimension dim = minSize;
2775 if (dim == null || !(isMinimumSizeSet() || isValid())) {
2776 synchronized (getTreeLock()) {
2777 minSize = (peer != null) ?
2778 peer.getMinimumSize() :
2779 size();
2780 dim = minSize;
2781 }
2782 }
2783 return new Dimension(dim);
2784 }
2785
2786 /**
2787 * Sets the maximum size of this component to a constant
2788 * value. Subsequent calls to <code>getMaximumSize</code> will always
2789 * return this value. Setting the maximum size to <code>null</code>
2790 * restores the default behavior.
2791 *
2792 * @param maximumSize a <code>Dimension</code> containing the
2793 * desired maximum allowable size
2794 * @see #getMaximumSize
2795 * @see #isMaximumSizeSet
2796 * @since 1.5
2797 */
2798 public void setMaximumSize(Dimension maximumSize) {
2799 // If the maximum size was set, use it as the old value, otherwise
2800 // use null to indicate we didn't previously have a set maximum
2801 // size.
2802 Dimension old;
2803 if (maxSizeSet) {
2804 old = this.maxSize;
2805 }
2806 else {
2807 old = null;
2808 }
2809 this.maxSize = maximumSize;
2810 maxSizeSet = (maximumSize != null);
2811 firePropertyChange("maximumSize", old, maximumSize);
2812 }
2813
2814 /**
2815 * Returns true if the maximum size has been set to a non-<code>null</code>
2816 * value otherwise returns false.
2817 *
2818 * @return true if <code>maximumSize</code> is non-<code>null</code>,
2819 * false otherwise
2820 * @since 1.5
2821 */
2822 public boolean isMaximumSizeSet() {
2823 return maxSizeSet;
2824 }
2825
2826 /**
2827 * Gets the maximum size of this component.
2828 * @return a dimension object indicating this component's maximum size
2829 * @see #getMinimumSize
2830 * @see #getPreferredSize
2831 * @see LayoutManager
2832 */
2833 public Dimension getMaximumSize() {
2834 if (isMaximumSizeSet()) {
2835 return new Dimension(maxSize);
2836 }
2837 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
2838 }
2849 public float getAlignmentX() {
2850 return CENTER_ALIGNMENT;
2851 }
2852
2853 /**
2854 * Returns the alignment along the y axis. This specifies how
2855 * the component would like to be aligned relative to other
2856 * components. The value should be a number between 0 and 1
2857 * where 0 represents alignment along the origin, 1 is aligned
2858 * the furthest away from the origin, 0.5 is centered, etc.
2859 *
2860 * @return the vertical alignment of this component
2861 */
2862 public float getAlignmentY() {
2863 return CENTER_ALIGNMENT;
2864 }
2865
2866 /**
2867 * Returns the baseline. The baseline is measured from the top of
2868 * the component. This method is primarily meant for
2869 * <code>LayoutManager</code>s to align components along their
2870 * baseline. A return value less than 0 indicates this component
2871 * does not have a reasonable baseline and that
2872 * <code>LayoutManager</code>s should not align this component on
2873 * its baseline.
2874 * <p>
2875 * The default implementation returns -1. Subclasses that support
2876 * baseline should override appropriately. If a value >= 0 is
2877 * returned, then the component has a valid baseline for any
2878 * size >= the minimum size and <code>getBaselineResizeBehavior</code>
2879 * can be used to determine how the baseline changes with size.
2880 *
2881 * @param width the width to get the baseline for
2882 * @param height the height to get the baseline for
2883 * @return the baseline or < 0 indicating there is no reasonable
2884 * baseline
2885 * @throws IllegalArgumentException if width or height is < 0
2886 * @see #getBaselineResizeBehavior
2887 * @see java.awt.FontMetrics
2888 * @since 1.6
2889 */
2890 public int getBaseline(int width, int height) {
2891 if (width < 0 || height < 0) {
2892 throw new IllegalArgumentException(
2893 "Width and height must be >= 0");
2894 }
2895 return -1;
2896 }
2897
2898 /**
2899 * Returns an enum indicating how the baseline of the component
2900 * changes as the size changes. This method is primarily meant for
2901 * layout managers and GUI builders.
2902 * <p>
2903 * The default implementation returns
2904 * <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a
2905 * baseline should override appropriately. Subclasses should
2906 * never return <code>null</code>; if the baseline can not be
2907 * calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers
2908 * should first ask for the baseline using
2909 * <code>getBaseline</code> and if a value >= 0 is returned use
2910 * this method. It is acceptable for this method to return a
2911 * value other than <code>BaselineResizeBehavior.OTHER</code> even if
2912 * <code>getBaseline</code> returns a value less than 0.
2913 *
2914 * @return an enum indicating how the baseline changes as the component
2915 * size changes
2916 * @see #getBaseline(int, int)
2917 * @since 1.6
2918 */
2919 public BaselineResizeBehavior getBaselineResizeBehavior() {
2920 return BaselineResizeBehavior.OTHER;
2921 }
2922
2923 /**
2924 * Prompts the layout manager to lay out this component. This is
2925 * usually called when the component (more specifically, container)
2926 * is validated.
2927 * @see #validate
2928 * @see LayoutManager
2929 */
2930 public void doLayout() {
2931 layout();
2932 }
2933
2934 /**
2935 * @deprecated As of JDK version 1.1,
2936 * replaced by <code>doLayout()</code>.
2937 */
2938 @Deprecated
2939 public void layout() {
2940 }
2941
2942 /**
2943 * Validates this component.
2944 * <p>
2945 * The meaning of the term <i>validating</i> is defined by the ancestors of
2946 * this class. See {@link Container#validate} for more details.
2947 *
2948 * @see #invalidate
2949 * @see #doLayout()
2950 * @see LayoutManager
2951 * @see Container#validate
2952 * @since 1.0
2953 */
2954 public void validate() {
2955 synchronized (getTreeLock()) {
2956 ComponentPeer peer = this.peer;
3065 // There's no parents. Just validate itself.
3066 validate();
3067 } else {
3068 while (!root.isValidateRoot()) {
3069 if (root.getContainer() == null) {
3070 // If there's no validate roots, we'll validate the
3071 // topmost container
3072 break;
3073 }
3074
3075 root = root.getContainer();
3076 }
3077
3078 root.validate();
3079 }
3080 }
3081 }
3082
3083 /**
3084 * Creates a graphics context for this component. This method will
3085 * return <code>null</code> if this component is currently not
3086 * displayable.
3087 * @return a graphics context for this component, or <code>null</code>
3088 * if it has none
3089 * @see #paint
3090 * @since 1.0
3091 */
3092 public Graphics getGraphics() {
3093 if (peer instanceof LightweightPeer) {
3094 // This is for a lightweight component, need to
3095 // translate coordinate spaces and clip relative
3096 // to the parent.
3097 if (parent == null) return null;
3098 Graphics g = parent.getGraphics();
3099 if (g == null) return null;
3100 if (g instanceof ConstrainableGraphics) {
3101 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3102 } else {
3103 g.translate(x,y);
3104 g.setClip(0, 0, width, height);
3105 }
3106 g.setFont(getFont());
3107 return g;
3129 }
3130 g.setFont(getFont_NoClientCode());
3131 return g;
3132 } else {
3133 return (peer != null) ? peer.getGraphics() : null;
3134 }
3135 }
3136
3137 /**
3138 * Gets the font metrics for the specified font.
3139 * Warning: Since Font metrics are affected by the
3140 * {@link java.awt.font.FontRenderContext FontRenderContext} and
3141 * this method does not provide one, it can return only metrics for
3142 * the default render context which may not match that used when
3143 * rendering on the Component if {@link Graphics2D} functionality is being
3144 * used. Instead metrics can be obtained at rendering time by calling
3145 * {@link Graphics#getFontMetrics()} or text measurement APIs on the
3146 * {@link Font Font} class.
3147 * @param font the font for which font metrics is to be
3148 * obtained
3149 * @return the font metrics for <code>font</code>
3150 * @see #getFont
3151 * @see java.awt.peer.ComponentPeer#getFontMetrics(Font)
3152 * @see Toolkit#getFontMetrics(Font)
3153 * @since 1.0
3154 */
3155 public FontMetrics getFontMetrics(Font font) {
3156 // This is an unsupported hack, but left in for a customer.
3157 // Do not remove.
3158 FontManager fm = FontManagerFactory.getInstance();
3159 if (fm instanceof SunFontManager
3160 && ((SunFontManager) fm).usePlatformFontMetrics()) {
3161
3162 if (peer != null &&
3163 !(peer instanceof LightweightPeer)) {
3164 return peer.getFontMetrics(font);
3165 }
3166 }
3167 return sun.font.FontDesignMetrics.getMetrics(font);
3168 }
3169
3170 /**
3171 * Sets the cursor image to the specified cursor. This cursor
3172 * image is displayed when the <code>contains</code> method for
3173 * this component returns true for the current cursor location, and
3174 * this Component is visible, displayable, and enabled. Setting the
3175 * cursor of a <code>Container</code> causes that cursor to be displayed
3176 * within all of the container's subcomponents, except for those
3177 * that have a non-<code>null</code> cursor.
3178 * <p>
3179 * The method may have no visual effect if the Java platform
3180 * implementation and/or the native system do not support
3181 * changing the mouse cursor shape.
3182 * @param cursor One of the constants defined
3183 * by the <code>Cursor</code> class;
3184 * if this parameter is <code>null</code>
3185 * then this component will inherit
3186 * the cursor of its parent
3187 * @see #isEnabled
3188 * @see #isShowing
3189 * @see #getCursor
3190 * @see #contains
3191 * @see Toolkit#createCustomCursor
3192 * @see Cursor
3193 * @since 1.1
3194 */
3195 public void setCursor(Cursor cursor) {
3196 this.cursor = cursor;
3197 updateCursorImmediately();
3198 }
3199
3200 /**
3201 * Updates the cursor. May not be invoked from the native
3202 * message pump.
3203 */
3204 final void updateCursorImmediately() {
3205 if (peer instanceof LightweightPeer) {
3206 Container nativeContainer = getNativeContainer();
3207
3208 if (nativeContainer == null) return;
3209
3210 ComponentPeer cPeer = nativeContainer.peer;
3211
3212 if (cPeer != null) {
3213 cPeer.updateCursorImmediately();
3214 }
3215 } else if (peer != null) {
3216 peer.updateCursorImmediately();
3217 }
3218 }
3219
3220 /**
3221 * Gets the cursor set in the component. If the component does
3222 * not have a cursor set, the cursor of its parent is returned.
3223 * If no cursor is set in the entire hierarchy,
3224 * <code>Cursor.DEFAULT_CURSOR</code> is returned.
3225 *
3226 * @return the cursor for this component
3227 * @see #setCursor
3228 * @since 1.1
3229 */
3230 public Cursor getCursor() {
3231 return getCursor_NoClientCode();
3232 }
3233
3234 final Cursor getCursor_NoClientCode() {
3235 Cursor cursor = this.cursor;
3236 if (cursor != null) {
3237 return cursor;
3238 }
3239 Container parent = this.parent;
3240 if (parent != null) {
3241 return parent.getCursor_NoClientCode();
3242 } else {
3243 return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
3244 }
3245 }
3246
3247 /**
3248 * Returns whether the cursor has been explicitly set for this Component.
3249 * If this method returns <code>false</code>, this Component is inheriting
3250 * its cursor from an ancestor.
3251 *
3252 * @return <code>true</code> if the cursor has been explicitly set for this
3253 * Component; <code>false</code> otherwise.
3254 * @since 1.4
3255 */
3256 public boolean isCursorSet() {
3257 return (cursor != null);
3258 }
3259
3260 /**
3261 * Paints this component.
3262 * <p>
3263 * This method is called when the contents of the component should
3264 * be painted; such as when the component is first being shown or
3265 * is damaged and in need of repair. The clip rectangle in the
3266 * <code>Graphics</code> parameter is set to the area
3267 * which needs to be painted.
3268 * Subclasses of <code>Component</code> that override this
3269 * method need not call <code>super.paint(g)</code>.
3270 * <p>
3271 * For performance reasons, <code>Component</code>s with zero width
3272 * or height aren't considered to need painting when they are first shown,
3273 * and also aren't considered to need repair.
3274 * <p>
3275 * <b>Note</b>: For more information on the paint mechanisms utilitized
3276 * by AWT and Swing, including information on how to write the most
3277 * efficient painting code, see
3278 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3279 *
3280 * @param g the graphics context to use for painting
3281 * @see #update
3282 * @since 1.0
3283 */
3284 public void paint(Graphics g) {
3285 }
3286
3287 /**
3288 * Updates this component.
3289 * <p>
3290 * If this component is not a lightweight component, the
3291 * AWT calls the <code>update</code> method in response to
3292 * a call to <code>repaint</code>. You can assume that
3293 * the background is not cleared.
3294 * <p>
3295 * The <code>update</code> method of <code>Component</code>
3296 * calls this component's <code>paint</code> method to redraw
3297 * this component. This method is commonly overridden by subclasses
3298 * which need to do additional work in response to a call to
3299 * <code>repaint</code>.
3300 * Subclasses of Component that override this method should either
3301 * call <code>super.update(g)</code>, or call <code>paint(g)</code>
3302 * directly from their <code>update</code> method.
3303 * <p>
3304 * The origin of the graphics context, its
3305 * (<code>0</code>, <code>0</code>) coordinate point, is the
3306 * top-left corner of this component. The clipping region of the
3307 * graphics context is the bounding rectangle of this component.
3308 *
3309 * <p>
3310 * <b>Note</b>: For more information on the paint mechanisms utilitized
3311 * by AWT and Swing, including information on how to write the most
3312 * efficient painting code, see
3313 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3314 *
3315 * @param g the specified context to use for updating
3316 * @see #paint
3317 * @see #repaint()
3318 * @since 1.0
3319 */
3320 public void update(Graphics g) {
3321 paint(g);
3322 }
3323
3324 /**
3325 * Paints this component and all of its subcomponents.
3326 * <p>
3327 * The origin of the graphics context, its
3328 * (<code>0</code>, <code>0</code>) coordinate point, is the
3329 * top-left corner of this component. The clipping region of the
3330 * graphics context is the bounding rectangle of this component.
3331 *
3332 * @param g the graphics context to use for painting
3333 * @see #paint
3334 * @since 1.0
3335 */
3336 public void paintAll(Graphics g) {
3337 if (isShowing()) {
3338 GraphicsCallback.PeerPaintCallback.getInstance().
3339 runOneComponent(this, new Rectangle(0, 0, width, height),
3340 g, g.getClip(),
3341 GraphicsCallback.LIGHTWEIGHTS |
3342 GraphicsCallback.HEAVYWEIGHTS);
3343 }
3344 }
3345
3346 /**
3347 * Simulates the peer callbacks into java.awt for painting of
3348 * lightweight Components.
3349 * @param g the graphics context to use for painting
3350 * @see #paintAll
3351 */
3352 void lightweightPaint(Graphics g) {
3353 paint(g);
3354 }
3355
3356 /**
3357 * Paints all the heavyweight subcomponents.
3358 */
3359 void paintHeavyweightComponents(Graphics g) {
3360 }
3361
3362 /**
3363 * Repaints this component.
3364 * <p>
3365 * If this component is a lightweight component, this method
3366 * causes a call to this component's <code>paint</code>
3367 * method as soon as possible. Otherwise, this method causes
3368 * a call to this component's <code>update</code> method as soon
3369 * as possible.
3370 * <p>
3371 * <b>Note</b>: For more information on the paint mechanisms utilitized
3372 * by AWT and Swing, including information on how to write the most
3373 * efficient painting code, see
3374 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3375
3376 *
3377 * @see #update(Graphics)
3378 * @since 1.0
3379 */
3380 public void repaint() {
3381 repaint(0, 0, 0, width, height);
3382 }
3383
3384 /**
3385 * Repaints the component. If this component is a lightweight
3386 * component, this results in a call to <code>paint</code>
3387 * within <code>tm</code> milliseconds.
3388 * <p>
3389 * <b>Note</b>: For more information on the paint mechanisms utilitized
3390 * by AWT and Swing, including information on how to write the most
3391 * efficient painting code, see
3392 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3393 *
3394 * @param tm maximum time in milliseconds before update
3395 * @see #paint
3396 * @see #update(Graphics)
3397 * @since 1.0
3398 */
3399 public void repaint(long tm) {
3400 repaint(tm, 0, 0, width, height);
3401 }
3402
3403 /**
3404 * Repaints the specified rectangle of this component.
3405 * <p>
3406 * If this component is a lightweight component, this method
3407 * causes a call to this component's <code>paint</code> method
3408 * as soon as possible. Otherwise, this method causes a call to
3409 * this component's <code>update</code> method as soon as possible.
3410 * <p>
3411 * <b>Note</b>: For more information on the paint mechanisms utilitized
3412 * by AWT and Swing, including information on how to write the most
3413 * efficient painting code, see
3414 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3415 *
3416 * @param x the <i>x</i> coordinate
3417 * @param y the <i>y</i> coordinate
3418 * @param width the width
3419 * @param height the height
3420 * @see #update(Graphics)
3421 * @since 1.0
3422 */
3423 public void repaint(int x, int y, int width, int height) {
3424 repaint(0, x, y, width, height);
3425 }
3426
3427 /**
3428 * Repaints the specified rectangle of this component within
3429 * <code>tm</code> milliseconds.
3430 * <p>
3431 * If this component is a lightweight component, this method causes
3432 * a call to this component's <code>paint</code> method.
3433 * Otherwise, this method causes a call to this component's
3434 * <code>update</code> method.
3435 * <p>
3436 * <b>Note</b>: For more information on the paint mechanisms utilitized
3437 * by AWT and Swing, including information on how to write the most
3438 * efficient painting code, see
3439 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3440 *
3441 * @param tm maximum time in milliseconds before update
3442 * @param x the <i>x</i> coordinate
3443 * @param y the <i>y</i> coordinate
3444 * @param width the width
3445 * @param height the height
3446 * @see #update(Graphics)
3447 * @since 1.0
3448 */
3449 public void repaint(long tm, int x, int y, int width, int height) {
3450 if (this.peer instanceof LightweightPeer) {
3451 // Needs to be translated to parent coordinates since
3452 // a parent native container provides the actual repaint
3453 // services. Additionally, the request is restricted to
3454 // the bounds of the component.
3472 int px = this.x + x;
3473 int py = this.y + y;
3474 parent.repaint(tm, px, py, pwidth, pheight);
3475 }
3476 } else {
3477 if (isVisible() && (this.peer != null) &&
3478 (width > 0) && (height > 0)) {
3479 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
3480 new Rectangle(x, y, width, height));
3481 SunToolkit.postEvent(SunToolkit.targetToAppContext(this), e);
3482 }
3483 }
3484 }
3485
3486 /**
3487 * Prints this component. Applications should override this method
3488 * for components that must do special processing before being
3489 * printed or should be printed differently than they are painted.
3490 * <p>
3491 * The default implementation of this method calls the
3492 * <code>paint</code> method.
3493 * <p>
3494 * The origin of the graphics context, its
3495 * (<code>0</code>, <code>0</code>) coordinate point, is the
3496 * top-left corner of this component. The clipping region of the
3497 * graphics context is the bounding rectangle of this component.
3498 * @param g the graphics context to use for printing
3499 * @see #paint(Graphics)
3500 * @since 1.0
3501 */
3502 public void print(Graphics g) {
3503 paint(g);
3504 }
3505
3506 /**
3507 * Prints this component and all of its subcomponents.
3508 * <p>
3509 * The origin of the graphics context, its
3510 * (<code>0</code>, <code>0</code>) coordinate point, is the
3511 * top-left corner of this component. The clipping region of the
3512 * graphics context is the bounding rectangle of this component.
3513 * @param g the graphics context to use for printing
3514 * @see #print(Graphics)
3515 * @since 1.0
3516 */
3517 public void printAll(Graphics g) {
3518 if (isShowing()) {
3519 GraphicsCallback.PeerPrintCallback.getInstance().
3520 runOneComponent(this, new Rectangle(0, 0, width, height),
3521 g, g.getClip(),
3522 GraphicsCallback.LIGHTWEIGHTS |
3523 GraphicsCallback.HEAVYWEIGHTS);
3524 }
3525 }
3526
3527 /**
3528 * Simulates the peer callbacks into java.awt for printing of
3529 * lightweight Components.
3530 * @param g the graphics context to use for printing
3533 void lightweightPrint(Graphics g) {
3534 print(g);
3535 }
3536
3537 /**
3538 * Prints all the heavyweight subcomponents.
3539 */
3540 void printHeavyweightComponents(Graphics g) {
3541 }
3542
3543 private Insets getInsets_NoClientCode() {
3544 ComponentPeer peer = this.peer;
3545 if (peer instanceof ContainerPeer) {
3546 return (Insets)((ContainerPeer)peer).getInsets().clone();
3547 }
3548 return new Insets(0, 0, 0, 0);
3549 }
3550
3551 /**
3552 * Repaints the component when the image has changed.
3553 * This <code>imageUpdate</code> method of an <code>ImageObserver</code>
3554 * is called when more information about an
3555 * image which had been previously requested using an asynchronous
3556 * routine such as the <code>drawImage</code> method of
3557 * <code>Graphics</code> becomes available.
3558 * See the definition of <code>imageUpdate</code> for
3559 * more information on this method and its arguments.
3560 * <p>
3561 * The <code>imageUpdate</code> method of <code>Component</code>
3562 * incrementally draws an image on the component as more of the bits
3563 * of the image are available.
3564 * <p>
3565 * If the system property <code>awt.image.incrementaldraw</code>
3566 * is missing or has the value <code>true</code>, the image is
3567 * incrementally drawn. If the system property has any other value,
3568 * then the image is not drawn until it has been completely loaded.
3569 * <p>
3570 * Also, if incremental drawing is in effect, the value of the
3571 * system property <code>awt.image.redrawrate</code> is interpreted
3572 * as an integer to give the maximum redraw rate, in milliseconds. If
3573 * the system property is missing or cannot be interpreted as an
3574 * integer, the redraw rate is once every 100ms.
3575 * <p>
3576 * The interpretation of the <code>x</code>, <code>y</code>,
3577 * <code>width</code>, and <code>height</code> arguments depends on
3578 * the value of the <code>infoflags</code> argument.
3579 *
3580 * @param img the image being observed
3581 * @param infoflags see <code>imageUpdate</code> for more information
3582 * @param x the <i>x</i> coordinate
3583 * @param y the <i>y</i> coordinate
3584 * @param w the width
3585 * @param h the height
3586 * @return <code>false</code> if the infoflags indicate that the
3587 * image is completely loaded; <code>true</code> otherwise.
3588 *
3589 * @see java.awt.image.ImageObserver
3590 * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
3591 * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)
3592 * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
3593 * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
3594 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
3595 * @since 1.0
3596 */
3597 public boolean imageUpdate(Image img, int infoflags,
3598 int x, int y, int w, int h) {
3599 int rate = -1;
3600 if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
3601 rate = 0;
3602 } else if ((infoflags & SOMEBITS) != 0) {
3603 if (isInc) {
3604 rate = incRate;
3605 if (rate < 0) {
3606 rate = 0;
3607 }
3616 /**
3617 * Creates an image from the specified image producer.
3618 * @param producer the image producer
3619 * @return the image produced
3620 * @since 1.0
3621 */
3622 public Image createImage(ImageProducer producer) {
3623 ComponentPeer peer = this.peer;
3624 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
3625 return peer.createImage(producer);
3626 }
3627 return getToolkit().createImage(producer);
3628 }
3629
3630 /**
3631 * Creates an off-screen drawable image
3632 * to be used for double buffering.
3633 * @param width the specified width
3634 * @param height the specified height
3635 * @return an off-screen drawable image, which can be used for double
3636 * buffering. The return value may be <code>null</code> if the
3637 * component is not displayable. This will always happen if
3638 * <code>GraphicsEnvironment.isHeadless()</code> returns
3639 * <code>true</code>.
3640 * @see #isDisplayable
3641 * @see GraphicsEnvironment#isHeadless
3642 * @since 1.0
3643 */
3644 public Image createImage(int width, int height) {
3645 ComponentPeer peer = this.peer;
3646 if (peer instanceof LightweightPeer) {
3647 if (parent != null) { return parent.createImage(width, height); }
3648 else { return null;}
3649 } else {
3650 return (peer != null) ? peer.createImage(width, height) : null;
3651 }
3652 }
3653
3654 /**
3655 * Creates a volatile off-screen drawable image
3656 * to be used for double buffering.
3657 * @param width the specified width.
3658 * @param height the specified height.
3659 * @return an off-screen drawable image, which can be used for double
3660 * buffering. The return value may be <code>null</code> if the
3661 * component is not displayable. This will always happen if
3662 * <code>GraphicsEnvironment.isHeadless()</code> returns
3663 * <code>true</code>.
3664 * @see java.awt.image.VolatileImage
3665 * @see #isDisplayable
3666 * @see GraphicsEnvironment#isHeadless
3667 * @since 1.4
3668 */
3669 public VolatileImage createVolatileImage(int width, int height) {
3670 ComponentPeer peer = this.peer;
3671 if (peer instanceof LightweightPeer) {
3672 if (parent != null) {
3673 return parent.createVolatileImage(width, height);
3674 }
3675 else { return null;}
3676 } else {
3677 return (peer != null) ?
3678 peer.createVolatileImage(width, height) : null;
3679 }
3680 }
3681
3682 /**
3683 * Creates a volatile off-screen drawable image, with the given capabilities.
3684 * The contents of this image may be lost at any time due
3685 * to operating system issues, so the image must be managed
3686 * via the <code>VolatileImage</code> interface.
3687 * @param width the specified width.
3688 * @param height the specified height.
3689 * @param caps the image capabilities
3690 * @exception AWTException if an image with the specified capabilities cannot
3691 * be created
3692 * @return a VolatileImage object, which can be used
3693 * to manage surface contents loss and capabilities.
3694 * @see java.awt.image.VolatileImage
3695 * @since 1.4
3696 */
3697 public VolatileImage createVolatileImage(int width, int height,
3698 ImageCapabilities caps) throws AWTException {
3699 // REMIND : check caps
3700 return createVolatileImage(width, height);
3701 }
3702
3703 /**
3704 * Prepares an image for rendering on this component. The image
3705 * data is downloaded asynchronously in another thread and the
3706 * appropriate screen representation of the image is generated.
3707 * @param image the <code>Image</code> for which to
3708 * prepare a screen representation
3709 * @param observer the <code>ImageObserver</code> object
3710 * to be notified as the image is being prepared
3711 * @return <code>true</code> if the image has already been fully
3712 * prepared; <code>false</code> otherwise
3713 * @since 1.0
3714 */
3715 public boolean prepareImage(Image image, ImageObserver observer) {
3716 return prepareImage(image, -1, -1, observer);
3717 }
3718
3719 /**
3720 * Prepares an image for rendering on this component at the
3721 * specified width and height.
3722 * <p>
3723 * The image data is downloaded asynchronously in another thread,
3724 * and an appropriately scaled screen representation of the image is
3725 * generated.
3726 * @param image the instance of <code>Image</code>
3727 * for which to prepare a screen representation
3728 * @param width the width of the desired screen representation
3729 * @param height the height of the desired screen representation
3730 * @param observer the <code>ImageObserver</code> object
3731 * to be notified as the image is being prepared
3732 * @return <code>true</code> if the image has already been fully
3733 * prepared; <code>false</code> otherwise
3734 * @see java.awt.image.ImageObserver
3735 * @since 1.0
3736 */
3737 public boolean prepareImage(Image image, int width, int height,
3738 ImageObserver observer) {
3739 ComponentPeer peer = this.peer;
3740 if (peer instanceof LightweightPeer) {
3741 return (parent != null)
3742 ? parent.prepareImage(image, width, height, observer)
3743 : getToolkit().prepareImage(image, width, height, observer);
3744 } else {
3745 return (peer != null)
3746 ? peer.prepareImage(image, width, height, observer)
3747 : getToolkit().prepareImage(image, width, height, observer);
3748 }
3749 }
3750
3751 /**
3752 * Returns the status of the construction of a screen representation
3753 * of the specified image.
3754 * <p>
3755 * This method does not cause the image to begin loading. An
3756 * application must use the <code>prepareImage</code> method
3757 * to force the loading of an image.
3758 * <p>
3759 * Information on the flags returned by this method can be found
3760 * with the discussion of the <code>ImageObserver</code> interface.
3761 * @param image the <code>Image</code> object whose status
3762 * is being checked
3763 * @param observer the <code>ImageObserver</code>
3764 * object to be notified as the image is being prepared
3765 * @return the bitwise inclusive <b>OR</b> of
3766 * <code>ImageObserver</code> flags indicating what
3767 * information about the image is currently available
3768 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3769 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3770 * @see java.awt.image.ImageObserver
3771 * @since 1.0
3772 */
3773 public int checkImage(Image image, ImageObserver observer) {
3774 return checkImage(image, -1, -1, observer);
3775 }
3776
3777 /**
3778 * Returns the status of the construction of a screen representation
3779 * of the specified image.
3780 * <p>
3781 * This method does not cause the image to begin loading. An
3782 * application must use the <code>prepareImage</code> method
3783 * to force the loading of an image.
3784 * <p>
3785 * The <code>checkImage</code> method of <code>Component</code>
3786 * calls its peer's <code>checkImage</code> method to calculate
3787 * the flags. If this component does not yet have a peer, the
3788 * component's toolkit's <code>checkImage</code> method is called
3789 * instead.
3790 * <p>
3791 * Information on the flags returned by this method can be found
3792 * with the discussion of the <code>ImageObserver</code> interface.
3793 * @param image the <code>Image</code> object whose status
3794 * is being checked
3795 * @param width the width of the scaled version
3796 * whose status is to be checked
3797 * @param height the height of the scaled version
3798 * whose status is to be checked
3799 * @param observer the <code>ImageObserver</code> object
3800 * to be notified as the image is being prepared
3801 * @return the bitwise inclusive <b>OR</b> of
3802 * <code>ImageObserver</code> flags indicating what
3803 * information about the image is currently available
3804 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3805 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3806 * @see java.awt.image.ImageObserver
3807 * @since 1.0
3808 */
3809 public int checkImage(Image image, int width, int height,
3810 ImageObserver observer) {
3811 ComponentPeer peer = this.peer;
3812 if (peer instanceof LightweightPeer) {
3813 return (parent != null)
3814 ? parent.checkImage(image, width, height, observer)
3815 : getToolkit().checkImage(image, width, height, observer);
3816 } else {
3817 return (peer != null)
3818 ? peer.checkImage(image, width, height, observer)
3819 : getToolkit().checkImage(image, width, height, observer);
3820 }
3821 }
3822
3823 /**
3824 * Creates a new strategy for multi-buffering on this component.
3825 * Multi-buffering is useful for rendering performance. This method
3826 * attempts to create the best strategy available with the number of
3827 * buffers supplied. It will always create a <code>BufferStrategy</code>
3828 * with that number of buffers.
3829 * A page-flipping strategy is attempted first, then a blitting strategy
3830 * using accelerated buffers. Finally, an unaccelerated blitting
3831 * strategy is used.
3832 * <p>
3833 * Each time this method is called,
3834 * the existing buffer strategy for this component is discarded.
3835 * @param numBuffers number of buffers to create, including the front buffer
3836 * @exception IllegalArgumentException if numBuffers is less than 1.
3837 * @exception IllegalStateException if the component is not displayable
3838 * @see #isDisplayable
3839 * @see Window#getBufferStrategy()
3840 * @see Canvas#getBufferStrategy()
3841 * @since 1.4
3842 */
3843 void createBufferStrategy(int numBuffers) {
3844 BufferCapabilities bufferCaps;
3845 if (numBuffers > 1) {
3846 // Try to create a page-flipping strategy
3847 bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3868 bufferCaps = new BufferCapabilities(new ImageCapabilities(false),
3869 new ImageCapabilities(false),
3870 null);
3871 try {
3872 createBufferStrategy(numBuffers, bufferCaps);
3873 return; // Success
3874 } catch (AWTException e) {
3875 // Code should never reach here (an unaccelerated blitting
3876 // strategy should always work)
3877 throw new InternalError("Could not create a buffer strategy", e);
3878 }
3879 }
3880
3881 /**
3882 * Creates a new strategy for multi-buffering on this component with the
3883 * required buffer capabilities. This is useful, for example, if only
3884 * accelerated memory or page flipping is desired (as specified by the
3885 * buffer capabilities).
3886 * <p>
3887 * Each time this method
3888 * is called, <code>dispose</code> will be invoked on the existing
3889 * <code>BufferStrategy</code>.
3890 * @param numBuffers number of buffers to create
3891 * @param caps the required capabilities for creating the buffer strategy;
3892 * cannot be <code>null</code>
3893 * @exception AWTException if the capabilities supplied could not be
3894 * supported or met; this may happen, for example, if there is not enough
3895 * accelerated memory currently available, or if page flipping is specified
3896 * but not possible.
3897 * @exception IllegalArgumentException if numBuffers is less than 1, or if
3898 * caps is <code>null</code>
3899 * @see Window#getBufferStrategy()
3900 * @see Canvas#getBufferStrategy()
3901 * @since 1.4
3902 */
3903 void createBufferStrategy(int numBuffers,
3904 BufferCapabilities caps) throws AWTException {
3905 // Check arguments
3906 if (numBuffers < 1) {
3907 throw new IllegalArgumentException(
3908 "Number of buffers must be at least 1");
3909 }
3910 if (caps == null) {
3911 throw new IllegalArgumentException("No capabilities specified");
3912 }
3913 // Destroy old buffers
3914 if (bufferStrategy != null) {
3915 bufferStrategy.dispose();
3916 }
3917 if (numBuffers == 1) {
3918 bufferStrategy = new SingleBufferStrategy(caps);
3963 /**
3964 * @return the back buffer currently used by this component's
3965 * BufferStrategy. If there is no BufferStrategy or no
3966 * back buffer, this method returns null.
3967 */
3968 Image getBackBuffer() {
3969 if (bufferStrategy != null) {
3970 if (bufferStrategy instanceof BltBufferStrategy) {
3971 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;
3972 return bltBS.getBackBuffer();
3973 } else if (bufferStrategy instanceof FlipBufferStrategy) {
3974 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;
3975 return flipBS.getBackBuffer();
3976 }
3977 }
3978 return null;
3979 }
3980
3981 /**
3982 * Inner class for flipping buffers on a component. That component must
3983 * be a <code>Canvas</code> or <code>Window</code> or <code>Applet</code>.
3984 * @see Canvas
3985 * @see Window
3986 * @see Applet
3987 * @see java.awt.image.BufferStrategy
3988 * @author Michael Martak
3989 * @since 1.4
3990 */
3991 protected class FlipBufferStrategy extends BufferStrategy {
3992 /**
3993 * The number of buffers
3994 */
3995 protected int numBuffers; // = 0
3996 /**
3997 * The buffering capabilities
3998 */
3999 protected BufferCapabilities caps; // = null
4000 /**
4001 * The drawing buffer
4002 */
4003 protected Image drawBuffer; // = null
4014 /**
4015 * Size of the back buffers. (Note: these fields were added in 6.0
4016 * but kept package-private to avoid exposing them in the spec.
4017 * None of these fields/methods really should have been marked
4018 * protected when they were introduced in 1.4, but now we just have
4019 * to live with that decision.)
4020 */
4021
4022 /**
4023 * The width of the back buffers
4024 */
4025 int width;
4026
4027 /**
4028 * The height of the back buffers
4029 */
4030 int height;
4031
4032 /**
4033 * Creates a new flipping buffer strategy for this component.
4034 * The component must be a <code>Canvas</code> or <code>Window</code> or
4035 * <code>Applet</code>.
4036 * @see Canvas
4037 * @see Window
4038 * @see Applet
4039 * @param numBuffers the number of buffers
4040 * @param caps the capabilities of the buffers
4041 * @exception AWTException if the capabilities supplied could not be
4042 * supported or met
4043 * @exception ClassCastException if the component is not a canvas or
4044 * window.
4045 * @exception IllegalStateException if the component has no peer
4046 * @exception IllegalArgumentException if {@code numBuffers} is less than two,
4047 * or if {@code BufferCapabilities.isPageFlipping} is not
4048 * {@code true}.
4049 * @see #createBuffers(int, BufferCapabilities)
4050 */
4051 protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)
4052 throws AWTException
4053 {
4054 if (!(Component.this instanceof Window) &&
4055 !(Component.this instanceof Canvas) &&
4056 !(Component.this instanceof Applet))
4057 {
4058 throw new ClassCastException(
4059 "Component must be a Canvas or Window or Applet");
4060 }
4061 this.numBuffers = numBuffers;
4062 this.caps = caps;
4063 createBuffers(numBuffers, caps);
4064 }
4065
4066 /**
4067 * Creates one or more complex, flipping buffers with the given
4068 * capabilities.
4069 * @param numBuffers number of buffers to create; must be greater than
4070 * one
4071 * @param caps the capabilities of the buffers.
4072 * <code>BufferCapabilities.isPageFlipping</code> must be
4073 * <code>true</code>.
4074 * @exception AWTException if the capabilities supplied could not be
4075 * supported or met
4076 * @exception IllegalStateException if the component has no peer
4077 * @exception IllegalArgumentException if numBuffers is less than two,
4078 * or if <code>BufferCapabilities.isPageFlipping</code> is not
4079 * <code>true</code>.
4080 * @see java.awt.BufferCapabilities#isPageFlipping()
4081 */
4082 protected void createBuffers(int numBuffers, BufferCapabilities caps)
4083 throws AWTException
4084 {
4085 if (numBuffers < 2) {
4086 throw new IllegalArgumentException(
4087 "Number of buffers cannot be less than two");
4088 } else if (peer == null) {
4089 throw new IllegalStateException(
4090 "Component must have a valid peer");
4091 } else if (caps == null || !caps.isPageFlipping()) {
4092 throw new IllegalArgumentException(
4093 "Page flipping capabilities must be specified");
4094 }
4095
4096 // save the current bounds
4097 width = getWidth();
4098 height = getHeight();
4099
4140
4141 /**
4142 * @return direct access to the back buffer, as an image.
4143 * @exception IllegalStateException if the buffers have not yet
4144 * been created
4145 */
4146 protected Image getBackBuffer() {
4147 if (peer != null) {
4148 return peer.getBackBuffer();
4149 } else {
4150 throw new IllegalStateException(
4151 "Component must have a valid peer");
4152 }
4153 }
4154
4155 /**
4156 * Flipping moves the contents of the back buffer to the front buffer,
4157 * either by copying or by moving the video pointer.
4158 * @param flipAction an integer value describing the flipping action
4159 * for the contents of the back buffer. This should be one of the
4160 * values of the <code>BufferCapabilities.FlipContents</code>
4161 * property.
4162 * @exception IllegalStateException if the buffers have not yet
4163 * been created
4164 * @see java.awt.BufferCapabilities#getFlipContents()
4165 */
4166 protected void flip(BufferCapabilities.FlipContents flipAction) {
4167 if (peer != null) {
4168 Image backBuffer = getBackBuffer();
4169 if (backBuffer != null) {
4170 peer.flip(0, 0,
4171 backBuffer.getWidth(null),
4172 backBuffer.getHeight(null), flipAction);
4173 }
4174 } else {
4175 throw new IllegalStateException(
4176 "Component must have a valid peer");
4177 }
4178 }
4179
4180 void flipSubRegion(int x1, int y1, int x2, int y2,
4254 int returnCode = drawVBuffer.validate(gc);
4255 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4256 try {
4257 createBuffers(numBuffers, caps);
4258 } catch (AWTException e) {
4259 // shouldn't be possible
4260 }
4261 if (drawVBuffer != null) {
4262 // backbuffers were recreated, so validate again
4263 drawVBuffer.validate(gc);
4264 }
4265 validatedContents = true;
4266 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4267 validatedContents = true;
4268 }
4269 }
4270 }
4271
4272 /**
4273 * @return whether the drawing buffer was lost since the last call to
4274 * <code>getDrawGraphics</code>
4275 */
4276 public boolean contentsLost() {
4277 if (drawVBuffer == null) {
4278 return false;
4279 }
4280 return drawVBuffer.contentsLost();
4281 }
4282
4283 /**
4284 * @return whether the drawing buffer was recently restored from a lost
4285 * state and reinitialized to the default background color (white)
4286 */
4287 public boolean contentsRestored() {
4288 return validatedContents;
4289 }
4290
4291 /**
4292 * Makes the next available buffer visible by either blitting or
4293 * flipping.
4294 */
4541 int returnCode =
4542 backBuffers[backBuffers.length - 1].validate(gc);
4543 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4544 if (checkSize) {
4545 createBackBuffers(backBuffers.length);
4546 // backbuffers were recreated, so validate again
4547 backBuffers[backBuffers.length - 1].validate(gc);
4548 }
4549 // else case means we're called from Swing on the toolkit
4550 // thread, don't recreate buffers as that'll deadlock
4551 // (creating VolatileImages invokes getting GraphicsConfig
4552 // which grabs treelock).
4553 validatedContents = true;
4554 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4555 validatedContents = true;
4556 }
4557 }
4558
4559 /**
4560 * @return whether the drawing buffer was lost since the last call to
4561 * <code>getDrawGraphics</code>
4562 */
4563 public boolean contentsLost() {
4564 if (backBuffers == null) {
4565 return false;
4566 } else {
4567 return backBuffers[backBuffers.length - 1].contentsLost();
4568 }
4569 }
4570
4571 /**
4572 * @return whether the drawing buffer was recently restored from a lost
4573 * state and reinitialized to the default background color (white)
4574 */
4575 public boolean contentsRestored() {
4576 return validatedContents;
4577 }
4578 } // Inner class BltBufferStrategy
4579
4580 /**
4581 * Private class to perform sub-region flipping.
4620 {
4621 super(numBuffers, caps);
4622 }
4623
4624 public void show(int x1, int y1, int x2, int y2) {
4625 showSubRegion(x1, y1, x2, y2);
4626 }
4627
4628 // This method is called by Swing on the toolkit thread.
4629 public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4630 if (!contentsLost()) {
4631 showSubRegion(x1, y1, x2, y2);
4632 return !contentsLost();
4633 }
4634 return false;
4635 }
4636 }
4637
4638 /**
4639 * Inner class for flipping buffers on a component. That component must
4640 * be a <code>Canvas</code> or <code>Window</code>.
4641 * @see Canvas
4642 * @see Window
4643 * @see java.awt.image.BufferStrategy
4644 * @author Michael Martak
4645 * @since 1.4
4646 */
4647 private class SingleBufferStrategy extends BufferStrategy {
4648
4649 private BufferCapabilities caps;
4650
4651 public SingleBufferStrategy(BufferCapabilities caps) {
4652 this.caps = caps;
4653 }
4654 public BufferCapabilities getCapabilities() {
4655 return caps;
4656 }
4657 public Graphics getDrawGraphics() {
4658 return getGraphics();
4659 }
4660 public boolean contentsLost() {
4688 * @see java.awt.image.BufferStrategy
4689 * @see GraphicsDevice#setFullScreenWindow
4690 */
4691 public void setIgnoreRepaint(boolean ignoreRepaint) {
4692 this.ignoreRepaint = ignoreRepaint;
4693 }
4694
4695 /**
4696 * @return whether or not paint messages received from the operating system
4697 * should be ignored.
4698 *
4699 * @since 1.4
4700 * @see #setIgnoreRepaint
4701 */
4702 public boolean getIgnoreRepaint() {
4703 return ignoreRepaint;
4704 }
4705
4706 /**
4707 * Checks whether this component "contains" the specified point,
4708 * where <code>x</code> and <code>y</code> are defined to be
4709 * relative to the coordinate system of this component.
4710 *
4711 * @param x the <i>x</i> coordinate of the point
4712 * @param y the <i>y</i> coordinate of the point
4713 * @return {@code true} if the point is within the component;
4714 * otherwise {@code false}
4715 * @see #getComponentAt(int, int)
4716 * @since 1.1
4717 */
4718 public boolean contains(int x, int y) {
4719 return inside(x, y);
4720 }
4721
4722 /**
4723 * Checks whether the point is inside of this component.
4724 *
4725 * @param x the <i>x</i> coordinate of the point
4726 * @param y the <i>y</i> coordinate of the point
4727 * @return {@code true} if the point is within the component;
4728 * otherwise {@code false}
4741 *
4742 * @param p the point
4743 * @return {@code true} if the point is within the component;
4744 * otherwise {@code false}
4745 * @throws NullPointerException if {@code p} is {@code null}
4746 * @see #getComponentAt(Point)
4747 * @since 1.1
4748 */
4749 public boolean contains(Point p) {
4750 return contains(p.x, p.y);
4751 }
4752
4753 /**
4754 * Determines if this component or one of its immediate
4755 * subcomponents contains the (<i>x</i>, <i>y</i>) location,
4756 * and if so, returns the containing component. This method only
4757 * looks one level deep. If the point (<i>x</i>, <i>y</i>) is
4758 * inside a subcomponent that itself has subcomponents, it does not
4759 * go looking down the subcomponent tree.
4760 * <p>
4761 * The <code>locate</code> method of <code>Component</code> simply
4762 * returns the component itself if the (<i>x</i>, <i>y</i>)
4763 * coordinate location is inside its bounding box, and <code>null</code>
4764 * otherwise.
4765 * @param x the <i>x</i> coordinate
4766 * @param y the <i>y</i> coordinate
4767 * @return the component or subcomponent that contains the
4768 * (<i>x</i>, <i>y</i>) location;
4769 * <code>null</code> if the location
4770 * is outside this component
4771 * @see #contains(int, int)
4772 * @since 1.0
4773 */
4774 public Component getComponentAt(int x, int y) {
4775 return locate(x, y);
4776 }
4777
4778 /**
4779 * Returns the component occupying the position specified (this component,
4780 * or immediate child component, or null if neither
4781 * of the first two occupies the location).
4782 *
4783 * @param x the <i>x</i> coordinate to search for components at
4784 * @param y the <i>y</i> coordinate to search for components at
4785 * @return the component at the specified location or {@code null}
4786 * @deprecated As of JDK version 1.1,
4787 * replaced by getComponentAt(int, int).
4788 */
4789 @Deprecated
4790 public Component locate(int x, int y) {
4791 return contains(x, y) ? this : null;
4792 }
4793
4794 /**
4795 * Returns the component or subcomponent that contains the
4796 * specified point.
4797 * @param p the point
4798 * @return the component at the specified location or {@code null}
4799 * @see java.awt.Component#contains
4800 * @since 1.1
4801 */
4802 public Component getComponentAt(Point p) {
4803 return getComponentAt(p.x, p.y);
4804 }
4805
4806 /**
4807 * @param e the event to deliver
4808 * @deprecated As of JDK version 1.1,
4809 * replaced by <code>dispatchEvent(AWTEvent e)</code>.
4810 */
4811 @Deprecated
4812 public void deliverEvent(Event e) {
4813 postEvent(e);
4814 }
4815
4816 /**
4817 * Dispatches an event to this component or one of its sub components.
4818 * Calls <code>processEvent</code> before returning for 1.1-style
4819 * events which have been enabled for the <code>Component</code>.
4820 * @param e the event
4821 */
4822 public final void dispatchEvent(AWTEvent e) {
4823 dispatchEventImpl(e);
4824 }
4825
4826 @SuppressWarnings("deprecation")
4827 void dispatchEventImpl(AWTEvent e) {
4828 int id = e.getID();
4829
4830 // Check that this component belongs to this app-context
4831 AppContext compContext = appContext;
4832 if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
4833 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
4834 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");
4835 }
4836 }
4837
4838 if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4839 eventLog.finest("{0}", e);
5267 int eventx = e.x;
5268 int eventy = e.y;
5269 if (parent != null) {
5270 e.translate(x, y);
5271 if (parent.postEvent(e)) {
5272 e.consume();
5273 return true;
5274 }
5275 // restore coords
5276 e.x = eventx;
5277 e.y = eventy;
5278 }
5279 return false;
5280 }
5281
5282 // Event source interfaces
5283
5284 /**
5285 * Adds the specified component listener to receive component events from
5286 * this component.
5287 * If listener <code>l</code> is <code>null</code>,
5288 * no exception is thrown and no action is performed.
5289 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5290 * >AWT Threading Issues</a> for details on AWT's threading model.
5291 *
5292 * @param l the component listener
5293 * @see java.awt.event.ComponentEvent
5294 * @see java.awt.event.ComponentListener
5295 * @see #removeComponentListener
5296 * @see #getComponentListeners
5297 * @since 1.1
5298 */
5299 public synchronized void addComponentListener(ComponentListener l) {
5300 if (l == null) {
5301 return;
5302 }
5303 componentListener = AWTEventMulticaster.add(componentListener, l);
5304 newEventsOnly = true;
5305 }
5306
5307 /**
5308 * Removes the specified component listener so that it no longer
5309 * receives component events from this component. This method performs
5310 * no function, nor does it throw an exception, if the listener
5311 * 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 * @param l the component listener
5317 * @see java.awt.event.ComponentEvent
5318 * @see java.awt.event.ComponentListener
5319 * @see #addComponentListener
5320 * @see #getComponentListeners
5321 * @since 1.1
5322 */
5323 public synchronized void removeComponentListener(ComponentListener l) {
5324 if (l == null) {
5325 return;
5326 }
5327 componentListener = AWTEventMulticaster.remove(componentListener, l);
5328 }
5329
5330 /**
5331 * Returns an array of all the component listeners
5332 * registered on this component.
5333 *
5334 * @return all <code>ComponentListener</code>s of this component
5335 * or an empty array if no component
5336 * listeners are currently registered
5337 *
5338 * @see #addComponentListener
5339 * @see #removeComponentListener
5340 * @since 1.4
5341 */
5342 public synchronized ComponentListener[] getComponentListeners() {
5343 return getListeners(ComponentListener.class);
5344 }
5345
5346 /**
5347 * Adds the specified focus listener to receive focus events from
5348 * this component when this component gains input focus.
5349 * If listener <code>l</code> is <code>null</code>,
5350 * no exception is thrown and no action is performed.
5351 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5352 * >AWT Threading Issues</a> for details on AWT's threading model.
5353 *
5354 * @param l the focus listener
5355 * @see java.awt.event.FocusEvent
5356 * @see java.awt.event.FocusListener
5357 * @see #removeFocusListener
5358 * @see #getFocusListeners
5359 * @since 1.1
5360 */
5361 public synchronized void addFocusListener(FocusListener l) {
5362 if (l == null) {
5363 return;
5364 }
5365 focusListener = AWTEventMulticaster.add(focusListener, l);
5366 newEventsOnly = true;
5367
5368 // if this is a lightweight component, enable focus events
5369 // in the native container.
5370 if (peer instanceof LightweightPeer) {
5371 parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5372 }
5373 }
5374
5375 /**
5376 * Removes the specified focus listener so that it no longer
5377 * receives focus events from this component. This method performs
5378 * no function, nor does it throw an exception, if the listener
5379 * specified by the argument was not previously added to this component.
5380 * If listener <code>l</code> is <code>null</code>,
5381 * no exception is thrown and no action is performed.
5382 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5383 * >AWT Threading Issues</a> for details on AWT's threading model.
5384 *
5385 * @param l the focus listener
5386 * @see java.awt.event.FocusEvent
5387 * @see java.awt.event.FocusListener
5388 * @see #addFocusListener
5389 * @see #getFocusListeners
5390 * @since 1.1
5391 */
5392 public synchronized void removeFocusListener(FocusListener l) {
5393 if (l == null) {
5394 return;
5395 }
5396 focusListener = AWTEventMulticaster.remove(focusListener, l);
5397 }
5398
5399 /**
5400 * Returns an array of all the focus listeners
5401 * registered on this component.
5402 *
5403 * @return all of this component's <code>FocusListener</code>s
5404 * or an empty array if no component
5405 * listeners are currently registered
5406 *
5407 * @see #addFocusListener
5408 * @see #removeFocusListener
5409 * @since 1.4
5410 */
5411 public synchronized FocusListener[] getFocusListeners() {
5412 return getListeners(FocusListener.class);
5413 }
5414
5415 /**
5416 * Adds the specified hierarchy listener to receive hierarchy changed
5417 * events from this component when the hierarchy to which this container
5418 * belongs changes.
5419 * If listener <code>l</code> is <code>null</code>,
5420 * no exception is thrown and no action is performed.
5421 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5422 * >AWT Threading Issues</a> for details on AWT's threading model.
5423 *
5424 * @param l the hierarchy listener
5425 * @see java.awt.event.HierarchyEvent
5426 * @see java.awt.event.HierarchyListener
5427 * @see #removeHierarchyListener
5428 * @see #getHierarchyListeners
5429 * @since 1.3
5430 */
5431 public void addHierarchyListener(HierarchyListener l) {
5432 if (l == null) {
5433 return;
5434 }
5435 boolean notifyAncestors;
5436 synchronized (this) {
5437 notifyAncestors =
5438 (hierarchyListener == null &&
5439 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5440 hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5441 notifyAncestors = (notifyAncestors && hierarchyListener != null);
5442 newEventsOnly = true;
5443 }
5444 if (notifyAncestors) {
5445 synchronized (getTreeLock()) {
5446 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5447 1);
5448 }
5449 }
5450 }
5451
5452 /**
5453 * Removes the specified hierarchy listener so that it no longer
5454 * receives hierarchy changed events from this component. This method
5455 * performs no function, nor does it throw an exception, if the listener
5456 * specified by the argument was not previously added to this component.
5457 * If listener <code>l</code> is <code>null</code>,
5458 * no exception is thrown and no action is performed.
5459 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5460 * >AWT Threading Issues</a> for details on AWT's threading model.
5461 *
5462 * @param l the hierarchy listener
5463 * @see java.awt.event.HierarchyEvent
5464 * @see java.awt.event.HierarchyListener
5465 * @see #addHierarchyListener
5466 * @see #getHierarchyListeners
5467 * @since 1.3
5468 */
5469 public void removeHierarchyListener(HierarchyListener l) {
5470 if (l == null) {
5471 return;
5472 }
5473 boolean notifyAncestors;
5474 synchronized (this) {
5475 notifyAncestors =
5476 (hierarchyListener != null &&
5477 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5478 hierarchyListener =
5479 AWTEventMulticaster.remove(hierarchyListener, l);
5480 notifyAncestors = (notifyAncestors && hierarchyListener == null);
5481 }
5482 if (notifyAncestors) {
5483 synchronized (getTreeLock()) {
5484 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5485 -1);
5486 }
5487 }
5488 }
5489
5490 /**
5491 * Returns an array of all the hierarchy listeners
5492 * registered on this component.
5493 *
5494 * @return all of this component's <code>HierarchyListener</code>s
5495 * or an empty array if no hierarchy
5496 * listeners are currently registered
5497 *
5498 * @see #addHierarchyListener
5499 * @see #removeHierarchyListener
5500 * @since 1.4
5501 */
5502 public synchronized HierarchyListener[] getHierarchyListeners() {
5503 return getListeners(HierarchyListener.class);
5504 }
5505
5506 /**
5507 * Adds the specified hierarchy bounds listener to receive hierarchy
5508 * bounds events from this component when the hierarchy to which this
5509 * container belongs changes.
5510 * If listener <code>l</code> is <code>null</code>,
5511 * no exception is thrown and no action is performed.
5512 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5513 * >AWT Threading Issues</a> for details on AWT's threading model.
5514 *
5515 * @param l the hierarchy bounds listener
5516 * @see java.awt.event.HierarchyEvent
5517 * @see java.awt.event.HierarchyBoundsListener
5518 * @see #removeHierarchyBoundsListener
5519 * @see #getHierarchyBoundsListeners
5520 * @since 1.3
5521 */
5522 public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5523 if (l == null) {
5524 return;
5525 }
5526 boolean notifyAncestors;
5527 synchronized (this) {
5528 notifyAncestors =
5529 (hierarchyBoundsListener == null &&
5530 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5531 hierarchyBoundsListener =
5532 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5533 notifyAncestors = (notifyAncestors &&
5534 hierarchyBoundsListener != null);
5535 newEventsOnly = true;
5536 }
5537 if (notifyAncestors) {
5538 synchronized (getTreeLock()) {
5539 adjustListeningChildrenOnParent(
5540 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5541 }
5542 }
5543 }
5544
5545 /**
5546 * Removes the specified hierarchy bounds listener so that it no longer
5547 * receives hierarchy bounds events from this component. This method
5548 * performs no function, nor does it throw an exception, if the listener
5549 * specified by the argument was not previously added to this component.
5550 * If listener <code>l</code> is <code>null</code>,
5551 * no exception is thrown and no action is performed.
5552 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5553 * >AWT Threading Issues</a> for details on AWT's threading model.
5554 *
5555 * @param l the hierarchy bounds listener
5556 * @see java.awt.event.HierarchyEvent
5557 * @see java.awt.event.HierarchyBoundsListener
5558 * @see #addHierarchyBoundsListener
5559 * @see #getHierarchyBoundsListeners
5560 * @since 1.3
5561 */
5562 public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5563 if (l == null) {
5564 return;
5565 }
5566 boolean notifyAncestors;
5567 synchronized (this) {
5568 notifyAncestors =
5569 (hierarchyBoundsListener != null &&
5570 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5636 HierarchyEvent e = new HierarchyEvent(this, id, changed,
5637 changedParent);
5638 dispatchEvent(e);
5639 return 1;
5640 }
5641 break;
5642 default:
5643 // assert false
5644 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5645 eventLog.fine("This code must never be reached");
5646 }
5647 break;
5648 }
5649 return 0;
5650 }
5651
5652 /**
5653 * Returns an array of all the hierarchy bounds listeners
5654 * registered on this component.
5655 *
5656 * @return all of this component's <code>HierarchyBoundsListener</code>s
5657 * or an empty array if no hierarchy bounds
5658 * listeners are currently registered
5659 *
5660 * @see #addHierarchyBoundsListener
5661 * @see #removeHierarchyBoundsListener
5662 * @since 1.4
5663 */
5664 public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5665 return getListeners(HierarchyBoundsListener.class);
5666 }
5667
5668 /*
5669 * Should only be called while holding the tree lock.
5670 * It's added only for overriding in java.awt.Window
5671 * because parent in Window is owner.
5672 */
5673 void adjustListeningChildrenOnParent(long mask, int num) {
5674 if (parent != null) {
5675 parent.adjustListeningChildren(mask, num);
5676 }
5692 */
5693 public synchronized void addKeyListener(KeyListener l) {
5694 if (l == null) {
5695 return;
5696 }
5697 keyListener = AWTEventMulticaster.add(keyListener, l);
5698 newEventsOnly = true;
5699
5700 // if this is a lightweight component, enable key events
5701 // in the native container.
5702 if (peer instanceof LightweightPeer) {
5703 parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5704 }
5705 }
5706
5707 /**
5708 * Removes the specified key listener so that it no longer
5709 * receives key events from this component. This method performs
5710 * no function, nor does it throw an exception, if the listener
5711 * specified by the argument was not previously added to this component.
5712 * If listener <code>l</code> is <code>null</code>,
5713 * no exception is thrown and no action is performed.
5714 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5715 * >AWT Threading Issues</a> for details on AWT's threading model.
5716 *
5717 * @param l the key listener
5718 * @see java.awt.event.KeyEvent
5719 * @see java.awt.event.KeyListener
5720 * @see #addKeyListener
5721 * @see #getKeyListeners
5722 * @since 1.1
5723 */
5724 public synchronized void removeKeyListener(KeyListener l) {
5725 if (l == null) {
5726 return;
5727 }
5728 keyListener = AWTEventMulticaster.remove(keyListener, l);
5729 }
5730
5731 /**
5732 * Returns an array of all the key listeners
5733 * registered on this component.
5734 *
5735 * @return all of this component's <code>KeyListener</code>s
5736 * or an empty array if no key
5737 * listeners are currently registered
5738 *
5739 * @see #addKeyListener
5740 * @see #removeKeyListener
5741 * @since 1.4
5742 */
5743 public synchronized KeyListener[] getKeyListeners() {
5744 return getListeners(KeyListener.class);
5745 }
5746
5747 /**
5748 * Adds the specified mouse listener to receive mouse events from
5749 * this component.
5750 * If listener <code>l</code> is <code>null</code>,
5751 * no exception is thrown and no action is performed.
5752 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5753 * >AWT Threading Issues</a> for details on AWT's threading model.
5754 *
5755 * @param l the mouse listener
5756 * @see java.awt.event.MouseEvent
5757 * @see java.awt.event.MouseListener
5758 * @see #removeMouseListener
5759 * @see #getMouseListeners
5760 * @since 1.1
5761 */
5762 public synchronized void addMouseListener(MouseListener l) {
5763 if (l == null) {
5764 return;
5765 }
5766 mouseListener = AWTEventMulticaster.add(mouseListener,l);
5767 newEventsOnly = true;
5768
5769 // if this is a lightweight component, enable mouse events
5770 // in the native container.
5771 if (peer instanceof LightweightPeer) {
5772 parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5773 }
5774 }
5775
5776 /**
5777 * Removes the specified mouse listener so that it no longer
5778 * receives mouse events from this component. This method performs
5779 * no function, nor does it throw an exception, if the listener
5780 * specified by the argument was not previously added to this component.
5781 * If listener <code>l</code> is <code>null</code>,
5782 * no exception is thrown and no action is performed.
5783 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5784 * >AWT Threading Issues</a> for details on AWT's threading model.
5785 *
5786 * @param l the mouse listener
5787 * @see java.awt.event.MouseEvent
5788 * @see java.awt.event.MouseListener
5789 * @see #addMouseListener
5790 * @see #getMouseListeners
5791 * @since 1.1
5792 */
5793 public synchronized void removeMouseListener(MouseListener l) {
5794 if (l == null) {
5795 return;
5796 }
5797 mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5798 }
5799
5800 /**
5801 * Returns an array of all the mouse listeners
5802 * registered on this component.
5803 *
5804 * @return all of this component's <code>MouseListener</code>s
5805 * or an empty array if no mouse
5806 * listeners are currently registered
5807 *
5808 * @see #addMouseListener
5809 * @see #removeMouseListener
5810 * @since 1.4
5811 */
5812 public synchronized MouseListener[] getMouseListeners() {
5813 return getListeners(MouseListener.class);
5814 }
5815
5816 /**
5817 * Adds the specified mouse motion listener to receive mouse motion
5818 * events from this component.
5819 * If listener <code>l</code> is <code>null</code>,
5820 * no exception is thrown and no action is performed.
5821 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5822 * >AWT Threading Issues</a> for details on AWT's threading model.
5823 *
5824 * @param l the mouse motion listener
5825 * @see java.awt.event.MouseEvent
5826 * @see java.awt.event.MouseMotionListener
5827 * @see #removeMouseMotionListener
5828 * @see #getMouseMotionListeners
5829 * @since 1.1
5830 */
5831 public synchronized void addMouseMotionListener(MouseMotionListener l) {
5832 if (l == null) {
5833 return;
5834 }
5835 mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5836 newEventsOnly = true;
5837
5838 // if this is a lightweight component, enable mouse events
5839 // in the native container.
5840 if (peer instanceof LightweightPeer) {
5841 parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5842 }
5843 }
5844
5845 /**
5846 * Removes the specified mouse motion listener so that it no longer
5847 * receives mouse motion events from this component. This method performs
5848 * no function, nor does it throw an exception, if the listener
5849 * specified by the argument was not previously added to this component.
5850 * If listener <code>l</code> is <code>null</code>,
5851 * no exception is thrown and no action is performed.
5852 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5853 * >AWT Threading Issues</a> for details on AWT's threading model.
5854 *
5855 * @param l the mouse motion listener
5856 * @see java.awt.event.MouseEvent
5857 * @see java.awt.event.MouseMotionListener
5858 * @see #addMouseMotionListener
5859 * @see #getMouseMotionListeners
5860 * @since 1.1
5861 */
5862 public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5863 if (l == null) {
5864 return;
5865 }
5866 mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5867 }
5868
5869 /**
5870 * Returns an array of all the mouse motion listeners
5871 * registered on this component.
5872 *
5873 * @return all of this component's <code>MouseMotionListener</code>s
5874 * or an empty array if no mouse motion
5875 * listeners are currently registered
5876 *
5877 * @see #addMouseMotionListener
5878 * @see #removeMouseMotionListener
5879 * @since 1.4
5880 */
5881 public synchronized MouseMotionListener[] getMouseMotionListeners() {
5882 return getListeners(MouseMotionListener.class);
5883 }
5884
5885 /**
5886 * Adds the specified mouse wheel listener to receive mouse wheel events
5887 * from this component. Containers also receive mouse wheel events from
5888 * sub-components.
5889 * <p>
5890 * For information on how mouse wheel events are dispatched, see
5891 * the class description for {@link MouseWheelEvent}.
5892 * <p>
5893 * If l is <code>null</code>, no exception is thrown and no
5894 * action is performed.
5895 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5896 * >AWT Threading Issues</a> for details on AWT's threading model.
5897 *
5898 * @param l the mouse wheel listener
5899 * @see java.awt.event.MouseWheelEvent
5900 * @see java.awt.event.MouseWheelListener
5901 * @see #removeMouseWheelListener
5902 * @see #getMouseWheelListeners
5903 * @since 1.4
5904 */
5905 public synchronized void addMouseWheelListener(MouseWheelListener l) {
5906 if (l == null) {
5907 return;
5908 }
5909 mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5910 newEventsOnly = true;
5911
5912 // if this is a lightweight component, enable mouse events
5913 // in the native container.
5926 * >AWT Threading Issues</a> for details on AWT's threading model.
5927 *
5928 * @param l the mouse wheel listener.
5929 * @see java.awt.event.MouseWheelEvent
5930 * @see java.awt.event.MouseWheelListener
5931 * @see #addMouseWheelListener
5932 * @see #getMouseWheelListeners
5933 * @since 1.4
5934 */
5935 public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5936 if (l == null) {
5937 return;
5938 }
5939 mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5940 }
5941
5942 /**
5943 * Returns an array of all the mouse wheel listeners
5944 * registered on this component.
5945 *
5946 * @return all of this component's <code>MouseWheelListener</code>s
5947 * or an empty array if no mouse wheel
5948 * listeners are currently registered
5949 *
5950 * @see #addMouseWheelListener
5951 * @see #removeMouseWheelListener
5952 * @since 1.4
5953 */
5954 public synchronized MouseWheelListener[] getMouseWheelListeners() {
5955 return getListeners(MouseWheelListener.class);
5956 }
5957
5958 /**
5959 * Adds the specified input method listener to receive
5960 * input method events from this component. A component will
5961 * only receive input method events from input methods
5962 * if it also overrides <code>getInputMethodRequests</code> to return an
5963 * <code>InputMethodRequests</code> instance.
5964 * If listener <code>l</code> is <code>null</code>,
5965 * no exception is thrown and no action is performed.
5966 * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
5967 * >AWT Threading Issues</a> for details on AWT's threading model.
5968 *
5969 * @param l the input method listener
5970 * @see java.awt.event.InputMethodEvent
5971 * @see java.awt.event.InputMethodListener
5972 * @see #removeInputMethodListener
5973 * @see #getInputMethodListeners
5974 * @see #getInputMethodRequests
5975 * @since 1.2
5976 */
5977 public synchronized void addInputMethodListener(InputMethodListener l) {
5978 if (l == null) {
5979 return;
5980 }
5981 inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5982 newEventsOnly = true;
5983 }
5984
5985 /**
5986 * Removes the specified input method listener so that it no longer
5987 * receives input method events from this component. This method performs
5988 * no function, nor does it throw an exception, if the listener
5989 * specified by the argument was not previously added to this component.
5990 * If listener <code>l</code> is <code>null</code>,
5991 * no exception is thrown and no action is performed.
5992 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5993 * >AWT Threading Issues</a> for details on AWT's threading model.
5994 *
5995 * @param l the input method listener
5996 * @see java.awt.event.InputMethodEvent
5997 * @see java.awt.event.InputMethodListener
5998 * @see #addInputMethodListener
5999 * @see #getInputMethodListeners
6000 * @since 1.2
6001 */
6002 public synchronized void removeInputMethodListener(InputMethodListener l) {
6003 if (l == null) {
6004 return;
6005 }
6006 inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
6007 }
6008
6009 /**
6010 * Returns an array of all the input method listeners
6011 * registered on this component.
6012 *
6013 * @return all of this component's <code>InputMethodListener</code>s
6014 * or an empty array if no input method
6015 * listeners are currently registered
6016 *
6017 * @see #addInputMethodListener
6018 * @see #removeInputMethodListener
6019 * @since 1.4
6020 */
6021 public synchronized InputMethodListener[] getInputMethodListeners() {
6022 return getListeners(InputMethodListener.class);
6023 }
6024
6025 /**
6026 * Returns an array of all the objects currently registered
6027 * as <code><em>Foo</em>Listener</code>s
6028 * upon this <code>Component</code>.
6029 * <code><em>Foo</em>Listener</code>s are registered using the
6030 * <code>add<em>Foo</em>Listener</code> method.
6031 *
6032 * <p>
6033 * You can specify the <code>listenerType</code> argument
6034 * with a class literal, such as
6035 * <code><em>Foo</em>Listener.class</code>.
6036 * For example, you can query a
6037 * <code>Component</code> <code>c</code>
6038 * for its mouse listeners with the following code:
6039 *
6040 * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
6041 *
6042 * If no such listeners exist, this method returns an empty array.
6043 *
6044 * @param <T> the type of the listeners
6045 * @param listenerType the type of listeners requested; this parameter
6046 * should specify an interface that descends from
6047 * <code>java.util.EventListener</code>
6048 * @return an array of all objects registered as
6049 * <code><em>Foo</em>Listener</code>s on this component,
6050 * or an empty array if no such listeners have been added
6051 * @exception ClassCastException if <code>listenerType</code>
6052 * doesn't specify a class or interface that implements
6053 * <code>java.util.EventListener</code>
6054 * @throws NullPointerException if {@code listenerType} is {@code null}
6055 * @see #getComponentListeners
6056 * @see #getFocusListeners
6057 * @see #getHierarchyListeners
6058 * @see #getHierarchyBoundsListeners
6059 * @see #getKeyListeners
6060 * @see #getMouseListeners
6061 * @see #getMouseMotionListeners
6062 * @see #getMouseWheelListeners
6063 * @see #getInputMethodListeners
6064 * @see #getPropertyChangeListeners
6065 *
6066 * @since 1.3
6067 */
6068 @SuppressWarnings("unchecked")
6069 public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
6070 EventListener l = null;
6071 if (listenerType == ComponentListener.class) {
6072 l = componentListener;
6073 } else if (listenerType == FocusListener.class) {
6079 } else if (listenerType == KeyListener.class) {
6080 l = keyListener;
6081 } else if (listenerType == MouseListener.class) {
6082 l = mouseListener;
6083 } else if (listenerType == MouseMotionListener.class) {
6084 l = mouseMotionListener;
6085 } else if (listenerType == MouseWheelListener.class) {
6086 l = mouseWheelListener;
6087 } else if (listenerType == InputMethodListener.class) {
6088 l = inputMethodListener;
6089 } else if (listenerType == PropertyChangeListener.class) {
6090 return (T[])getPropertyChangeListeners();
6091 }
6092 return AWTEventMulticaster.getListeners(l, listenerType);
6093 }
6094
6095 /**
6096 * Gets the input method request handler which supports
6097 * requests from input methods for this component. A component
6098 * that supports on-the-spot text input must override this
6099 * method to return an <code>InputMethodRequests</code> instance.
6100 * At the same time, it also has to handle input method events.
6101 *
6102 * @return the input method request handler for this component,
6103 * <code>null</code> by default
6104 * @see #addInputMethodListener
6105 * @since 1.2
6106 */
6107 public InputMethodRequests getInputMethodRequests() {
6108 return null;
6109 }
6110
6111 /**
6112 * Gets the input context used by this component for handling
6113 * the communication with input methods when text is entered
6114 * in this component. By default, the input context used for
6115 * the parent component is returned. Components may
6116 * override this to return a private input context.
6117 *
6118 * @return the input context used by this component;
6119 * <code>null</code> if no context can be determined
6120 * @since 1.2
6121 */
6122 public InputContext getInputContext() {
6123 Container parent = this.parent;
6124 if (parent == null) {
6125 return null;
6126 } else {
6127 return parent.getInputContext();
6128 }
6129 }
6130
6131 /**
6132 * Enables the events defined by the specified event mask parameter
6133 * to be delivered to this component.
6134 * <p>
6135 * Event types are automatically enabled when a listener for
6136 * that event type is added to the component.
6137 * <p>
6138 * This method only needs to be invoked by subclasses of
6139 * <code>Component</code> which desire to have the specified event
6140 * types delivered to <code>processEvent</code> regardless of whether
6141 * or not a listener is registered.
6142 * @param eventsToEnable the event mask defining the event types
6143 * @see #processEvent
6144 * @see #disableEvents
6145 * @see AWTEvent
6146 * @since 1.1
6147 */
6148 protected final void enableEvents(long eventsToEnable) {
6149 long notifyAncestors = 0;
6150 synchronized (this) {
6151 if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6152 hierarchyListener == null &&
6153 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
6154 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6155 }
6156 if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
6157 hierarchyBoundsListener == null &&
6158 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
6159 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6160 }
6292 clazz.getDeclaredMethod(
6293 "coalesceEvents", coalesceEventsParams
6294 );
6295 return true;
6296 } catch (NoSuchMethodException e) {
6297 // Not present in this class.
6298 return false;
6299 }
6300 }
6301
6302 /**
6303 * Indicates whether coalesceEvents may do something.
6304 */
6305 final boolean isCoalescingEnabled() {
6306 return coalescingEnabled;
6307 }
6308
6309
6310 /**
6311 * Potentially coalesce an event being posted with an existing
6312 * event. This method is called by <code>EventQueue.postEvent</code>
6313 * if an event with the same ID as the event to be posted is found in
6314 * the queue (both events must have this component as their source).
6315 * This method either returns a coalesced event which replaces
6316 * the existing event (and the new event is then discarded), or
6317 * <code>null</code> to indicate that no combining should be done
6318 * (add the second event to the end of the queue). Either event
6319 * parameter may be modified and returned, as the other one is discarded
6320 * unless <code>null</code> is returned.
6321 * <p>
6322 * This implementation of <code>coalesceEvents</code> coalesces
6323 * two event types: mouse move (and drag) events,
6324 * and paint (and update) events.
6325 * For mouse move events the last event is always returned, causing
6326 * intermediate moves to be discarded. For paint events, the new
6327 * event is coalesced into a complex <code>RepaintArea</code> in the peer.
6328 * The new <code>AWTEvent</code> is always returned.
6329 *
6330 * @param existingEvent the event already on the <code>EventQueue</code>
6331 * @param newEvent the event being posted to the
6332 * <code>EventQueue</code>
6333 * @return a coalesced event, or <code>null</code> indicating that no
6334 * coalescing was done
6335 */
6336 protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6337 AWTEvent newEvent) {
6338 return null;
6339 }
6340
6341 /**
6342 * Processes events occurring on this component. By default this
6343 * method calls the appropriate
6344 * <code>process<event type>Event</code>
6345 * method for the given class of event.
6346 * <p>Note that if the event parameter is <code>null</code>
6347 * the behavior is unspecified and may result in an
6348 * exception.
6349 *
6350 * @param e the event
6351 * @see #processComponentEvent
6352 * @see #processFocusEvent
6353 * @see #processKeyEvent
6354 * @see #processMouseEvent
6355 * @see #processMouseMotionEvent
6356 * @see #processInputMethodEvent
6357 * @see #processHierarchyEvent
6358 * @see #processMouseWheelEvent
6359 * @since 1.1
6360 */
6361 protected void processEvent(AWTEvent e) {
6362 if (e instanceof FocusEvent) {
6363 processFocusEvent((FocusEvent)e);
6364
6365 } else if (e instanceof MouseEvent) {
6366 switch(e.getID()) {
6386 } else if (e instanceof ComponentEvent) {
6387 processComponentEvent((ComponentEvent)e);
6388 } else if (e instanceof InputMethodEvent) {
6389 processInputMethodEvent((InputMethodEvent)e);
6390 } else if (e instanceof HierarchyEvent) {
6391 switch (e.getID()) {
6392 case HierarchyEvent.HIERARCHY_CHANGED:
6393 processHierarchyEvent((HierarchyEvent)e);
6394 break;
6395 case HierarchyEvent.ANCESTOR_MOVED:
6396 case HierarchyEvent.ANCESTOR_RESIZED:
6397 processHierarchyBoundsEvent((HierarchyEvent)e);
6398 break;
6399 }
6400 }
6401 }
6402
6403 /**
6404 * Processes component events occurring on this component by
6405 * dispatching them to any registered
6406 * <code>ComponentListener</code> objects.
6407 * <p>
6408 * This method is not called unless component events are
6409 * enabled for this component. Component events are enabled
6410 * when one of the following occurs:
6411 * <ul>
6412 * <li>A <code>ComponentListener</code> object is registered
6413 * via <code>addComponentListener</code>.
6414 * <li>Component events are enabled via <code>enableEvents</code>.
6415 * </ul>
6416 * <p>Note that if the event parameter is <code>null</code>
6417 * the behavior is unspecified and may result in an
6418 * exception.
6419 *
6420 * @param e the component event
6421 * @see java.awt.event.ComponentEvent
6422 * @see java.awt.event.ComponentListener
6423 * @see #addComponentListener
6424 * @see #enableEvents
6425 * @since 1.1
6426 */
6427 protected void processComponentEvent(ComponentEvent e) {
6428 ComponentListener listener = componentListener;
6429 if (listener != null) {
6430 int id = e.getID();
6431 switch(id) {
6432 case ComponentEvent.COMPONENT_RESIZED:
6433 listener.componentResized(e);
6434 break;
6435 case ComponentEvent.COMPONENT_MOVED:
6436 listener.componentMoved(e);
6437 break;
6438 case ComponentEvent.COMPONENT_SHOWN:
6439 listener.componentShown(e);
6440 break;
6441 case ComponentEvent.COMPONENT_HIDDEN:
6442 listener.componentHidden(e);
6443 break;
6444 }
6445 }
6446 }
6447
6448 /**
6449 * Processes focus events occurring on this component by
6450 * dispatching them to any registered
6451 * <code>FocusListener</code> objects.
6452 * <p>
6453 * This method is not called unless focus events are
6454 * enabled for this component. Focus events are enabled
6455 * when one of the following occurs:
6456 * <ul>
6457 * <li>A <code>FocusListener</code> object is registered
6458 * via <code>addFocusListener</code>.
6459 * <li>Focus events are enabled via <code>enableEvents</code>.
6460 * </ul>
6461 * <p>
6462 * If focus events are enabled for a <code>Component</code>,
6463 * the current <code>KeyboardFocusManager</code> determines
6464 * whether or not a focus event should be dispatched to
6465 * registered <code>FocusListener</code> objects. If the
6466 * events are to be dispatched, the <code>KeyboardFocusManager</code>
6467 * calls the <code>Component</code>'s <code>dispatchEvent</code>
6468 * method, which results in a call to the <code>Component</code>'s
6469 * <code>processFocusEvent</code> method.
6470 * <p>
6471 * If focus events are enabled for a <code>Component</code>, calling
6472 * the <code>Component</code>'s <code>dispatchEvent</code> method
6473 * with a <code>FocusEvent</code> as the argument will result in a
6474 * call to the <code>Component</code>'s <code>processFocusEvent</code>
6475 * method regardless of the current <code>KeyboardFocusManager</code>.
6476 *
6477 * <p>Note that if the event parameter is <code>null</code>
6478 * the behavior is unspecified and may result in an
6479 * exception.
6480 *
6481 * @param e the focus event
6482 * @see java.awt.event.FocusEvent
6483 * @see java.awt.event.FocusListener
6484 * @see java.awt.KeyboardFocusManager
6485 * @see #addFocusListener
6486 * @see #enableEvents
6487 * @see #dispatchEvent
6488 * @since 1.1
6489 */
6490 protected void processFocusEvent(FocusEvent e) {
6491 FocusListener listener = focusListener;
6492 if (listener != null) {
6493 int id = e.getID();
6494 switch(id) {
6495 case FocusEvent.FOCUS_GAINED:
6496 listener.focusGained(e);
6497 break;
6498 case FocusEvent.FOCUS_LOST:
6499 listener.focusLost(e);
6500 break;
6501 }
6502 }
6503 }
6504
6505 /**
6506 * Processes key events occurring on this component by
6507 * dispatching them to any registered
6508 * <code>KeyListener</code> objects.
6509 * <p>
6510 * This method is not called unless key events are
6511 * enabled for this component. Key events are enabled
6512 * when one of the following occurs:
6513 * <ul>
6514 * <li>A <code>KeyListener</code> object is registered
6515 * via <code>addKeyListener</code>.
6516 * <li>Key events are enabled via <code>enableEvents</code>.
6517 * </ul>
6518 *
6519 * <p>
6520 * If key events are enabled for a <code>Component</code>,
6521 * the current <code>KeyboardFocusManager</code> determines
6522 * whether or not a key event should be dispatched to
6523 * registered <code>KeyListener</code> objects. The
6524 * <code>DefaultKeyboardFocusManager</code> will not dispatch
6525 * key events to a <code>Component</code> that is not the focus
6526 * owner or is not showing.
6527 * <p>
6528 * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to
6529 * the focus owner. Please see the
6530 * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6531 * for further information.
6532 * <p>
6533 * Calling a <code>Component</code>'s <code>dispatchEvent</code>
6534 * method with a <code>KeyEvent</code> as the argument will
6535 * result in a call to the <code>Component</code>'s
6536 * <code>processKeyEvent</code> method regardless of the
6537 * current <code>KeyboardFocusManager</code> as long as the
6538 * component is showing, focused, and enabled, and key events
6539 * are enabled on it.
6540 * <p>If the event parameter is <code>null</code>
6541 * the behavior is unspecified and may result in an
6542 * exception.
6543 *
6544 * @param e the key event
6545 * @see java.awt.event.KeyEvent
6546 * @see java.awt.event.KeyListener
6547 * @see java.awt.KeyboardFocusManager
6548 * @see java.awt.DefaultKeyboardFocusManager
6549 * @see #processEvent
6550 * @see #dispatchEvent
6551 * @see #addKeyListener
6552 * @see #enableEvents
6553 * @see #isShowing
6554 * @since 1.1
6555 */
6556 protected void processKeyEvent(KeyEvent e) {
6557 KeyListener listener = keyListener;
6558 if (listener != null) {
6559 int id = e.getID();
6560 switch(id) {
6561 case KeyEvent.KEY_TYPED:
6562 listener.keyTyped(e);
6563 break;
6564 case KeyEvent.KEY_PRESSED:
6565 listener.keyPressed(e);
6566 break;
6567 case KeyEvent.KEY_RELEASED:
6568 listener.keyReleased(e);
6569 break;
6570 }
6571 }
6572 }
6573
6574 /**
6575 * Processes mouse events occurring on this component by
6576 * dispatching them to any registered
6577 * <code>MouseListener</code> objects.
6578 * <p>
6579 * This method is not called unless mouse events are
6580 * enabled for this component. Mouse events are enabled
6581 * when one of the following occurs:
6582 * <ul>
6583 * <li>A <code>MouseListener</code> object is registered
6584 * via <code>addMouseListener</code>.
6585 * <li>Mouse events are enabled via <code>enableEvents</code>.
6586 * </ul>
6587 * <p>Note that if the event parameter is <code>null</code>
6588 * the behavior is unspecified and may result in an
6589 * exception.
6590 *
6591 * @param e the mouse event
6592 * @see java.awt.event.MouseEvent
6593 * @see java.awt.event.MouseListener
6594 * @see #addMouseListener
6595 * @see #enableEvents
6596 * @since 1.1
6597 */
6598 protected void processMouseEvent(MouseEvent e) {
6599 MouseListener listener = mouseListener;
6600 if (listener != null) {
6601 int id = e.getID();
6602 switch(id) {
6603 case MouseEvent.MOUSE_PRESSED:
6604 listener.mousePressed(e);
6605 break;
6606 case MouseEvent.MOUSE_RELEASED:
6607 listener.mouseReleased(e);
6608 break;
6609 case MouseEvent.MOUSE_CLICKED:
6610 listener.mouseClicked(e);
6611 break;
6612 case MouseEvent.MOUSE_EXITED:
6613 listener.mouseExited(e);
6614 break;
6615 case MouseEvent.MOUSE_ENTERED:
6616 listener.mouseEntered(e);
6617 break;
6618 }
6619 }
6620 }
6621
6622 /**
6623 * Processes mouse motion events occurring on this component by
6624 * dispatching them to any registered
6625 * <code>MouseMotionListener</code> objects.
6626 * <p>
6627 * This method is not called unless mouse motion events are
6628 * enabled for this component. Mouse motion events are enabled
6629 * when one of the following occurs:
6630 * <ul>
6631 * <li>A <code>MouseMotionListener</code> object is registered
6632 * via <code>addMouseMotionListener</code>.
6633 * <li>Mouse motion events are enabled via <code>enableEvents</code>.
6634 * </ul>
6635 * <p>Note that if the event parameter is <code>null</code>
6636 * the behavior is unspecified and may result in an
6637 * exception.
6638 *
6639 * @param e the mouse motion event
6640 * @see java.awt.event.MouseEvent
6641 * @see java.awt.event.MouseMotionListener
6642 * @see #addMouseMotionListener
6643 * @see #enableEvents
6644 * @since 1.1
6645 */
6646 protected void processMouseMotionEvent(MouseEvent e) {
6647 MouseMotionListener listener = mouseMotionListener;
6648 if (listener != null) {
6649 int id = e.getID();
6650 switch(id) {
6651 case MouseEvent.MOUSE_MOVED:
6652 listener.mouseMoved(e);
6653 break;
6654 case MouseEvent.MOUSE_DRAGGED:
6655 listener.mouseDragged(e);
6656 break;
6657 }
6658 }
6659 }
6660
6661 /**
6662 * Processes mouse wheel events occurring on this component by
6663 * dispatching them to any registered
6664 * <code>MouseWheelListener</code> objects.
6665 * <p>
6666 * This method is not called unless mouse wheel events are
6667 * enabled for this component. Mouse wheel events are enabled
6668 * when one of the following occurs:
6669 * <ul>
6670 * <li>A <code>MouseWheelListener</code> object is registered
6671 * via <code>addMouseWheelListener</code>.
6672 * <li>Mouse wheel events are enabled via <code>enableEvents</code>.
6673 * </ul>
6674 * <p>
6675 * For information on how mouse wheel events are dispatched, see
6676 * the class description for {@link MouseWheelEvent}.
6677 * <p>
6678 * Note that if the event parameter is <code>null</code>
6679 * the behavior is unspecified and may result in an
6680 * exception.
6681 *
6682 * @param e the mouse wheel event
6683 * @see java.awt.event.MouseWheelEvent
6684 * @see java.awt.event.MouseWheelListener
6685 * @see #addMouseWheelListener
6686 * @see #enableEvents
6687 * @since 1.4
6688 */
6689 protected void processMouseWheelEvent(MouseWheelEvent e) {
6690 MouseWheelListener listener = mouseWheelListener;
6691 if (listener != null) {
6692 int id = e.getID();
6693 switch(id) {
6694 case MouseEvent.MOUSE_WHEEL:
6695 listener.mouseWheelMoved(e);
6696 break;
6697 }
6698 }
6699 }
6700
6701 boolean postsOldMouseEvents() {
6702 return false;
6703 }
6704
6705 /**
6706 * Processes input method events occurring on this component by
6707 * dispatching them to any registered
6708 * <code>InputMethodListener</code> objects.
6709 * <p>
6710 * This method is not called unless input method events
6711 * are enabled for this component. Input method events are enabled
6712 * when one of the following occurs:
6713 * <ul>
6714 * <li>An <code>InputMethodListener</code> object is registered
6715 * via <code>addInputMethodListener</code>.
6716 * <li>Input method events are enabled via <code>enableEvents</code>.
6717 * </ul>
6718 * <p>Note that if the event parameter is <code>null</code>
6719 * the behavior is unspecified and may result in an
6720 * exception.
6721 *
6722 * @param e the input method event
6723 * @see java.awt.event.InputMethodEvent
6724 * @see java.awt.event.InputMethodListener
6725 * @see #addInputMethodListener
6726 * @see #enableEvents
6727 * @since 1.2
6728 */
6729 protected void processInputMethodEvent(InputMethodEvent e) {
6730 InputMethodListener listener = inputMethodListener;
6731 if (listener != null) {
6732 int id = e.getID();
6733 switch (id) {
6734 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6735 listener.inputMethodTextChanged(e);
6736 break;
6737 case InputMethodEvent.CARET_POSITION_CHANGED:
6738 listener.caretPositionChanged(e);
6739 break;
6740 }
6741 }
6742 }
6743
6744 /**
6745 * Processes hierarchy events occurring on this component by
6746 * dispatching them to any registered
6747 * <code>HierarchyListener</code> objects.
6748 * <p>
6749 * This method is not called unless hierarchy events
6750 * are enabled for this component. Hierarchy events are enabled
6751 * when one of the following occurs:
6752 * <ul>
6753 * <li>An <code>HierarchyListener</code> object is registered
6754 * via <code>addHierarchyListener</code>.
6755 * <li>Hierarchy events are enabled via <code>enableEvents</code>.
6756 * </ul>
6757 * <p>Note that if the event parameter is <code>null</code>
6758 * the behavior is unspecified and may result in an
6759 * exception.
6760 *
6761 * @param e the hierarchy event
6762 * @see java.awt.event.HierarchyEvent
6763 * @see java.awt.event.HierarchyListener
6764 * @see #addHierarchyListener
6765 * @see #enableEvents
6766 * @since 1.3
6767 */
6768 protected void processHierarchyEvent(HierarchyEvent e) {
6769 HierarchyListener listener = hierarchyListener;
6770 if (listener != null) {
6771 int id = e.getID();
6772 switch (id) {
6773 case HierarchyEvent.HIERARCHY_CHANGED:
6774 listener.hierarchyChanged(e);
6775 break;
6776 }
6777 }
6778 }
6779
6780 /**
6781 * Processes hierarchy bounds events occurring on this component by
6782 * dispatching them to any registered
6783 * <code>HierarchyBoundsListener</code> objects.
6784 * <p>
6785 * This method is not called unless hierarchy bounds events
6786 * are enabled for this component. Hierarchy bounds events are enabled
6787 * when one of the following occurs:
6788 * <ul>
6789 * <li>An <code>HierarchyBoundsListener</code> object is registered
6790 * via <code>addHierarchyBoundsListener</code>.
6791 * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>.
6792 * </ul>
6793 * <p>Note that if the event parameter is <code>null</code>
6794 * the behavior is unspecified and may result in an
6795 * exception.
6796 *
6797 * @param e the hierarchy event
6798 * @see java.awt.event.HierarchyEvent
6799 * @see java.awt.event.HierarchyBoundsListener
6800 * @see #addHierarchyBoundsListener
6801 * @see #enableEvents
6802 * @since 1.3
6803 */
6804 protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6805 HierarchyBoundsListener listener = hierarchyBoundsListener;
6806 if (listener != null) {
6807 int id = e.getID();
6808 switch (id) {
6809 case HierarchyEvent.ANCESTOR_MOVED:
6810 listener.ancestorMoved(e);
6811 break;
6812 case HierarchyEvent.ANCESTOR_RESIZED:
6813 listener.ancestorResized(e);
6960 */
6961 @Deprecated
6962 public boolean keyUp(Event evt, int key) {
6963 return false;
6964 }
6965
6966 /**
6967 * @param evt the event to handle
6968 * @param what the object acted on
6969 * @return {@code false}
6970 * @deprecated As of JDK version 1.1,
6971 * should register this component as ActionListener on component
6972 * which fires action events.
6973 */
6974 @Deprecated
6975 public boolean action(Event evt, Object what) {
6976 return false;
6977 }
6978
6979 /**
6980 * Makes this <code>Component</code> displayable by connecting it to a
6981 * native screen resource.
6982 * This method is called internally by the toolkit and should
6983 * not be called directly by programs.
6984 * <p>
6985 * This method changes layout-related information, and therefore,
6986 * invalidates the component hierarchy.
6987 *
6988 * @see #isDisplayable
6989 * @see #removeNotify
6990 * @see #invalidate
6991 * @since 1.0
6992 */
6993 public void addNotify() {
6994 synchronized (getTreeLock()) {
6995 ComponentPeer peer = this.peer;
6996 if (peer == null || peer instanceof LightweightPeer){
6997 if (peer == null) {
6998 // Update both the Component's peer variable and the local
6999 // variable we use for thread safety.
7000 this.peer = peer = getComponentFactory().createComponent(this);
7064 }
7065
7066 isAddNotifyComplete = true;
7067
7068 if (hierarchyListener != null ||
7069 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7070 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7071 HierarchyEvent e =
7072 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7073 this, parent,
7074 HierarchyEvent.DISPLAYABILITY_CHANGED |
7075 ((isRecursivelyVisible())
7076 ? HierarchyEvent.SHOWING_CHANGED
7077 : 0));
7078 dispatchEvent(e);
7079 }
7080 }
7081 }
7082
7083 /**
7084 * Makes this <code>Component</code> undisplayable by destroying it native
7085 * screen resource.
7086 * <p>
7087 * This method is called by the toolkit internally and should
7088 * not be called directly by programs. Code overriding
7089 * this method should call <code>super.removeNotify</code> as
7090 * the first line of the overriding method.
7091 *
7092 * @see #isDisplayable
7093 * @see #addNotify
7094 * @since 1.0
7095 */
7096 public void removeNotify() {
7097 KeyboardFocusManager.clearMostRecentFocusOwner(this);
7098 if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
7099 getPermanentFocusOwner() == this)
7100 {
7101 KeyboardFocusManager.getCurrentKeyboardFocusManager().
7102 setGlobalPermanentFocusOwner(null);
7103 }
7104
7105 synchronized (getTreeLock()) {
7106 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
7107 transferFocus(true);
7108 }
7109
7181 * replaced by processFocusEvent(FocusEvent).
7182 */
7183 @Deprecated
7184 public boolean gotFocus(Event evt, Object what) {
7185 return false;
7186 }
7187
7188 /**
7189 * @param evt the event to handle
7190 * @param what the object focused
7191 * @return {@code false}
7192 * @deprecated As of JDK version 1.1,
7193 * replaced by processFocusEvent(FocusEvent).
7194 */
7195 @Deprecated
7196 public boolean lostFocus(Event evt, Object what) {
7197 return false;
7198 }
7199
7200 /**
7201 * Returns whether this <code>Component</code> can become the focus
7202 * owner.
7203 *
7204 * @return <code>true</code> if this <code>Component</code> is
7205 * focusable; <code>false</code> otherwise
7206 * @see #setFocusable
7207 * @since 1.1
7208 * @deprecated As of 1.4, replaced by <code>isFocusable()</code>.
7209 */
7210 @Deprecated
7211 public boolean isFocusTraversable() {
7212 if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
7213 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
7214 }
7215 return focusable;
7216 }
7217
7218 /**
7219 * Returns whether this Component can be focused.
7220 *
7221 * @return <code>true</code> if this Component is focusable;
7222 * <code>false</code> otherwise.
7223 * @see #setFocusable
7224 * @since 1.4
7225 */
7226 public boolean isFocusable() {
7227 return isFocusTraversable();
7228 }
7229
7230 /**
7231 * Sets the focusable state of this Component to the specified value. This
7232 * value overrides the Component's default focusability.
7233 *
7234 * @param focusable indicates whether this Component is focusable
7235 * @see #isFocusable
7236 * @since 1.4
7237 * @beaninfo
7238 * bound: true
7239 */
7240 public void setFocusable(boolean focusable) {
7241 boolean oldFocusable;
7242 synchronized (this) {
7326 * contains null, or if any keystroke represents a KEY_TYPED event,
7327 * or if any keystroke already maps to another focus traversal
7328 * operation for this Component
7329 * @since 1.4
7330 * @beaninfo
7331 * bound: true
7332 */
7333 public void setFocusTraversalKeys(int id,
7334 Set<? extends AWTKeyStroke> keystrokes)
7335 {
7336 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7337 throw new IllegalArgumentException("invalid focus traversal key identifier");
7338 }
7339
7340 setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7341 }
7342
7343 /**
7344 * Returns the Set of focus traversal keys for a given traversal operation
7345 * for this Component. (See
7346 * <code>setFocusTraversalKeys</code> for a full description of each key.)
7347 * <p>
7348 * If a Set of traversal keys has not been explicitly defined for this
7349 * Component, then this Component's parent's Set is returned. If no Set
7350 * has been explicitly defined for any of this Component's ancestors, then
7351 * the current KeyboardFocusManager's default Set is returned.
7352 *
7353 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7354 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7355 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7356 * @return the Set of AWTKeyStrokes for the specified operation. The Set
7357 * will be unmodifiable, and may be empty. null will never be
7358 * returned.
7359 * @see #setFocusTraversalKeys
7360 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7361 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7362 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7363 * @throws IllegalArgumentException if id is not one of
7364 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7365 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7366 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7426 Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)
7427 ? focusTraversalKeys[id]
7428 : null;
7429
7430 if (keystrokes != null) {
7431 return keystrokes;
7432 } else {
7433 Container parent = this.parent;
7434 if (parent != null) {
7435 return parent.getFocusTraversalKeys(id);
7436 } else {
7437 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7438 getDefaultFocusTraversalKeys(id);
7439 }
7440 }
7441 }
7442
7443 /**
7444 * Returns whether the Set of focus traversal keys for the given focus
7445 * traversal operation has been explicitly defined for this Component. If
7446 * this method returns <code>false</code>, this Component is inheriting the
7447 * Set from an ancestor, or from the current KeyboardFocusManager.
7448 *
7449 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7450 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7451 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7452 * @return <code>true</code> if the Set of focus traversal keys for the
7453 * given focus traversal operation has been explicitly defined for
7454 * this Component; <code>false</code> otherwise.
7455 * @throws IllegalArgumentException if id is not one of
7456 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7457 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7458 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7459 * @since 1.4
7460 */
7461 public boolean areFocusTraversalKeysSet(int id) {
7462 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7463 throw new IllegalArgumentException("invalid focus traversal key identifier");
7464 }
7465
7466 return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7467 }
7468
7469 /**
7470 * Sets whether focus traversal keys are enabled for this Component.
7471 * Components for which focus traversal keys are disabled receive key
7472 * events for focus traversal keys. Components for which focus traversal
7473 * keys are enabled do not see these events; instead, the events are
7474 * automatically converted to traversal operations.
7509 */
7510 public boolean getFocusTraversalKeysEnabled() {
7511 return focusTraversalKeysEnabled;
7512 }
7513
7514 /**
7515 * Requests that this Component get the input focus, and that this
7516 * Component's top-level ancestor become the focused Window. This
7517 * component must be displayable, focusable, visible and all of
7518 * its ancestors (with the exception of the top-level Window) must
7519 * be visible for the request to be granted. Every effort will be
7520 * made to honor the request; however, in some cases it may be
7521 * impossible to do so. Developers must never assume that this
7522 * Component is the focus owner until this Component receives a
7523 * FOCUS_GAINED event. If this request is denied because this
7524 * Component's top-level Window cannot become the focused Window,
7525 * the request will be remembered and will be granted when the
7526 * Window is later focused by the user.
7527 * <p>
7528 * This method cannot be used to set the focus owner to no Component at
7529 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7530 * instead.
7531 * <p>
7532 * Because the focus behavior of this method is platform-dependent,
7533 * developers are strongly encouraged to use
7534 * <code>requestFocusInWindow</code> when possible.
7535 *
7536 * <p>Note: Not all focus transfers result from invoking this method. As
7537 * such, a component may receive focus without this or any of the other
7538 * {@code requestFocus} methods of {@code Component} being invoked.
7539 *
7540 * @see #requestFocusInWindow
7541 * @see java.awt.event.FocusEvent
7542 * @see #addFocusListener
7543 * @see #isFocusable
7544 * @see #isDisplayable
7545 * @see KeyboardFocusManager#clearGlobalFocusOwner
7546 * @since 1.0
7547 */
7548 public void requestFocus() {
7549 requestFocusHelper(false, true);
7550 }
7551
7552 boolean requestFocus(CausedFocusEvent.Cause cause) {
7553 return requestFocusHelper(false, true, cause);
7554 }
7555
7556 /**
7557 * Requests that this <code>Component</code> get the input focus,
7558 * and that this <code>Component</code>'s top-level ancestor
7559 * become the focused <code>Window</code>. This component must be
7560 * displayable, focusable, visible and all of its ancestors (with
7561 * the exception of the top-level Window) must be visible for the
7562 * request to be granted. Every effort will be made to honor the
7563 * request; however, in some cases it may be impossible to do
7564 * so. Developers must never assume that this component is the
7565 * focus owner until this component receives a FOCUS_GAINED
7566 * event. If this request is denied because this component's
7567 * top-level window cannot become the focused window, the request
7568 * will be remembered and will be granted when the window is later
7569 * focused by the user.
7570 * <p>
7571 * This method returns a boolean value. If <code>false</code> is returned,
7572 * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7573 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7574 * extraordinary event, such as disposal of the component's peer, occurs
7575 * before the request can be granted by the native windowing system. Again,
7576 * while a return value of <code>true</code> indicates that the request is
7577 * likely to succeed, developers must never assume that this component is
7578 * the focus owner until this component receives a FOCUS_GAINED event.
7579 * <p>
7580 * This method cannot be used to set the focus owner to no component at
7581 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7582 * instead.
7583 * <p>
7584 * Because the focus behavior of this method is platform-dependent,
7585 * developers are strongly encouraged to use
7586 * <code>requestFocusInWindow</code> when possible.
7587 * <p>
7588 * Every effort will be made to ensure that <code>FocusEvent</code>s
7589 * generated as a
7590 * result of this request will have the specified temporary value. However,
7591 * because specifying an arbitrary temporary state may not be implementable
7592 * on all native windowing systems, correct behavior for this method can be
7593 * guaranteed only for lightweight <code>Component</code>s.
7594 * This method is not intended
7595 * for general use, but exists instead as a hook for lightweight component
7596 * libraries, such as Swing.
7597 *
7598 * <p>Note: Not all focus transfers result from invoking this method. As
7599 * such, a component may receive focus without this or any of the other
7600 * {@code requestFocus} methods of {@code Component} being invoked.
7601 *
7602 * @param temporary true if the focus change is temporary,
7603 * such as when the window loses the focus; for
7604 * more information on temporary focus changes see the
7605 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7606 * @return <code>false</code> if the focus change request is guaranteed to
7607 * fail; <code>true</code> if it is likely to succeed
7608 * @see java.awt.event.FocusEvent
7609 * @see #addFocusListener
7610 * @see #isFocusable
7611 * @see #isDisplayable
7612 * @see KeyboardFocusManager#clearGlobalFocusOwner
7613 * @since 1.4
7614 */
7615 protected boolean requestFocus(boolean temporary) {
7616 return requestFocusHelper(temporary, true);
7617 }
7618
7619 boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {
7620 return requestFocusHelper(temporary, true, cause);
7621 }
7622 /**
7623 * Requests that this Component get the input focus, if this
7624 * Component's top-level ancestor is already the focused
7625 * Window. This component must be displayable, focusable, visible
7626 * and all of its ancestors (with the exception of the top-level
7627 * Window) must be visible for the request to be granted. Every
7628 * effort will be made to honor the request; however, in some
7629 * cases it may be impossible to do so. Developers must never
7630 * assume that this Component is the focus owner until this
7631 * Component receives a FOCUS_GAINED event.
7632 * <p>
7633 * This method returns a boolean value. If <code>false</code> is returned,
7634 * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7635 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7636 * extraordinary event, such as disposal of the Component's peer, occurs
7637 * before the request can be granted by the native windowing system. Again,
7638 * while a return value of <code>true</code> indicates that the request is
7639 * likely to succeed, developers must never assume that this Component is
7640 * the focus owner until this Component receives a FOCUS_GAINED event.
7641 * <p>
7642 * This method cannot be used to set the focus owner to no Component at
7643 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code>
7644 * instead.
7645 * <p>
7646 * The focus behavior of this method can be implemented uniformly across
7647 * platforms, and thus developers are strongly encouraged to use this
7648 * method over <code>requestFocus</code> when possible. Code which relies
7649 * on <code>requestFocus</code> may exhibit different focus behavior on
7650 * different platforms.
7651 *
7652 * <p>Note: Not all focus transfers result from invoking this method. As
7653 * such, a component may receive focus without this or any of the other
7654 * {@code requestFocus} methods of {@code Component} being invoked.
7655 *
7656 * @return <code>false</code> if the focus change request is guaranteed to
7657 * fail; <code>true</code> if it is likely to succeed
7658 * @see #requestFocus
7659 * @see java.awt.event.FocusEvent
7660 * @see #addFocusListener
7661 * @see #isFocusable
7662 * @see #isDisplayable
7663 * @see KeyboardFocusManager#clearGlobalFocusOwner
7664 * @since 1.4
7665 */
7666 public boolean requestFocusInWindow() {
7667 return requestFocusHelper(false, false);
7668 }
7669
7670 boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {
7671 return requestFocusHelper(false, false, cause);
7672 }
7673
7674 /**
7675 * Requests that this <code>Component</code> get the input focus,
7676 * if this <code>Component</code>'s top-level ancestor is already
7677 * the focused <code>Window</code>. This component must be
7678 * displayable, focusable, visible and all of its ancestors (with
7679 * the exception of the top-level Window) must be visible for the
7680 * request to be granted. Every effort will be made to honor the
7681 * request; however, in some cases it may be impossible to do
7682 * so. Developers must never assume that this component is the
7683 * focus owner until this component receives a FOCUS_GAINED event.
7684 * <p>
7685 * This method returns a boolean value. If <code>false</code> is returned,
7686 * the request is <b>guaranteed to fail</b>. If <code>true</code> is
7687 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7688 * extraordinary event, such as disposal of the component's peer, occurs
7689 * before the request can be granted by the native windowing system. Again,
7690 * while a return value of <code>true</code> indicates that the request is
7691 * likely to succeed, developers must never assume that this component is
7692 * the focus owner until this component receives a FOCUS_GAINED event.
7693 * <p>
7694 * This method cannot be used to set the focus owner to no component at
7695 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code>
7696 * instead.
7697 * <p>
7698 * The focus behavior of this method can be implemented uniformly across
7699 * platforms, and thus developers are strongly encouraged to use this
7700 * method over <code>requestFocus</code> when possible. Code which relies
7701 * on <code>requestFocus</code> may exhibit different focus behavior on
7702 * different platforms.
7703 * <p>
7704 * Every effort will be made to ensure that <code>FocusEvent</code>s
7705 * generated as a
7706 * result of this request will have the specified temporary value. However,
7707 * because specifying an arbitrary temporary state may not be implementable
7708 * on all native windowing systems, correct behavior for this method can be
7709 * guaranteed only for lightweight components. This method is not intended
7710 * for general use, but exists instead as a hook for lightweight component
7711 * libraries, such as Swing.
7712 *
7713 * <p>Note: Not all focus transfers result from invoking this method. As
7714 * such, a component may receive focus without this or any of the other
7715 * {@code requestFocus} methods of {@code Component} being invoked.
7716 *
7717 * @param temporary true if the focus change is temporary,
7718 * such as when the window loses the focus; for
7719 * more information on temporary focus changes see the
7720 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7721 * @return <code>false</code> if the focus change request is guaranteed to
7722 * fail; <code>true</code> if it is likely to succeed
7723 * @see #requestFocus
7724 * @see java.awt.event.FocusEvent
7725 * @see #addFocusListener
7726 * @see #isFocusable
7727 * @see #isDisplayable
7728 * @see KeyboardFocusManager#clearGlobalFocusOwner
7729 * @since 1.4
7730 */
7731 protected boolean requestFocusInWindow(boolean temporary) {
7732 return requestFocusHelper(temporary, false);
7733 }
7734
7735 boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {
7736 return requestFocusHelper(temporary, false, cause);
7737 }
7738
7739 final boolean requestFocusHelper(boolean temporary,
7740 boolean focusedWindowChangeAllowed) {
7741 return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);
7742 }
7937 *
7938 * @return this Component's nearest focus-cycle-root ancestor
7939 * @see Container#isFocusCycleRoot()
7940 * @since 1.4
7941 */
7942 public Container getFocusCycleRootAncestor() {
7943 Container rootAncestor = this.parent;
7944 while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {
7945 rootAncestor = rootAncestor.parent;
7946 }
7947 return rootAncestor;
7948 }
7949
7950 /**
7951 * Returns whether the specified Container is the focus cycle root of this
7952 * Component's focus traversal cycle. Each focus traversal cycle has only
7953 * a single focus cycle root and each Component which is not a Container
7954 * belongs to only a single focus traversal cycle.
7955 *
7956 * @param container the Container to be tested
7957 * @return <code>true</code> if the specified Container is a focus-cycle-
7958 * root of this Component; <code>false</code> otherwise
7959 * @see Container#isFocusCycleRoot()
7960 * @since 1.4
7961 */
7962 public boolean isFocusCycleRoot(Container container) {
7963 Container rootAncestor = getFocusCycleRootAncestor();
7964 return (rootAncestor == container);
7965 }
7966
7967 Container getTraversalRoot() {
7968 return getFocusCycleRootAncestor();
7969 }
7970
7971 /**
7972 * Transfers the focus to the next component, as though this Component were
7973 * the focus owner.
7974 * @see #requestFocus()
7975 * @since 1.1
7976 */
7977 public void transferFocus() {
7978 nextFocus();
8119
8120 KeyboardFocusManager.getCurrentKeyboardFocusManager().
8121 setGlobalCurrentFocusCycleRootPriv(fcr);
8122 rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
8123 } else {
8124 Window window = getContainingWindow();
8125
8126 if (window != null) {
8127 Component toFocus = window.getFocusTraversalPolicy().
8128 getDefaultComponent(window);
8129 if (toFocus != null) {
8130 KeyboardFocusManager.getCurrentKeyboardFocusManager().
8131 setGlobalCurrentFocusCycleRootPriv(window);
8132 toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
8133 }
8134 }
8135 }
8136 }
8137
8138 /**
8139 * Returns <code>true</code> if this <code>Component</code> is the
8140 * focus owner. This method is obsolete, and has been replaced by
8141 * <code>isFocusOwner()</code>.
8142 *
8143 * @return <code>true</code> if this <code>Component</code> is the
8144 * focus owner; <code>false</code> otherwise
8145 * @since 1.2
8146 */
8147 public boolean hasFocus() {
8148 return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
8149 getFocusOwner() == this);
8150 }
8151
8152 /**
8153 * Returns <code>true</code> if this <code>Component</code> is the
8154 * focus owner.
8155 *
8156 * @return <code>true</code> if this <code>Component</code> is the
8157 * focus owner; <code>false</code> otherwise
8158 * @since 1.4
8159 */
8160 public boolean isFocusOwner() {
8161 return hasFocus();
8162 }
8163
8164 /*
8165 * Used to disallow auto-focus-transfer on disposal of the focus owner
8166 * in the process of disposing its parent container.
8167 */
8168 private boolean autoFocusTransferOnDisposal = true;
8169
8170 void setAutoFocusTransferOnDisposal(boolean value) {
8171 autoFocusTransferOnDisposal = value;
8172 }
8173
8174 boolean isAutoFocusTransferOnDisposal() {
8175 return autoFocusTransferOnDisposal;
8176 }
8177
8216 int index = popups.indexOf(popup);
8217 if (index >= 0) {
8218 PopupMenu pmenu = (PopupMenu)popup;
8219 if (pmenu.peer != null) {
8220 pmenu.removeNotify();
8221 }
8222 pmenu.parent = null;
8223 popups.removeElementAt(index);
8224 if (popups.size() == 0) {
8225 popups = null;
8226 }
8227 }
8228 }
8229 }
8230
8231 /**
8232 * Returns a string representing the state of this component. This
8233 * method is intended to be used only for debugging purposes, and the
8234 * content and format of the returned string may vary between
8235 * implementations. The returned string may be empty but may not be
8236 * <code>null</code>.
8237 *
8238 * @return a string representation of this component's state
8239 * @since 1.0
8240 */
8241 protected String paramString() {
8242 final String thisName = Objects.toString(getName(), "");
8243 final String invalid = isValid() ? "" : ",invalid";
8244 final String hidden = visible ? "" : ",hidden";
8245 final String disabled = enabled ? "" : ",disabled";
8246 return thisName + ',' + x + ',' + y + ',' + width + 'x' + height
8247 + invalid + hidden + disabled;
8248 }
8249
8250 /**
8251 * Returns a string representation of this component and its values.
8252 * @return a string representation of this component
8253 * @since 1.0
8254 */
8255 public String toString() {
8256 return getClass().getName() + '[' + paramString() + ']';
8257 }
8258
8259 /**
8260 * Prints a listing of this component to the standard system output
8261 * stream <code>System.out</code>.
8262 * @see java.lang.System#out
8263 * @since 1.0
8264 */
8265 public void list() {
8266 list(System.out, 0);
8267 }
8268
8269 /**
8270 * Prints a listing of this component to the specified output
8271 * stream.
8272 * @param out a print stream
8273 * @throws NullPointerException if {@code out} is {@code null}
8274 * @since 1.0
8275 */
8276 public void list(PrintStream out) {
8277 list(out, 0);
8278 }
8279
8280 /**
8281 * Prints out a list, starting at the specified indentation, to the
8336 * registered for all bound properties of this class, including the
8337 * following:
8338 * <ul>
8339 * <li>this Component's font ("font")</li>
8340 * <li>this Component's background color ("background")</li>
8341 * <li>this Component's foreground color ("foreground")</li>
8342 * <li>this Component's focusability ("focusable")</li>
8343 * <li>this Component's focus traversal keys enabled state
8344 * ("focusTraversalKeysEnabled")</li>
8345 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8346 * ("forwardFocusTraversalKeys")</li>
8347 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8348 * ("backwardFocusTraversalKeys")</li>
8349 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8350 * ("upCycleFocusTraversalKeys")</li>
8351 * <li>this Component's preferred size ("preferredSize")</li>
8352 * <li>this Component's minimum size ("minimumSize")</li>
8353 * <li>this Component's maximum size ("maximumSize")</li>
8354 * <li>this Component's name ("name")</li>
8355 * </ul>
8356 * Note that if this <code>Component</code> is inheriting a bound property, then no
8357 * event will be fired in response to a change in the inherited property.
8358 * <p>
8359 * If <code>listener</code> is <code>null</code>,
8360 * no exception is thrown and no action is performed.
8361 *
8362 * @param listener the property change listener to be added
8363 *
8364 * @see #removePropertyChangeListener
8365 * @see #getPropertyChangeListeners
8366 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8367 */
8368 public void addPropertyChangeListener(
8369 PropertyChangeListener listener) {
8370 synchronized (getObjectLock()) {
8371 if (listener == null) {
8372 return;
8373 }
8374 if (changeSupport == null) {
8375 changeSupport = new PropertyChangeSupport(this);
8376 }
8377 changeSupport.addPropertyChangeListener(listener);
8378 }
8379 }
8388 * @param listener the PropertyChangeListener to be removed
8389 *
8390 * @see #addPropertyChangeListener
8391 * @see #getPropertyChangeListeners
8392 * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
8393 */
8394 public void removePropertyChangeListener(
8395 PropertyChangeListener listener) {
8396 synchronized (getObjectLock()) {
8397 if (listener == null || changeSupport == null) {
8398 return;
8399 }
8400 changeSupport.removePropertyChangeListener(listener);
8401 }
8402 }
8403
8404 /**
8405 * Returns an array of all the property change listeners
8406 * registered on this component.
8407 *
8408 * @return all of this component's <code>PropertyChangeListener</code>s
8409 * or an empty array if no property change
8410 * listeners are currently registered
8411 *
8412 * @see #addPropertyChangeListener
8413 * @see #removePropertyChangeListener
8414 * @see #getPropertyChangeListeners(java.lang.String)
8415 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners
8416 * @since 1.4
8417 */
8418 public PropertyChangeListener[] getPropertyChangeListeners() {
8419 synchronized (getObjectLock()) {
8420 if (changeSupport == null) {
8421 return new PropertyChangeListener[0];
8422 }
8423 return changeSupport.getPropertyChangeListeners();
8424 }
8425 }
8426
8427 /**
8428 * Adds a PropertyChangeListener to the listener list for a specific
8429 * property. The specified property may be user-defined, or one of the
8430 * following:
8431 * <ul>
8432 * <li>this Component's font ("font")</li>
8433 * <li>this Component's background color ("background")</li>
8434 * <li>this Component's foreground color ("foreground")</li>
8435 * <li>this Component's focusability ("focusable")</li>
8436 * <li>this Component's focus traversal keys enabled state
8437 * ("focusTraversalKeysEnabled")</li>
8438 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8439 * ("forwardFocusTraversalKeys")</li>
8440 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8441 * ("backwardFocusTraversalKeys")</li>
8442 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8443 * ("upCycleFocusTraversalKeys")</li>
8444 * </ul>
8445 * Note that if this <code>Component</code> is inheriting a bound property, then no
8446 * event will be fired in response to a change in the inherited property.
8447 * <p>
8448 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8449 * no exception is thrown and no action is taken.
8450 *
8451 * @param propertyName one of the property names listed above
8452 * @param listener the property change listener to be added
8453 *
8454 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8455 * @see #getPropertyChangeListeners(java.lang.String)
8456 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8457 */
8458 public void addPropertyChangeListener(
8459 String propertyName,
8460 PropertyChangeListener listener) {
8461 synchronized (getObjectLock()) {
8462 if (listener == null) {
8463 return;
8464 }
8465 if (changeSupport == null) {
8466 changeSupport = new PropertyChangeSupport(this);
8467 }
8468 changeSupport.addPropertyChangeListener(propertyName, listener);
8469 }
8470 }
8471
8472 /**
8473 * Removes a <code>PropertyChangeListener</code> from the listener
8474 * list for a specific property. This method should be used to remove
8475 * <code>PropertyChangeListener</code>s
8476 * that were registered for a specific bound property.
8477 * <p>
8478 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>,
8479 * no exception is thrown and no action is taken.
8480 *
8481 * @param propertyName a valid property name
8482 * @param listener the PropertyChangeListener to be removed
8483 *
8484 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8485 * @see #getPropertyChangeListeners(java.lang.String)
8486 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
8487 */
8488 public void removePropertyChangeListener(
8489 String propertyName,
8490 PropertyChangeListener listener) {
8491 synchronized (getObjectLock()) {
8492 if (listener == null || changeSupport == null) {
8493 return;
8494 }
8495 changeSupport.removePropertyChangeListener(propertyName, listener);
8496 }
8497 }
8498
8499 /**
8500 * Returns an array of all the listeners which have been associated
8501 * with the named property.
8502 *
8503 * @param propertyName the property name
8504 * @return all of the <code>PropertyChangeListener</code>s associated with
8505 * the named property; if no such listeners have been added or
8506 * if <code>propertyName</code> is <code>null</code>, an empty
8507 * array is returned
8508 *
8509 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8510 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8511 * @see #getPropertyChangeListeners
8512 * @since 1.4
8513 */
8514 public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
8515 synchronized (getObjectLock()) {
8516 if (changeSupport == null) {
8517 return new PropertyChangeListener[0];
8518 }
8519 return changeSupport.getPropertyChangeListeners(propertyName);
8520 }
8521 }
8522
8523 /**
8524 * Support for reporting bound property changes for Object properties.
8525 * This method can be called when a bound property has changed and it will
8526 * send the appropriate PropertyChangeEvent to any registered
8687 */
8688 public void firePropertyChange(String propertyName, double oldValue, double newValue) {
8689 if (changeSupport == null || oldValue == newValue) {
8690 return;
8691 }
8692 firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));
8693 }
8694
8695
8696 // Serialization support.
8697
8698 /**
8699 * Component Serialized Data Version.
8700 *
8701 * @serial
8702 */
8703 private int componentSerializedDataVersion = 4;
8704
8705 /**
8706 * This hack is for Swing serialization. It will invoke
8707 * the Swing package private method <code>compWriteObjectNotify</code>.
8708 */
8709 private void doSwingSerialization() {
8710 Package swingPackage = Package.getPackage("javax.swing");
8711 // For Swing serialization to correctly work Swing needs to
8712 // be notified before Component does it's serialization. This
8713 // hack accommodates this.
8714 //
8715 // Swing classes MUST be loaded by the bootstrap class loader,
8716 // otherwise we don't consider them.
8717 for (Class<?> klass = Component.this.getClass(); klass != null;
8718 klass = klass.getSuperclass()) {
8719 if (klass.getPackage() == swingPackage &&
8720 klass.getClassLoader() == null) {
8721 final Class<?> swingClass = klass;
8722 // Find the first override of the compWriteObjectNotify method
8723 Method[] methods = AccessController.doPrivileged(
8724 new PrivilegedAction<Method[]>() {
8725 public Method[] run() {
8726 return swingClass.getDeclaredMethods();
8727 }
8741 // Invoke the method
8742 try {
8743 method.invoke(this, (Object[]) null);
8744 } catch (IllegalAccessException iae) {
8745 } catch (InvocationTargetException ite) {
8746 }
8747 // We're done, bail.
8748 return;
8749 }
8750 }
8751 }
8752 }
8753 }
8754
8755 /**
8756 * Writes default serializable fields to stream. Writes
8757 * a variety of serializable listeners as optional data.
8758 * The non-serializable listeners are detected and
8759 * no attempt is made to serialize them.
8760 *
8761 * @param s the <code>ObjectOutputStream</code> to write
8762 * @serialData <code>null</code> terminated sequence of
8763 * 0 or more pairs; the pair consists of a <code>String</code>
8764 * and an <code>Object</code>; the <code>String</code> indicates
8765 * the type of object and is one of the following (as of 1.4):
8766 * <code>componentListenerK</code> indicating an
8767 * <code>ComponentListener</code> object;
8768 * <code>focusListenerK</code> indicating an
8769 * <code>FocusListener</code> object;
8770 * <code>keyListenerK</code> indicating an
8771 * <code>KeyListener</code> object;
8772 * <code>mouseListenerK</code> indicating an
8773 * <code>MouseListener</code> object;
8774 * <code>mouseMotionListenerK</code> indicating an
8775 * <code>MouseMotionListener</code> object;
8776 * <code>inputMethodListenerK</code> indicating an
8777 * <code>InputMethodListener</code> object;
8778 * <code>hierarchyListenerK</code> indicating an
8779 * <code>HierarchyListener</code> object;
8780 * <code>hierarchyBoundsListenerK</code> indicating an
8781 * <code>HierarchyBoundsListener</code> object;
8782 * <code>mouseWheelListenerK</code> indicating an
8783 * <code>MouseWheelListener</code> object
8784 * @serialData an optional <code>ComponentOrientation</code>
8785 * (after <code>inputMethodListener</code>, as of 1.2)
8786 *
8787 * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
8788 * @see #componentListenerK
8789 * @see #focusListenerK
8790 * @see #keyListenerK
8791 * @see #mouseListenerK
8792 * @see #mouseMotionListenerK
8793 * @see #inputMethodListenerK
8794 * @see #hierarchyListenerK
8795 * @see #hierarchyBoundsListenerK
8796 * @see #mouseWheelListenerK
8797 * @see #readObject(ObjectInputStream)
8798 */
8799 private void writeObject(ObjectOutputStream s)
8800 throws IOException
8801 {
8802 doSwingSerialization();
8803
8804 s.defaultWriteObject();
8805
8807 AWTEventMulticaster.save(s, focusListenerK, focusListener);
8808 AWTEventMulticaster.save(s, keyListenerK, keyListener);
8809 AWTEventMulticaster.save(s, mouseListenerK, mouseListener);
8810 AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);
8811 AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);
8812
8813 s.writeObject(null);
8814 s.writeObject(componentOrientation);
8815
8816 AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);
8817 AWTEventMulticaster.save(s, hierarchyBoundsListenerK,
8818 hierarchyBoundsListener);
8819 s.writeObject(null);
8820
8821 AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);
8822 s.writeObject(null);
8823
8824 }
8825
8826 /**
8827 * Reads the <code>ObjectInputStream</code> and if it isn't
8828 * <code>null</code> adds a listener to receive a variety
8829 * of events fired by the component.
8830 * Unrecognized keys or values will be ignored.
8831 *
8832 * @param s the <code>ObjectInputStream</code> to read
8833 * @see #writeObject(ObjectOutputStream)
8834 */
8835 private void readObject(ObjectInputStream s)
8836 throws ClassNotFoundException, IOException
8837 {
8838 objectLock = new Object();
8839
8840 acc = AccessController.getContext();
8841
8842 s.defaultReadObject();
8843
8844 appContext = AppContext.getAppContext();
8845 coalescingEnabled = checkCoalescing();
8846 if (componentSerializedDataVersion < 4) {
8847 // These fields are non-transient and rely on default
8848 // serialization. However, the default values are insufficient,
8849 // so we need to set them explicitly for object data streams prior
8850 // to 1.4.
8851 focusable = true;
8852 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
8954 // might have been caused by reasons unrelated to
8955 // mouse wheel listeners
8956
8957 if (!e.eof) {
8958 throw (e);
8959 }
8960 }
8961
8962 if (popups != null) {
8963 int npopups = popups.size();
8964 for (int i = 0 ; i < npopups ; i++) {
8965 PopupMenu popup = popups.elementAt(i);
8966 popup.parent = this;
8967 }
8968 }
8969 }
8970
8971 /**
8972 * Sets the language-sensitive orientation that is to be used to order
8973 * the elements or text within this component. Language-sensitive
8974 * <code>LayoutManager</code> and <code>Component</code>
8975 * subclasses will use this property to
8976 * determine how to lay out and draw components.
8977 * <p>
8978 * At construction time, a component's orientation is set to
8979 * <code>ComponentOrientation.UNKNOWN</code>,
8980 * indicating that it has not been specified
8981 * explicitly. The UNKNOWN orientation behaves the same as
8982 * <code>ComponentOrientation.LEFT_TO_RIGHT</code>.
8983 * <p>
8984 * To set the orientation of a single component, use this method.
8985 * To set the orientation of an entire component
8986 * hierarchy, use
8987 * {@link #applyComponentOrientation applyComponentOrientation}.
8988 * <p>
8989 * This method changes layout-related information, and therefore,
8990 * invalidates the component hierarchy.
8991 *
8992 * @param o the orientation to be set
8993 *
8994 * @see ComponentOrientation
8995 * @see #invalidate
8996 *
8997 * @author Laura Werner, IBM
8998 * @beaninfo
8999 * bound: true
9000 */
9001 public void setComponentOrientation(ComponentOrientation o) {
9002 ComponentOrientation oldValue = componentOrientation;
9003 componentOrientation = o;
9004
9005 // This is a bound property, so report the change to
9006 // any registered listeners. (Cheap if there are none.)
9007 firePropertyChange("componentOrientation", oldValue, o);
9008
9009 // This could change the preferred size of the Component.
9010 invalidateIfValid();
9011 }
9012
9013 /**
9014 * Retrieves the language-sensitive orientation that is to be used to order
9015 * the elements or text within this component. <code>LayoutManager</code>
9016 * and <code>Component</code>
9017 * subclasses that wish to respect orientation should call this method to
9018 * get the component's orientation before performing layout or drawing.
9019 *
9020 * @return the orientation to order the elements or text
9021 * @see ComponentOrientation
9022 *
9023 * @author Laura Werner, IBM
9024 */
9025 public ComponentOrientation getComponentOrientation() {
9026 return componentOrientation;
9027 }
9028
9029 /**
9030 * Sets the <code>ComponentOrientation</code> property of this component
9031 * and all components contained within it.
9032 * <p>
9033 * This method changes layout-related information, and therefore,
9034 * invalidates the component hierarchy.
9035 *
9036 *
9037 * @param orientation the new component orientation of this component and
9038 * the components contained within it.
9039 * @exception NullPointerException if <code>orientation</code> is null.
9040 * @see #setComponentOrientation
9041 * @see #getComponentOrientation
9042 * @see #invalidate
9043 * @since 1.4
9044 */
9045 public void applyComponentOrientation(ComponentOrientation orientation) {
9046 if (orientation == null) {
9047 throw new NullPointerException();
9048 }
9049 setComponentOrientation(orientation);
9050 }
9051
9052 final boolean canBeFocusOwner() {
9053 // It is enabled, visible, focusable.
9054 if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {
9055 return true;
9056 }
9057 return false;
9058 }
9059
9087 final void relocateComponent() {
9088 synchronized (getTreeLock()) {
9089 if (peer == null) {
9090 return;
9091 }
9092 int nativeX = x;
9093 int nativeY = y;
9094 for (Component cont = getContainer();
9095 cont != null && cont.isLightweight();
9096 cont = cont.getContainer())
9097 {
9098 nativeX += cont.x;
9099 nativeY += cont.y;
9100 }
9101 peer.setBounds(nativeX, nativeY, width, height,
9102 ComponentPeer.SET_LOCATION);
9103 }
9104 }
9105
9106 /**
9107 * Returns the <code>Window</code> ancestor of the component.
9108 * @return Window ancestor of the component or component by itself if it is Window;
9109 * null, if component is not a part of window hierarchy
9110 */
9111 Window getContainingWindow() {
9112 return SunToolkit.getContainingWindow(this);
9113 }
9114
9115 /**
9116 * Initialize JNI field and method IDs
9117 */
9118 private static native void initIDs();
9119
9120 /*
9121 * --- Accessibility Support ---
9122 *
9123 * Component will contain all of the methods in interface Accessible,
9124 * though it won't actually implement the interface - that will be up
9125 * to the individual objects which extend Component.
9126 */
9127
9128 /**
9129 * The {@code AccessibleContext} associated with this {@code Component}.
9130 */
9131 protected AccessibleContext accessibleContext = null;
9132
9133 /**
9134 * Gets the <code>AccessibleContext</code> associated
9135 * with this <code>Component</code>.
9136 * The method implemented by this base
9137 * class returns null. Classes that extend <code>Component</code>
9138 * should implement this method to return the
9139 * <code>AccessibleContext</code> associated with the subclass.
9140 *
9141 *
9142 * @return the <code>AccessibleContext</code> of this
9143 * <code>Component</code>
9144 * @since 1.3
9145 */
9146 public AccessibleContext getAccessibleContext() {
9147 return accessibleContext;
9148 }
9149
9150 /**
9151 * Inner class of Component used to provide default support for
9152 * accessibility. This class is not meant to be used directly by
9153 * application developers, but is instead meant only to be
9154 * subclassed by component developers.
9155 * <p>
9156 * The class used to obtain the accessible role for this object.
9157 * @since 1.3
9158 */
9159 protected abstract class AccessibleAWTComponent extends AccessibleContext
9160 implements Serializable, AccessibleComponent {
9161
9162 private static final long serialVersionUID = 642321655757800191L;
9163
9224 */
9225 protected class AccessibleAWTFocusHandler implements FocusListener {
9226 public void focusGained(FocusEvent event) {
9227 if (accessibleContext != null) {
9228 accessibleContext.firePropertyChange(
9229 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9230 null, AccessibleState.FOCUSED);
9231 }
9232 }
9233 public void focusLost(FocusEvent event) {
9234 if (accessibleContext != null) {
9235 accessibleContext.firePropertyChange(
9236 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9237 AccessibleState.FOCUSED, null);
9238 }
9239 }
9240 } // inner class AccessibleAWTFocusHandler
9241
9242
9243 /**
9244 * Adds a <code>PropertyChangeListener</code> to the listener list.
9245 *
9246 * @param listener the property change listener to be added
9247 */
9248 public void addPropertyChangeListener(PropertyChangeListener listener) {
9249 if (accessibleAWTComponentHandler == null) {
9250 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();
9251 }
9252 if (accessibleAWTFocusHandler == null) {
9253 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();
9254 }
9255 if (propertyListenersCount++ == 0) {
9256 Component.this.addComponentListener(accessibleAWTComponentHandler);
9257 Component.this.addFocusListener(accessibleAWTFocusHandler);
9258 }
9259 super.addPropertyChangeListener(listener);
9260 }
9261
9262 /**
9263 * Remove a PropertyChangeListener from the listener list.
9264 * This removes a PropertyChangeListener that was registered
9265 * for all properties.
9266 *
9267 * @param listener The PropertyChangeListener to be removed
9268 */
9269 public void removePropertyChangeListener(PropertyChangeListener listener) {
9270 if (--propertyListenersCount == 0) {
9271 Component.this.removeComponentListener(accessibleAWTComponentHandler);
9272 Component.this.removeFocusListener(accessibleAWTFocusHandler);
9273 }
9274 super.removePropertyChangeListener(listener);
9275 }
9276
9277 // AccessibleContext methods
9278 //
9279 /**
9280 * Gets the accessible name of this object. This should almost never
9281 * return <code>java.awt.Component.getName()</code>,
9282 * as that generally isn't a localized name,
9283 * and doesn't have meaning for the user. If the
9284 * object is fundamentally a text object (e.g. a menu item), the
9285 * accessible name should be the text of the object (e.g. "save").
9286 * If the object has a tooltip, the tooltip text may also be an
9287 * appropriate String to return.
9288 *
9289 * @return the localized name of the object -- can be
9290 * <code>null</code> if this
9291 * object does not have a name
9292 * @see javax.accessibility.AccessibleContext#setAccessibleName
9293 */
9294 public String getAccessibleName() {
9295 return accessibleName;
9296 }
9297
9298 /**
9299 * Gets the accessible description of this object. This should be
9300 * a concise, localized description of what this object is - what
9301 * is its meaning to the user. If the object has a tooltip, the
9302 * tooltip text may be an appropriate string to return, assuming
9303 * it contains a concise description of the object (instead of just
9304 * the name of the object - e.g. a "Save" icon on a toolbar that
9305 * had "save" as the tooltip text shouldn't return the tooltip
9306 * text as the description, but something like "Saves the current
9307 * text document" instead).
9308 *
9309 * @return the localized description of the object -- can be
9310 * <code>null</code> if this object does not have a description
9311 * @see javax.accessibility.AccessibleContext#setAccessibleDescription
9312 */
9313 public String getAccessibleDescription() {
9314 return accessibleDescription;
9315 }
9316
9317 /**
9318 * Gets the role of this object.
9319 *
9320 * @return an instance of <code>AccessibleRole</code>
9321 * describing the role of the object
9322 * @see javax.accessibility.AccessibleRole
9323 */
9324 public AccessibleRole getAccessibleRole() {
9325 return AccessibleRole.AWT_COMPONENT;
9326 }
9327
9328 /**
9329 * Gets the state of this object.
9330 *
9331 * @return an instance of <code>AccessibleStateSet</code>
9332 * containing the current state set of the object
9333 * @see javax.accessibility.AccessibleState
9334 */
9335 public AccessibleStateSet getAccessibleStateSet() {
9336 return Component.this.getAccessibleStateSet();
9337 }
9338
9339 /**
9340 * Gets the <code>Accessible</code> parent of this object.
9341 * If the parent of this object implements <code>Accessible</code>,
9342 * this method should simply return <code>getParent</code>.
9343 *
9344 * @return the <code>Accessible</code> parent of this
9345 * object -- can be <code>null</code> if this
9346 * object does not have an <code>Accessible</code> parent
9347 */
9348 public Accessible getAccessibleParent() {
9349 if (accessibleParent != null) {
9350 return accessibleParent;
9351 } else {
9352 Container parent = getParent();
9353 if (parent instanceof Accessible) {
9354 return (Accessible) parent;
9355 }
9356 }
9357 return null;
9358 }
9359
9360 /**
9361 * Gets the index of this object in its accessible parent.
9362 *
9363 * @return the index of this object in its parent; or -1 if this
9364 * object does not have an accessible parent
9365 * @see #getAccessibleParent
9366 */
9367 public int getAccessibleIndexInParent() {
9368 return Component.this.getAccessibleIndexInParent();
9369 }
9370
9371 /**
9372 * Returns the number of accessible children in the object. If all
9373 * of the children of this object implement <code>Accessible</code>,
9374 * then this method should return the number of children of this object.
9375 *
9376 * @return the number of accessible children in the object
9377 */
9378 public int getAccessibleChildrenCount() {
9379 return 0; // Components don't have children
9380 }
9381
9382 /**
9383 * Returns the nth <code>Accessible</code> child of the object.
9384 *
9385 * @param i zero-based index of child
9386 * @return the nth <code>Accessible</code> child of the object
9387 */
9388 public Accessible getAccessibleChild(int i) {
9389 return null; // Components don't have children
9390 }
9391
9392 /**
9393 * Returns the locale of this object.
9394 *
9395 * @return the locale of this object
9396 */
9397 public Locale getLocale() {
9398 return Component.this.getLocale();
9399 }
9400
9401 /**
9402 * Gets the <code>AccessibleComponent</code> associated
9403 * with this object if one exists.
9404 * Otherwise return <code>null</code>.
9405 *
9406 * @return the component
9407 */
9408 public AccessibleComponent getAccessibleComponent() {
9409 return this;
9410 }
9411
9412
9413 // AccessibleComponent methods
9414 //
9415 /**
9416 * Gets the background color of this object.
9417 *
9418 * @return the background color, if supported, of the object;
9419 * otherwise, <code>null</code>
9420 */
9421 public Color getBackground() {
9422 return Component.this.getBackground();
9423 }
9424
9425 /**
9426 * Sets the background color of this object.
9427 * (For transparency, see <code>isOpaque</code>.)
9428 *
9429 * @param c the new <code>Color</code> for the background
9430 * @see Component#isOpaque
9431 */
9432 public void setBackground(Color c) {
9433 Component.this.setBackground(c);
9434 }
9435
9436 /**
9437 * Gets the foreground color of this object.
9438 *
9439 * @return the foreground color, if supported, of the object;
9440 * otherwise, <code>null</code>
9441 */
9442 public Color getForeground() {
9443 return Component.this.getForeground();
9444 }
9445
9446 /**
9447 * Sets the foreground color of this object.
9448 *
9449 * @param c the new <code>Color</code> for the foreground
9450 */
9451 public void setForeground(Color c) {
9452 Component.this.setForeground(c);
9453 }
9454
9455 /**
9456 * Gets the <code>Cursor</code> of this object.
9457 *
9458 * @return the <code>Cursor</code>, if supported,
9459 * of the object; otherwise, <code>null</code>
9460 */
9461 public Cursor getCursor() {
9462 return Component.this.getCursor();
9463 }
9464
9465 /**
9466 * Sets the <code>Cursor</code> of this object.
9467 * <p>
9468 * The method may have no visual effect if the Java platform
9469 * implementation and/or the native system do not support
9470 * changing the mouse cursor shape.
9471 * @param cursor the new <code>Cursor</code> for the object
9472 */
9473 public void setCursor(Cursor cursor) {
9474 Component.this.setCursor(cursor);
9475 }
9476
9477 /**
9478 * Gets the <code>Font</code> of this object.
9479 *
9480 * @return the <code>Font</code>, if supported,
9481 * for the object; otherwise, <code>null</code>
9482 */
9483 public Font getFont() {
9484 return Component.this.getFont();
9485 }
9486
9487 /**
9488 * Sets the <code>Font</code> of this object.
9489 *
9490 * @param f the new <code>Font</code> for the object
9491 */
9492 public void setFont(Font f) {
9493 Component.this.setFont(f);
9494 }
9495
9496 /**
9497 * Gets the <code>FontMetrics</code> of this object.
9498 *
9499 * @param f the <code>Font</code>
9500 * @return the <code>FontMetrics</code>, if supported,
9501 * the object; otherwise, <code>null</code>
9502 * @see #getFont
9503 */
9504 public FontMetrics getFontMetrics(Font f) {
9505 if (f == null) {
9506 return null;
9507 } else {
9508 return Component.this.getFontMetrics(f);
9509 }
9510 }
9511
9512 /**
9513 * Determines if the object is enabled.
9514 *
9515 * @return true if object is enabled; otherwise, false
9516 */
9517 public boolean isEnabled() {
9518 return Component.this.isEnabled();
9519 }
9520
9521 /**
9529 if (b != old) {
9530 if (accessibleContext != null) {
9531 if (b) {
9532 accessibleContext.firePropertyChange(
9533 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9534 null, AccessibleState.ENABLED);
9535 } else {
9536 accessibleContext.firePropertyChange(
9537 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9538 AccessibleState.ENABLED, null);
9539 }
9540 }
9541 }
9542 }
9543
9544 /**
9545 * Determines if the object is visible. Note: this means that the
9546 * object intends to be visible; however, it may not in fact be
9547 * showing on the screen because one of the objects that this object
9548 * is contained by is not visible. To determine if an object is
9549 * showing on the screen, use <code>isShowing</code>.
9550 *
9551 * @return true if object is visible; otherwise, false
9552 */
9553 public boolean isVisible() {
9554 return Component.this.isVisible();
9555 }
9556
9557 /**
9558 * Sets the visible state of the object.
9559 *
9560 * @param b if true, shows this object; otherwise, hides it
9561 */
9562 public void setVisible(boolean b) {
9563 boolean old = Component.this.isVisible();
9564 Component.this.setVisible(b);
9565 if (b != old) {
9566 if (accessibleContext != null) {
9567 if (b) {
9568 accessibleContext.firePropertyChange(
9569 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9578 }
9579
9580 /**
9581 * Determines if the object is showing. This is determined by checking
9582 * the visibility of the object and ancestors of the object. Note:
9583 * this will return true even if the object is obscured by another
9584 * (for example, it happens to be underneath a menu that was pulled
9585 * down).
9586 *
9587 * @return true if object is showing; otherwise, false
9588 */
9589 public boolean isShowing() {
9590 return Component.this.isShowing();
9591 }
9592
9593 /**
9594 * Checks whether the specified point is within this object's bounds,
9595 * where the point's x and y coordinates are defined to be relative to
9596 * the coordinate system of the object.
9597 *
9598 * @param p the <code>Point</code> relative to the
9599 * coordinate system of the object
9600 * @return true if object contains <code>Point</code>; otherwise false
9601 */
9602 public boolean contains(Point p) {
9603 return Component.this.contains(p);
9604 }
9605
9606 /**
9607 * Returns the location of the object on the screen.
9608 *
9609 * @return location of object on screen -- can be
9610 * <code>null</code> if this object is not on the screen
9611 */
9612 public Point getLocationOnScreen() {
9613 synchronized (Component.this.getTreeLock()) {
9614 if (Component.this.isShowing()) {
9615 return Component.this.getLocationOnScreen();
9616 } else {
9617 return null;
9618 }
9619 }
9620 }
9621
9622 /**
9623 * Gets the location of the object relative to the parent in the form
9624 * of a point specifying the object's top-left corner in the screen's
9625 * coordinate space.
9626 *
9627 * @return an instance of Point representing the top-left corner of
9628 * the object's bounds in the coordinate space of the screen;
9629 * <code>null</code> if this object or its parent are not on the screen
9630 */
9631 public Point getLocation() {
9632 return Component.this.getLocation();
9633 }
9634
9635 /**
9636 * Sets the location of the object relative to the parent.
9637 * @param p the coordinates of the object
9638 */
9639 public void setLocation(Point p) {
9640 Component.this.setLocation(p);
9641 }
9642
9643 /**
9644 * Gets the bounds of this object in the form of a Rectangle object.
9645 * The bounds specify this object's width, height, and location
9646 * relative to its parent.
9647 *
9648 * @return a rectangle indicating this component's bounds;
9649 * <code>null</code> if this object is not on the screen
9650 */
9651 public Rectangle getBounds() {
9652 return Component.this.getBounds();
9653 }
9654
9655 /**
9656 * Sets the bounds of this object in the form of a
9657 * <code>Rectangle</code> object.
9658 * The bounds specify this object's width, height, and location
9659 * relative to its parent.
9660 *
9661 * @param r a rectangle indicating this component's bounds
9662 */
9663 public void setBounds(Rectangle r) {
9664 Component.this.setBounds(r);
9665 }
9666
9667 /**
9668 * Returns the size of this object in the form of a
9669 * <code>Dimension</code> object. The height field of the
9670 * <code>Dimension</code> object contains this object's
9671 * height, and the width field of the <code>Dimension</code>
9672 * object contains this object's width.
9673 *
9674 * @return a <code>Dimension</code> object that indicates
9675 * the size of this component; <code>null</code> if
9676 * this object is not on the screen
9677 */
9678 public Dimension getSize() {
9679 return Component.this.getSize();
9680 }
9681
9682 /**
9683 * Resizes this object so that it has width and height.
9684 *
9685 * @param d - the dimension specifying the new size of the object
9686 */
9687 public void setSize(Dimension d) {
9688 Component.this.setSize(d);
9689 }
9690
9691 /**
9692 * Returns the <code>Accessible</code> child,
9693 * if one exists, contained at the local
9694 * coordinate <code>Point</code>. Otherwise returns
9695 * <code>null</code>.
9696 *
9697 * @param p the point defining the top-left corner of
9698 * the <code>Accessible</code>, given in the
9699 * coordinate space of the object's parent
9700 * @return the <code>Accessible</code>, if it exists,
9701 * at the specified location; else <code>null</code>
9702 */
9703 public Accessible getAccessibleAt(Point p) {
9704 return null; // Components don't have children
9705 }
9706
9707 /**
9708 * Returns whether this object can accept focus or not.
9709 *
9710 * @return true if object can accept focus; otherwise false
9711 */
9712 public boolean isFocusTraversable() {
9713 return Component.this.isFocusTraversable();
9714 }
9715
9716 /**
9717 * Requests focus for this object.
9718 */
9719 public void requestFocus() {
9720 Component.this.requestFocus();
9721 }
9755 int index = -1;
9756 Container parent = this.getParent();
9757 if (parent != null && parent instanceof Accessible) {
9758 Component ca[] = parent.getComponents();
9759 for (int i = 0; i < ca.length; i++) {
9760 if (ca[i] instanceof Accessible) {
9761 index++;
9762 }
9763 if (this.equals(ca[i])) {
9764 return index;
9765 }
9766 }
9767 }
9768 return -1;
9769 }
9770 }
9771
9772 /**
9773 * Gets the current state set of this object.
9774 *
9775 * @return an instance of <code>AccessibleStateSet</code>
9776 * containing the current state set of the object
9777 * @see AccessibleState
9778 */
9779 AccessibleStateSet getAccessibleStateSet() {
9780 synchronized (getTreeLock()) {
9781 AccessibleStateSet states = new AccessibleStateSet();
9782 if (this.isEnabled()) {
9783 states.add(AccessibleState.ENABLED);
9784 }
9785 if (this.isFocusTraversable()) {
9786 states.add(AccessibleState.FOCUSABLE);
9787 }
9788 if (this.isVisible()) {
9789 states.add(AccessibleState.VISIBLE);
9790 }
9791 if (this.isShowing()) {
9792 states.add(AccessibleState.SHOWING);
9793 }
9794 if (this.isFocusOwner()) {
9795 states.add(AccessibleState.FOCUSED);
|
72 import sun.awt.EmbeddedFrame;
73 import sun.awt.dnd.SunDropTargetEvent;
74 import sun.awt.im.CompositionArea;
75 import sun.font.FontManager;
76 import sun.font.FontManagerFactory;
77 import sun.font.SunFontManager;
78 import sun.java2d.SunGraphics2D;
79 import sun.java2d.pipe.Region;
80 import sun.awt.image.VSyncedBSManager;
81 import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
82 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
83 import sun.awt.RequestFocusController;
84 import sun.java2d.SunGraphicsEnvironment;
85 import sun.util.logging.PlatformLogger;
86
87 /**
88 * A <em>component</em> is an object having a graphical representation
89 * that can be displayed on the screen and that can interact with the
90 * user. Examples of components are the buttons, checkboxes, and scrollbars
91 * of a typical graphical user interface. <p>
92 * The {@code Component} class is the abstract superclass of
93 * the nonmenu-related Abstract Window Toolkit components. Class
94 * {@code Component} can also be extended directly to create a
95 * lightweight component. A lightweight component is a component that is
96 * not associated with a native window. On the contrary, a heavyweight
97 * component is associated with a native window. The {@link #isLightweight()}
98 * method may be used to distinguish between the two kinds of the components.
99 * <p>
100 * Lightweight and heavyweight components may be mixed in a single component
101 * hierarchy. However, for correct operating of such a mixed hierarchy of
102 * components, the whole hierarchy must be valid. When the hierarchy gets
103 * invalidated, like after changing the bounds of components, or
104 * adding/removing components to/from containers, the whole hierarchy must be
105 * validated afterwards by means of the {@link Container#validate()} method
106 * invoked on the top-most invalid container of the hierarchy.
107 *
108 * <h3>Serialization</h3>
109 * It is important to note that only AWT listeners which conform
110 * to the {@code Serializable} protocol will be saved when
111 * the object is stored. If an AWT object has listeners that
112 * aren't marked serializable, they will be dropped at
113 * {@code writeObject} time. Developers will need, as always,
114 * to consider the implications of making an object serializable.
115 * One situation to watch out for is this:
116 * <pre>
117 * import java.awt.*;
118 * import java.awt.event.*;
119 * import java.io.Serializable;
120 *
121 * class MyApp implements ActionListener, Serializable
122 * {
123 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
124 * Button aButton = new Button();
125 *
126 * MyApp()
127 * {
128 * // Oops, now aButton has a listener with a reference
129 * // to bigOne!
130 * aButton.addActionListener(this);
131 * }
132 *
133 * public void actionPerformed(ActionEvent e)
134 * {
135 * System.out.println("Hello There");
136 * }
137 * }
138 * </pre>
139 * In this example, serializing {@code aButton} by itself
140 * will cause {@code MyApp} and everything it refers to
141 * to be serialized as well. The problem is that the listener
142 * is serializable by coincidence, not by design. To separate
143 * the decisions about {@code MyApp} and the
144 * {@code ActionListener} being serializable one can use a
145 * nested class, as in the following example:
146 * <pre>
147 * import java.awt.*;
148 * import java.awt.event.*;
149 * import java.io.Serializable;
150 *
151 * class MyApp implements java.io.Serializable
152 * {
153 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
154 * Button aButton = new Button();
155 *
156 * static class MyActionListener implements ActionListener
157 * {
158 * public void actionPerformed(ActionEvent e)
159 * {
160 * System.out.println("Hello There");
161 * }
162 * }
163 *
164 * MyApp()
177 * <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/focus.html">
178 * How to Use the Focus Subsystem</a>,
179 * a section in <em>The Java Tutorial</em>, and the
180 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
181 * for more information.
182 *
183 * @author Arthur van Hoff
184 * @author Sami Shaio
185 */
186 public abstract class Component implements ImageObserver, MenuContainer,
187 Serializable
188 {
189
190 private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");
191 private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");
192 private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");
193 private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");
194
195 /**
196 * The peer of the component. The peer implements the component's
197 * behavior. The peer is set when the {@code Component} is
198 * added to a container that also is a peer.
199 * @see #addNotify
200 * @see #removeNotify
201 */
202 transient volatile ComponentPeer peer;
203
204 /**
205 * The parent of the object. It may be {@code null}
206 * for top-level components.
207 * @see #getParent
208 */
209 transient Container parent;
210
211 /**
212 * The {@code AppContext} of the component. Applets/Plugin may
213 * change the AppContext.
214 */
215 transient AppContext appContext;
216
217 /**
218 * The x position of the component in the parent's coordinate system.
219 *
220 * @serial
221 * @see #getLocation
222 */
223 int x;
224
225 /**
226 * The y position of the component in the parent's coordinate system.
227 *
228 * @serial
229 * @see #getLocation
230 */
231 int y;
232
233 /**
234 * The width of the component.
235 *
236 * @serial
237 * @see #getSize
238 */
239 int width;
240
241 /**
242 * The height of the component.
243 *
244 * @serial
245 * @see #getSize
246 */
247 int height;
248
249 /**
250 * The foreground color for this component.
251 * {@code foreground} can be {@code null}.
252 *
253 * @serial
254 * @see #getForeground
255 * @see #setForeground
256 */
257 Color foreground;
258
259 /**
260 * The background color for this component.
261 * {@code background} can be {@code null}.
262 *
263 * @serial
264 * @see #getBackground
265 * @see #setBackground
266 */
267 Color background;
268
269 /**
270 * The font used by this component.
271 * The {@code font} can be {@code null}.
272 *
273 * @serial
274 * @see #getFont
275 * @see #setFont
276 */
277 volatile Font font;
278
279 /**
280 * The font which the peer is currently using.
281 * ({@code null} if no peer exists.)
282 */
283 Font peerFont;
284
285 /**
286 * The cursor displayed when pointer is over this component.
287 * This value can be {@code null}.
288 *
289 * @serial
290 * @see #getCursor
291 * @see #setCursor
292 */
293 Cursor cursor;
294
295 /**
296 * The locale for the component.
297 *
298 * @serial
299 * @see #getLocale
300 * @see #setLocale
301 */
302 Locale locale;
303
304 /**
305 * A reference to a {@code GraphicsConfiguration} object
306 * used to describe the characteristics of a graphics
307 * destination.
308 * This value can be {@code null}.
309 *
310 * @since 1.3
311 * @serial
312 * @see GraphicsConfiguration
313 * @see #getGraphicsConfiguration
314 */
315 private transient GraphicsConfiguration graphicsConfig = null;
316
317 /**
318 * A reference to a {@code BufferStrategy} object
319 * used to manipulate the buffers on this component.
320 *
321 * @since 1.4
322 * @see java.awt.image.BufferStrategy
323 * @see #getBufferStrategy()
324 */
325 transient BufferStrategy bufferStrategy = null;
326
327 /**
328 * True when the object should ignore all repaint events.
329 *
330 * @since 1.4
331 * @serial
332 * @see #setIgnoreRepaint
333 * @see #getIgnoreRepaint
334 */
335 boolean ignoreRepaint = false;
336
337 /**
338 * True when the object is visible. An object that is not
350 *
351 * @serial
352 * @see #isEnabled
353 * @see #setEnabled
354 */
355 boolean enabled = true;
356
357 /**
358 * True when the object is valid. An invalid object needs to
359 * be laid out. This flag is set to false when the object
360 * size is changed.
361 *
362 * @serial
363 * @see #isValid
364 * @see #validate
365 * @see #invalidate
366 */
367 private volatile boolean valid = false;
368
369 /**
370 * The {@code DropTarget} associated with this component.
371 *
372 * @since 1.2
373 * @serial
374 * @see #setDropTarget
375 * @see #getDropTarget
376 */
377 DropTarget dropTarget;
378
379 /**
380 * @serial
381 * @see #add
382 */
383 Vector<PopupMenu> popups;
384
385 /**
386 * A component's name.
387 * This field can be {@code null}.
388 *
389 * @serial
390 * @see #getName
391 * @see #setName(String)
392 */
393 private String name;
394
395 /**
396 * A bool to determine whether the name has
397 * been set explicitly. {@code nameExplicitlySet} will
398 * be false if the name has not been set and
399 * true if it has.
400 *
401 * @serial
402 * @see #getName
403 * @see #setName(String)
404 */
405 private boolean nameExplicitlySet = false;
406
407 /**
408 * Indicates whether this Component can be focused.
409 *
410 * @serial
411 * @see #setFocusable
412 * @see #isFocusable
413 * @since 1.4
414 */
415 private boolean focusable = true;
416
417 private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
506 * Maximum size
507 *
508 * @serial
509 */
510 Dimension maxSize;
511
512 /**
513 * Whether or not setMaximumSize has been invoked with a non-null value.
514 */
515 boolean maxSizeSet;
516
517 /**
518 * The orientation for this component.
519 * @see #getComponentOrientation
520 * @see #setComponentOrientation
521 */
522 transient ComponentOrientation componentOrientation
523 = ComponentOrientation.UNKNOWN;
524
525 /**
526 * {@code newEventsOnly} will be true if the event is
527 * one of the event types enabled for the component.
528 * It will then allow for normal processing to
529 * continue. If it is false the event is passed
530 * to the component's parent and up the ancestor
531 * tree until the event has been consumed.
532 *
533 * @serial
534 * @see #dispatchEvent
535 */
536 boolean newEventsOnly = false;
537 transient ComponentListener componentListener;
538 transient FocusListener focusListener;
539 transient HierarchyListener hierarchyListener;
540 transient HierarchyBoundsListener hierarchyBoundsListener;
541 transient KeyListener keyListener;
542 transient MouseListener mouseListener;
543 transient MouseMotionListener mouseMotionListener;
544 transient MouseWheelListener mouseWheelListener;
545 transient InputMethodListener inputMethodListener;
546
548 static final String actionListenerK = "actionL";
549 static final String adjustmentListenerK = "adjustmentL";
550 static final String componentListenerK = "componentL";
551 static final String containerListenerK = "containerL";
552 static final String focusListenerK = "focusL";
553 static final String itemListenerK = "itemL";
554 static final String keyListenerK = "keyL";
555 static final String mouseListenerK = "mouseL";
556 static final String mouseMotionListenerK = "mouseMotionL";
557 static final String mouseWheelListenerK = "mouseWheelL";
558 static final String textListenerK = "textL";
559 static final String ownedWindowK = "ownedL";
560 static final String windowListenerK = "windowL";
561 static final String inputMethodListenerK = "inputMethodL";
562 static final String hierarchyListenerK = "hierarchyL";
563 static final String hierarchyBoundsListenerK = "hierarchyBoundsL";
564 static final String windowStateListenerK = "windowStateL";
565 static final String windowFocusListenerK = "windowFocusL";
566
567 /**
568 * The {@code eventMask} is ONLY set by subclasses via
569 * {@code enableEvents}.
570 * The mask should NOT be set when listeners are registered
571 * so that we can distinguish the difference between when
572 * listeners request events and subclasses request them.
573 * One bit is used to indicate whether input methods are
574 * enabled; this bit is set by {@code enableInputMethods} and is
575 * on by default.
576 *
577 * @serial
578 * @see #enableInputMethods
579 * @see AWTEvent
580 */
581 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
582
583 /**
584 * Static properties for incremental drawing.
585 * @see #imageUpdate
586 */
587 static boolean isInc;
588 static int incRate;
589 static {
590 /* ensure that the necessary native libraries are loaded */
591 Toolkit.loadLibraries();
592 /* initialize JNI field and method ids */
593 if (!GraphicsEnvironment.isHeadless()) {
594 initIDs();
595 }
596
597 String s = java.security.AccessController.doPrivileged(
598 new GetPropertyAction("awt.image.incrementaldraw"));
599 isInc = (s == null || s.equals("true"));
600
601 s = java.security.AccessController.doPrivileged(
602 new GetPropertyAction("awt.image.redrawrate"));
603 incRate = (s != null) ? Integer.parseInt(s) : 100;
604 }
605
606 /**
607 * Ease-of-use constant for {@code getAlignmentY()}.
608 * Specifies an alignment to the top of the component.
609 * @see #getAlignmentY
610 */
611 public static final float TOP_ALIGNMENT = 0.0f;
612
613 /**
614 * Ease-of-use constant for {@code getAlignmentY} and
615 * {@code getAlignmentX}. Specifies an alignment to
616 * the center of the component
617 * @see #getAlignmentX
618 * @see #getAlignmentY
619 */
620 public static final float CENTER_ALIGNMENT = 0.5f;
621
622 /**
623 * Ease-of-use constant for {@code getAlignmentY}.
624 * Specifies an alignment to the bottom of the component.
625 * @see #getAlignmentY
626 */
627 public static final float BOTTOM_ALIGNMENT = 1.0f;
628
629 /**
630 * Ease-of-use constant for {@code getAlignmentX}.
631 * Specifies an alignment to the left side of the component.
632 * @see #getAlignmentX
633 */
634 public static final float LEFT_ALIGNMENT = 0.0f;
635
636 /**
637 * Ease-of-use constant for {@code getAlignmentX}.
638 * Specifies an alignment to the right side of the component.
639 * @see #getAlignmentX
640 */
641 public static final float RIGHT_ALIGNMENT = 1.0f;
642
643 /*
644 * JDK 1.1 serialVersionUID
645 */
646 private static final long serialVersionUID = -7644114512714619750L;
647
648 /**
649 * If any {@code PropertyChangeListeners} have been registered,
650 * the {@code changeSupport} field describes them.
651 *
652 * @serial
653 * @since 1.2
654 * @see #addPropertyChangeListener
655 * @see #removePropertyChangeListener
656 * @see #firePropertyChange
657 */
658 private PropertyChangeSupport changeSupport;
659
660 /*
661 * In some cases using "this" as an object to synchronize by
662 * can lead to a deadlock if client code also uses synchronization
663 * by a component object. For every such situation revealed we should
664 * consider possibility of replacing "this" with the package private
665 * objectLock object introduced below. So far there are 3 issues known:
666 * - CR 6708322 (the getName/setName methods);
667 * - CR 6608764 (the PropertyChangeListener machinery);
668 * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods).
669 *
670 * Note: this field is considered final, though readObject() prohibits
688 boolean isPacked = false;
689
690 /**
691 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
692 * to signal setBounds what's changing. Should be used under TreeLock.
693 * This is only needed due to the inability to change the cross-calling
694 * order of public and deprecated methods.
695 */
696 private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
697
698 /**
699 * Enumeration of the common ways the baseline of a component can
700 * change as the size changes. The baseline resize behavior is
701 * primarily for layout managers that need to know how the
702 * position of the baseline changes as the component size changes.
703 * In general the baseline resize behavior will be valid for sizes
704 * greater than or equal to the minimum size (the actual minimum
705 * size; not a developer specified minimum size). For sizes
706 * smaller than the minimum size the baseline may change in a way
707 * other than the baseline resize behavior indicates. Similarly,
708 * as the size approaches {@code Integer.MAX_VALUE} and/or
709 * {@code Short.MAX_VALUE} the baseline may change in a way
710 * other than the baseline resize behavior indicates.
711 *
712 * @see #getBaselineResizeBehavior
713 * @see #getBaseline(int,int)
714 * @since 1.6
715 */
716 public enum BaselineResizeBehavior {
717 /**
718 * Indicates the baseline remains fixed relative to the
719 * y-origin. That is, {@code getBaseline} returns
720 * the same value regardless of the height or width. For example, a
721 * {@code JLabel} containing non-empty text with a
722 * vertical alignment of {@code TOP} should have a
723 * baseline type of {@code CONSTANT_ASCENT}.
724 */
725 CONSTANT_ASCENT,
726
727 /**
728 * Indicates the baseline remains fixed relative to the height
729 * and does not change as the width is varied. That is, for
730 * any height H the difference between H and
731 * {@code getBaseline(w, H)} is the same. For example, a
732 * {@code JLabel} containing non-empty text with a
733 * vertical alignment of {@code BOTTOM} should have a
734 * baseline type of {@code CONSTANT_DESCENT}.
735 */
736 CONSTANT_DESCENT,
737
738 /**
739 * Indicates the baseline remains a fixed distance from
740 * the center of the component. That is, for any height H the
741 * difference between {@code getBaseline(w, H)} and
742 * {@code H / 2} is the same (plus or minus one depending upon
743 * rounding error).
744 * <p>
745 * Because of possible rounding errors it is recommended
746 * you ask for the baseline with two consecutive heights and use
747 * the return value to determine if you need to pad calculations
748 * by 1. The following shows how to calculate the baseline for
749 * any height:
750 * <pre>
751 * Dimension preferredSize = component.getPreferredSize();
752 * int baseline = getBaseline(preferredSize.width,
753 * preferredSize.height);
754 * int nextBaseline = getBaseline(preferredSize.width,
755 * preferredSize.height + 1);
756 * // Amount to add to height when calculating where baseline
757 * // lands for a particular height:
758 * int padding = 0;
759 * // Where the baseline is relative to the mid point
760 * int baselineOffset = baseline - height / 2;
761 * if (preferredSize.height % 2 == 0 &&
762 * baseline != nextBaseline) {
971 }
972
973 public void revalidateSynchronously(Component comp) {
974 comp.revalidateSynchronously();
975 }
976
977 @Override
978 public void createBufferStrategy(Component comp, int numBuffers,
979 BufferCapabilities caps) throws AWTException {
980 comp.createBufferStrategy(numBuffers, caps);
981 }
982
983 @Override
984 public BufferStrategy getBufferStrategy(Component comp) {
985 return comp.getBufferStrategy();
986 }
987 });
988 }
989
990 /**
991 * Constructs a new component. Class {@code Component} can be
992 * extended directly to create a lightweight component that does not
993 * utilize an opaque native window. A lightweight component must be
994 * hosted by a native container somewhere higher up in the component
995 * tree (for example, by a {@code Frame} object).
996 */
997 protected Component() {
998 appContext = AppContext.getAppContext();
999 }
1000
1001 @SuppressWarnings({"rawtypes", "unchecked"})
1002 void initializeFocusTraversalKeys() {
1003 focusTraversalKeys = new Set[3];
1004 }
1005
1006 /**
1007 * Constructs a name for this component. Called by {@code getName}
1008 * when the name is {@code null}.
1009 */
1010 String constructComponentName() {
1011 return null; // For strict compliance with prior platform versions, a Component
1012 // that doesn't set its name should return null from
1013 // getName()
1014 }
1015
1016 /**
1017 * Gets the name of the component.
1018 * @return this component's name
1019 * @see #setName
1020 * @since 1.1
1021 */
1022 public String getName() {
1023 if (name == null && !nameExplicitlySet) {
1024 synchronized(getObjectLock()) {
1025 if (name == null && !nameExplicitlySet)
1026 name = constructComponentName();
1027 }
1028 }
1054 public Container getParent() {
1055 return getParent_NoClientCode();
1056 }
1057
1058 // NOTE: This method may be called by privileged threads.
1059 // This functionality is implemented in a package-private method
1060 // to insure that it cannot be overridden by client subclasses.
1061 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1062 final Container getParent_NoClientCode() {
1063 return parent;
1064 }
1065
1066 // This method is overridden in the Window class to return null,
1067 // because the parent field of the Window object contains
1068 // the owner of the window, not its parent.
1069 Container getContainer() {
1070 return getParent_NoClientCode();
1071 }
1072
1073 /**
1074 * Associate a {@code DropTarget} with this component.
1075 * The {@code Component} will receive drops only if it
1076 * is enabled.
1077 *
1078 * @see #isEnabled
1079 * @param dt The DropTarget
1080 */
1081
1082 public synchronized void setDropTarget(DropTarget dt) {
1083 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1084 return;
1085
1086 DropTarget old;
1087
1088 if ((old = dropTarget) != null) {
1089 dropTarget.removeNotify();
1090
1091 DropTarget t = dropTarget;
1092
1093 dropTarget = null;
1094
1095 try {
1102 // if we have a new one, and we have a peer, add it!
1103
1104 if ((dropTarget = dt) != null) {
1105 try {
1106 dropTarget.setComponent(this);
1107 dropTarget.addNotify();
1108 } catch (IllegalArgumentException iae) {
1109 if (old != null) {
1110 try {
1111 old.setComponent(this);
1112 dropTarget.addNotify();
1113 } catch (IllegalArgumentException iae1) {
1114 // ignore it!
1115 }
1116 }
1117 }
1118 }
1119 }
1120
1121 /**
1122 * Gets the {@code DropTarget} associated with this
1123 * {@code Component}.
1124 *
1125 * @return the drop target
1126 */
1127
1128 public synchronized DropTarget getDropTarget() { return dropTarget; }
1129
1130 /**
1131 * Gets the {@code GraphicsConfiguration} associated with this
1132 * {@code Component}.
1133 * If the {@code Component} has not been assigned a specific
1134 * {@code GraphicsConfiguration},
1135 * the {@code GraphicsConfiguration} of the
1136 * {@code Component} object's top-level container is
1137 * returned.
1138 * If the {@code Component} has been created, but not yet added
1139 * to a {@code Container}, this method returns {@code null}.
1140 *
1141 * @return the {@code GraphicsConfiguration} used by this
1142 * {@code Component} or {@code null}
1143 * @since 1.3
1144 */
1145 public GraphicsConfiguration getGraphicsConfiguration() {
1146 synchronized(getTreeLock()) {
1147 return getGraphicsConfiguration_NoClientCode();
1148 }
1149 }
1150
1151 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1152 return graphicsConfig;
1153 }
1154
1155 void setGraphicsConfiguration(GraphicsConfiguration gc) {
1156 synchronized(getTreeLock()) {
1157 if (updateGraphicsData(gc)) {
1158 removeNotify();
1159 addNotify();
1160 }
1161 }
1162 }
1163
1164 boolean updateGraphicsData(GraphicsConfiguration gc) {
1165 checkTreeLock();
1166
1167 if (graphicsConfig == gc) {
1168 return false;
1169 }
1170
1171 graphicsConfig = gc;
1172
1173 ComponentPeer peer = this.peer;
1174 if (peer != null) {
1175 return peer.updateGraphicsData(gc);
1176 }
1177 return false;
1178 }
1179
1180 /**
1181 * Checks that this component's {@code GraphicsDevice}
1182 * {@code idString} matches the string argument.
1183 */
1184 void checkGD(String stringID) {
1185 if (graphicsConfig != null) {
1186 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1187 throw new IllegalArgumentException(
1188 "adding a container to a container on a different GraphicsDevice");
1189 }
1190 }
1191 }
1192
1193 /**
1194 * Gets this component's locking object (the object that owns the thread
1195 * synchronization monitor) for AWT component-tree and layout
1196 * operations.
1197 * @return this component's locking object
1198 */
1199 public final Object getTreeLock() {
1200 return LOCK;
1201 }
1202
1228 return parent.getToolkitImpl();
1229 }
1230 return Toolkit.getDefaultToolkit();
1231 }
1232
1233 final ComponentFactory getComponentFactory() {
1234 final Toolkit toolkit = getToolkit();
1235 if (toolkit instanceof ComponentFactory) {
1236 return (ComponentFactory) toolkit;
1237 }
1238 throw new AWTError("UI components are unsupported by: " + toolkit);
1239 }
1240
1241 /**
1242 * Determines whether this component is valid. A component is valid
1243 * when it is correctly sized and positioned within its parent
1244 * container and all its children are also valid.
1245 * In order to account for peers' size requirements, components are invalidated
1246 * before they are first shown on the screen. By the time the parent container
1247 * is fully realized, all its components will be valid.
1248 * @return {@code true} if the component is valid, {@code false}
1249 * otherwise
1250 * @see #validate
1251 * @see #invalidate
1252 * @since 1.0
1253 */
1254 public boolean isValid() {
1255 return (peer != null) && valid;
1256 }
1257
1258 /**
1259 * Determines whether this component is displayable. A component is
1260 * displayable when it is connected to a native screen resource.
1261 * <p>
1262 * A component is made displayable either when it is added to
1263 * a displayable containment hierarchy or when its containment
1264 * hierarchy is made displayable.
1265 * A containment hierarchy is made displayable when its ancestor
1266 * window is either packed or made visible.
1267 * <p>
1268 * A component is made undisplayable either when it is removed from
1269 * a displayable containment hierarchy or when its containment hierarchy
1270 * is made undisplayable. A containment hierarchy is made
1271 * undisplayable when its ancestor window is disposed.
1272 *
1273 * @return {@code true} if the component is displayable,
1274 * {@code false} otherwise
1275 * @see Container#add(Component)
1276 * @see Window#pack
1277 * @see Window#show
1278 * @see Container#remove(Component)
1279 * @see Window#dispose
1280 * @since 1.2
1281 */
1282 public boolean isDisplayable() {
1283 return peer != null;
1284 }
1285
1286 /**
1287 * Determines whether this component should be visible when its
1288 * parent is visible. Components are
1289 * initially visible, with the exception of top level components such
1290 * as {@code Frame} objects.
1291 * @return {@code true} if the component is visible,
1292 * {@code false} otherwise
1293 * @see #setVisible
1294 * @since 1.0
1295 */
1296 @Transient
1297 public boolean isVisible() {
1298 return isVisible_NoClientCode();
1299 }
1300 final boolean isVisible_NoClientCode() {
1301 return visible;
1302 }
1303
1304 /**
1305 * Determines whether this component will be displayed on the screen.
1306 * @return {@code true} if the component and all of its ancestors
1307 * until a toplevel window or null parent are visible,
1308 * {@code false} otherwise
1309 */
1310 boolean isRecursivelyVisible() {
1311 return visible && (parent == null || parent.isRecursivelyVisible());
1312 }
1313
1314 /**
1315 * Determines the bounds of a visible part of the component relative to its
1316 * parent.
1317 *
1318 * @return the visible part of bounds
1319 */
1320 private Rectangle getRecursivelyVisibleBounds() {
1321 final Component container = getContainer();
1322 final Rectangle bounds = getBounds();
1323 if (container == null) {
1324 // we are top level window or haven't a container, return our bounds
1325 return bounds;
1326 }
1327 // translate the container's bounds to our coordinate space
1328 final Rectangle parentsBounds = container.getRecursivelyVisibleBounds();
1353 if (!isShowing()) {
1354 return null;
1355 }
1356 Window win = getContainingWindow();
1357 Toolkit toolkit = Toolkit.getDefaultToolkit();
1358 if (!(toolkit instanceof ComponentFactory)) {
1359 return null;
1360 }
1361 if (!((ComponentFactory) toolkit).getMouseInfoPeer().isWindowUnderMouse(win)) {
1362 return null;
1363 }
1364 final boolean INCLUDE_DISABLED = true;
1365 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1366 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1367 relativeToWindow.y,
1368 INCLUDE_DISABLED);
1369 return inTheSameWindow;
1370 }
1371
1372 /**
1373 * Returns the position of the mouse pointer in this {@code Component}'s
1374 * coordinate space if the {@code Component} is directly under the mouse
1375 * pointer, otherwise returns {@code null}.
1376 * If the {@code Component} is not showing on the screen, this method
1377 * returns {@code null} even if the mouse pointer is above the area
1378 * where the {@code Component} would be displayed.
1379 * If the {@code Component} is partially or fully obscured by other
1380 * {@code Component}s or native windows, this method returns a non-null
1381 * value only if the mouse pointer is located above the unobscured part of the
1382 * {@code Component}.
1383 * <p>
1384 * For {@code Container}s it returns a non-null value if the mouse is
1385 * above the {@code Container} itself or above any of its descendants.
1386 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1387 * <p>
1388 * Sometimes the exact mouse coordinates are not important, and the only thing
1389 * that matters is whether a specific {@code Component} is under the mouse
1390 * pointer. If the return value of this method is {@code null}, mouse
1391 * pointer is not directly above the {@code Component}.
1392 *
1393 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1394 * @see #isShowing
1395 * @see Container#getMousePosition
1396 * @return mouse coordinates relative to this {@code Component}, or null
1397 * @since 1.5
1398 */
1399 public Point getMousePosition() throws HeadlessException {
1400 if (GraphicsEnvironment.isHeadless()) {
1401 throw new HeadlessException();
1402 }
1403
1404 PointerInfo pi = java.security.AccessController.doPrivileged(
1405 new java.security.PrivilegedAction<PointerInfo>() {
1406 public PointerInfo run() {
1407 return MouseInfo.getPointerInfo();
1408 }
1409 }
1410 );
1411
1412 synchronized (getTreeLock()) {
1413 Component inTheSameWindow = findUnderMouseInWindow(pi);
1414 if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1415 return null;
1416 }
1421 /**
1422 * Overridden in Container. Must be called under TreeLock.
1423 */
1424 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1425 return comp == this;
1426 }
1427
1428 /**
1429 * Determines whether this component is showing on screen. This means
1430 * that the component must be visible, and it must be in a container
1431 * that is visible and showing.
1432 * <p>
1433 * <strong>Note:</strong> sometimes there is no way to detect whether the
1434 * {@code Component} is actually visible to the user. This can happen when:
1435 * <ul>
1436 * <li>the component has been added to a visible {@code ScrollPane} but
1437 * the {@code Component} is not currently in the scroll pane's view port.
1438 * <li>the {@code Component} is obscured by another {@code Component} or
1439 * {@code Container}.
1440 * </ul>
1441 * @return {@code true} if the component is showing,
1442 * {@code false} otherwise
1443 * @see #setVisible
1444 * @since 1.0
1445 */
1446 public boolean isShowing() {
1447 if (visible && (peer != null)) {
1448 Container parent = this.parent;
1449 return (parent == null) || parent.isShowing();
1450 }
1451 return false;
1452 }
1453
1454 /**
1455 * Determines whether this component is enabled. An enabled component
1456 * can respond to user input and generate events. Components are
1457 * enabled initially by default. A component may be enabled or disabled by
1458 * calling its {@code setEnabled} method.
1459 * @return {@code true} if the component is enabled,
1460 * {@code false} otherwise
1461 * @see #setEnabled
1462 * @since 1.0
1463 */
1464 public boolean isEnabled() {
1465 return isEnabledImpl();
1466 }
1467
1468 /*
1469 * This is called by the native code, so client code can't
1470 * be called on the toolkit thread.
1471 */
1472 final boolean isEnabledImpl() {
1473 return enabled;
1474 }
1475
1476 /**
1477 * Enables or disables this component, depending on the value of the
1478 * parameter {@code b}. An enabled component can respond to user
1479 * input and generate events. Components are enabled initially by default.
1480 *
1481 * <p>Note: Disabling a lightweight component does not prevent it from
1482 * receiving MouseEvents.
1483 * <p>Note: Disabling a heavyweight container prevents all components
1484 * in this container from receiving any input events. But disabling a
1485 * lightweight container affects only this container.
1486 *
1487 * @param b If {@code true}, this component is
1488 * enabled; otherwise this component is disabled
1489 * @see #isEnabled
1490 * @see #isLightweight
1491 * @since 1.1
1492 */
1493 public void setEnabled(boolean b) {
1494 enable(b);
1495 }
1496
1497 /**
1498 * @deprecated As of JDK version 1.1,
1499 * replaced by {@code setEnabled(boolean)}.
1500 */
1501 @Deprecated
1502 public void enable() {
1503 if (!enabled) {
1504 synchronized (getTreeLock()) {
1505 enabled = true;
1506 ComponentPeer peer = this.peer;
1507 if (peer != null) {
1508 peer.setEnabled(true);
1509 if (visible && !getRecursivelyVisibleBounds().isEmpty()) {
1510 updateCursorImmediately();
1511 }
1512 }
1513 }
1514 if (accessibleContext != null) {
1515 accessibleContext.firePropertyChange(
1516 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1517 null, AccessibleState.ENABLED);
1518 }
1519 }
1520 }
1521
1522 /**
1523 * Enables or disables this component.
1524 *
1525 * @param b {@code true} to enable this component;
1526 * otherwise {@code false}
1527 *
1528 * @deprecated As of JDK version 1.1,
1529 * replaced by {@code setEnabled(boolean)}.
1530 */
1531 @Deprecated
1532 public void enable(boolean b) {
1533 if (b) {
1534 enable();
1535 } else {
1536 disable();
1537 }
1538 }
1539
1540 /**
1541 * @deprecated As of JDK version 1.1,
1542 * replaced by {@code setEnabled(boolean)}.
1543 */
1544 @Deprecated
1545 public void disable() {
1546 if (enabled) {
1547 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1548 synchronized (getTreeLock()) {
1549 enabled = false;
1550 // A disabled lw container is allowed to contain a focus owner.
1551 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1552 KeyboardFocusManager.isAutoFocusTransferEnabled())
1553 {
1554 // Don't clear the global focus owner. If transferFocus
1555 // fails, we want the focus to stay on the disabled
1556 // Component so that keyboard traversal, et. al. still
1557 // makes sense to the user.
1558 transferFocus(false);
1559 }
1560 ComponentPeer peer = this.peer;
1561 if (peer != null) {
1562 peer.setEnabled(false);
1612 new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1613 inputContext.dispatchEvent(focusGainedEvent);
1614 }
1615 }
1616
1617 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1618 } else {
1619 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1620 InputContext inputContext = getInputContext();
1621 if (inputContext != null) {
1622 inputContext.endComposition();
1623 inputContext.removeNotify(this);
1624 }
1625 }
1626 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1627 }
1628 }
1629
1630 /**
1631 * Shows or hides this component depending on the value of parameter
1632 * {@code b}.
1633 * <p>
1634 * This method changes layout-related information, and therefore,
1635 * invalidates the component hierarchy.
1636 *
1637 * @param b if {@code true}, shows this component;
1638 * otherwise, hides this component
1639 * @see #isVisible
1640 * @see #invalidate
1641 * @since 1.1
1642 */
1643 public void setVisible(boolean b) {
1644 show(b);
1645 }
1646
1647 /**
1648 * @deprecated As of JDK version 1.1,
1649 * replaced by {@code setVisible(boolean)}.
1650 */
1651 @Deprecated
1652 public void show() {
1653 if (!visible) {
1654 synchronized (getTreeLock()) {
1655 visible = true;
1656 mixOnShowing();
1657 ComponentPeer peer = this.peer;
1658 if (peer != null) {
1659 peer.setVisible(true);
1660 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1661 this, parent,
1662 HierarchyEvent.SHOWING_CHANGED,
1663 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1664 if (peer instanceof LightweightPeer) {
1665 repaint();
1666 }
1667 updateCursorImmediately();
1668 }
1669
1672 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1673 ComponentEvent e = new ComponentEvent(this,
1674 ComponentEvent.COMPONENT_SHOWN);
1675 Toolkit.getEventQueue().postEvent(e);
1676 }
1677 }
1678 Container parent = this.parent;
1679 if (parent != null) {
1680 parent.invalidate();
1681 }
1682 }
1683 }
1684
1685 /**
1686 * Makes this component visible or invisible.
1687 *
1688 * @param b {@code true} to make this component visible;
1689 * otherwise {@code false}
1690 *
1691 * @deprecated As of JDK version 1.1,
1692 * replaced by {@code setVisible(boolean)}.
1693 */
1694 @Deprecated
1695 public void show(boolean b) {
1696 if (b) {
1697 show();
1698 } else {
1699 hide();
1700 }
1701 }
1702
1703 boolean containsFocus() {
1704 return isFocusOwner();
1705 }
1706
1707 void clearMostRecentFocusOwnerOnHide() {
1708 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1709 }
1710
1711 void clearCurrentFocusCycleRootOnHide() {
1712 /* do nothing */
1713 }
1714
1715 /**
1716 * @deprecated As of JDK version 1.1,
1717 * replaced by {@code setVisible(boolean)}.
1718 */
1719 @Deprecated
1720 public void hide() {
1721 isPacked = false;
1722
1723 if (visible) {
1724 clearCurrentFocusCycleRootOnHide();
1725 clearMostRecentFocusOwnerOnHide();
1726 synchronized (getTreeLock()) {
1727 visible = false;
1728 mixOnHiding(isLightweight());
1729 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
1730 transferFocus(true);
1731 }
1732 ComponentPeer peer = this.peer;
1733 if (peer != null) {
1734 peer.setVisible(false);
1735 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1736 this, parent,
1737 HierarchyEvent.SHOWING_CHANGED,
1762 * not have a foreground color, the foreground color of its parent
1763 * is returned
1764 * @see #setForeground
1765 * @since 1.0
1766 * @beaninfo
1767 * bound: true
1768 */
1769 @Transient
1770 public Color getForeground() {
1771 Color foreground = this.foreground;
1772 if (foreground != null) {
1773 return foreground;
1774 }
1775 Container parent = this.parent;
1776 return (parent != null) ? parent.getForeground() : null;
1777 }
1778
1779 /**
1780 * Sets the foreground color of this component.
1781 * @param c the color to become this component's
1782 * foreground color; if this parameter is {@code null}
1783 * then this component will inherit
1784 * the foreground color of its parent
1785 * @see #getForeground
1786 * @since 1.0
1787 */
1788 public void setForeground(Color c) {
1789 Color oldColor = foreground;
1790 ComponentPeer peer = this.peer;
1791 foreground = c;
1792 if (peer != null) {
1793 c = getForeground();
1794 if (c != null) {
1795 peer.setForeground(c);
1796 }
1797 }
1798 // This is a bound property, so report the change to
1799 // any registered listeners. (Cheap if there are none.)
1800 firePropertyChange("foreground", oldColor, c);
1801 }
1802
1803 /**
1804 * Returns whether the foreground color has been explicitly set for this
1805 * Component. If this method returns {@code false}, this Component is
1806 * inheriting its foreground color from an ancestor.
1807 *
1808 * @return {@code true} if the foreground color has been explicitly
1809 * set for this Component; {@code false} otherwise.
1810 * @since 1.4
1811 */
1812 public boolean isForegroundSet() {
1813 return (foreground != null);
1814 }
1815
1816 /**
1817 * Gets the background color of this component.
1818 * @return this component's background color; if this component does
1819 * not have a background color,
1820 * the background color of its parent is returned
1821 * @see #setBackground
1822 * @since 1.0
1823 */
1824 @Transient
1825 public Color getBackground() {
1826 Color background = this.background;
1827 if (background != null) {
1828 return background;
1829 }
1830 Container parent = this.parent;
1831 return (parent != null) ? parent.getBackground() : null;
1832 }
1833
1834 /**
1835 * Sets the background color of this component.
1836 * <p>
1837 * The background color affects each component differently and the
1838 * parts of the component that are affected by the background color
1839 * may differ between operating systems.
1840 *
1841 * @param c the color to become this component's color;
1842 * if this parameter is {@code null}, then this
1843 * component will inherit the background color of its parent
1844 * @see #getBackground
1845 * @since 1.0
1846 * @beaninfo
1847 * bound: true
1848 */
1849 public void setBackground(Color c) {
1850 Color oldColor = background;
1851 ComponentPeer peer = this.peer;
1852 background = c;
1853 if (peer != null) {
1854 c = getBackground();
1855 if (c != null) {
1856 peer.setBackground(c);
1857 }
1858 }
1859 // This is a bound property, so report the change to
1860 // any registered listeners. (Cheap if there are none.)
1861 firePropertyChange("background", oldColor, c);
1862 }
1863
1864 /**
1865 * Returns whether the background color has been explicitly set for this
1866 * Component. If this method returns {@code false}, this Component is
1867 * inheriting its background color from an ancestor.
1868 *
1869 * @return {@code true} if the background color has been explicitly
1870 * set for this Component; {@code false} otherwise.
1871 * @since 1.4
1872 */
1873 public boolean isBackgroundSet() {
1874 return (background != null);
1875 }
1876
1877 /**
1878 * Gets the font of this component.
1879 * @return this component's font; if a font has not been set
1880 * for this component, the font of its parent is returned
1881 * @see #setFont
1882 * @since 1.0
1883 */
1884 @Transient
1885 public Font getFont() {
1886 return getFont_NoClientCode();
1887 }
1888
1889 // NOTE: This method may be called by privileged threads.
1890 // This functionality is implemented in a package-private method
1891 // to insure that it cannot be overridden by client subclasses.
1892 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1893 final Font getFont_NoClientCode() {
1894 Font font = this.font;
1895 if (font != null) {
1896 return font;
1897 }
1898 Container parent = this.parent;
1899 return (parent != null) ? parent.getFont_NoClientCode() : null;
1900 }
1901
1902 /**
1903 * Sets the font of this component.
1904 * <p>
1905 * This method changes layout-related information, and therefore,
1906 * invalidates the component hierarchy.
1907 *
1908 * @param f the font to become this component's font;
1909 * if this parameter is {@code null} then this
1910 * component will inherit the font of its parent
1911 * @see #getFont
1912 * @see #invalidate
1913 * @since 1.0
1914 * @beaninfo
1915 * bound: true
1916 */
1917 public void setFont(Font f) {
1918 Font oldFont, newFont;
1919 synchronized(getTreeLock()) {
1920 oldFont = font;
1921 newFont = font = f;
1922 ComponentPeer peer = this.peer;
1923 if (peer != null) {
1924 f = getFont();
1925 if (f != null) {
1926 peer.setFont(f);
1927 peerFont = f;
1928 }
1929 }
1930 }
1931 // This is a bound property, so report the change to
1932 // any registered listeners. (Cheap if there are none.)
1933 firePropertyChange("font", oldFont, newFont);
1934
1935 // This could change the preferred size of the Component.
1936 // Fix for 6213660. Should compare old and new fonts and do not
1937 // call invalidate() if they are equal.
1938 if (f != oldFont && (oldFont == null ||
1939 !oldFont.equals(f))) {
1940 invalidateIfValid();
1941 }
1942 }
1943
1944 /**
1945 * Returns whether the font has been explicitly set for this Component. If
1946 * this method returns {@code false}, this Component is inheriting its
1947 * font from an ancestor.
1948 *
1949 * @return {@code true} if the font has been explicitly set for this
1950 * Component; {@code false} otherwise.
1951 * @since 1.4
1952 */
1953 public boolean isFontSet() {
1954 return (font != null);
1955 }
1956
1957 /**
1958 * Gets the locale of this component.
1959 * @return this component's locale; if this component does not
1960 * have a locale, the locale of its parent is returned
1961 * @see #setLocale
1962 * @exception IllegalComponentStateException if the {@code Component}
1963 * does not have its own locale and has not yet been added to
1964 * a containment hierarchy such that the locale can be determined
1965 * from the containing parent
1966 * @since 1.1
1967 */
1968 public Locale getLocale() {
1969 Locale locale = this.locale;
1970 if (locale != null) {
1971 return locale;
1972 }
1973 Container parent = this.parent;
1974
1975 if (parent == null) {
1976 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");
1977 } else {
1978 return parent.getLocale();
1979 }
1980 }
1981
1982 /**
1986 * invalidates the component hierarchy.
1987 *
1988 * @param l the locale to become this component's locale
1989 * @see #getLocale
1990 * @see #invalidate
1991 * @since 1.1
1992 */
1993 public void setLocale(Locale l) {
1994 Locale oldValue = locale;
1995 locale = l;
1996
1997 // This is a bound property, so report the change to
1998 // any registered listeners. (Cheap if there are none.)
1999 firePropertyChange("locale", oldValue, l);
2000
2001 // This could change the preferred size of the Component.
2002 invalidateIfValid();
2003 }
2004
2005 /**
2006 * Gets the instance of {@code ColorModel} used to display
2007 * the component on the output device.
2008 * @return the color model used by this component
2009 * @see java.awt.image.ColorModel
2010 * @see java.awt.peer.ComponentPeer#getColorModel()
2011 * @see Toolkit#getColorModel()
2012 * @since 1.0
2013 */
2014 public ColorModel getColorModel() {
2015 ComponentPeer peer = this.peer;
2016 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
2017 return peer.getColorModel();
2018 } else if (GraphicsEnvironment.isHeadless()) {
2019 return ColorModel.getRGBdefault();
2020 } // else
2021 return getToolkit().getColorModel();
2022 }
2023
2024 /**
2025 * Gets the location of this component in the form of a
2026 * point specifying the component's top-left corner.
2027 * The location will be relative to the parent's coordinate space.
2028 * <p>
2029 * Due to the asynchronous nature of native event handling, this
2030 * method can return outdated values (for instance, after several calls
2031 * of {@code setLocation()} in rapid succession). For this
2032 * reason, the recommended method of obtaining a component's position is
2033 * within {@code java.awt.event.ComponentListener.componentMoved()},
2034 * which is called after the operating system has finished moving the
2035 * component.
2036 * </p>
2037 * @return an instance of {@code Point} representing
2038 * the top-left corner of the component's bounds in
2039 * the coordinate space of the component's parent
2040 * @see #setLocation
2041 * @see #getLocationOnScreen
2042 * @since 1.1
2043 */
2044 public Point getLocation() {
2045 return location();
2046 }
2047
2048 /**
2049 * Gets the location of this component in the form of a point
2050 * specifying the component's top-left corner in the screen's
2051 * coordinate space.
2052 * @return an instance of {@code Point} representing
2053 * the top-left corner of the component's bounds in the
2054 * coordinate space of the screen
2055 * @throws IllegalComponentStateException if the
2056 * component is not showing on the screen
2057 * @see #setLocation
2058 * @see #getLocation
2059 */
2060 public Point getLocationOnScreen() {
2061 synchronized (getTreeLock()) {
2062 return getLocationOnScreen_NoTreeLock();
2063 }
2064 }
2065
2066 /*
2067 * a package private version of getLocationOnScreen
2068 * used by GlobalCursormanager to update cursor
2069 */
2070 final Point getLocationOnScreen_NoTreeLock() {
2071
2072 if (peer != null && isShowing()) {
2078 for(Component c = this; c != host; c = c.getParent()) {
2079 pt.x += c.x;
2080 pt.y += c.y;
2081 }
2082 return pt;
2083 } else {
2084 Point pt = peer.getLocationOnScreen();
2085 return pt;
2086 }
2087 } else {
2088 throw new IllegalComponentStateException("component must be showing on the screen to determine its location");
2089 }
2090 }
2091
2092
2093 /**
2094 * Returns the location of this component's top left corner.
2095 *
2096 * @return the location of this component's top left corner
2097 * @deprecated As of JDK version 1.1,
2098 * replaced by {@code getLocation()}.
2099 */
2100 @Deprecated
2101 public Point location() {
2102 return location_NoClientCode();
2103 }
2104
2105 private Point location_NoClientCode() {
2106 return new Point(x, y);
2107 }
2108
2109 /**
2110 * Moves this component to a new location. The top-left corner of
2111 * the new location is specified by the {@code x} and {@code y}
2112 * parameters in the coordinate space of this component's parent.
2113 * <p>
2114 * This method changes layout-related information, and therefore,
2115 * invalidates the component hierarchy.
2116 *
2117 * @param x the <i>x</i>-coordinate of the new location's
2118 * top-left corner in the parent's coordinate space
2119 * @param y the <i>y</i>-coordinate of the new location's
2120 * top-left corner in the parent's coordinate space
2121 * @see #getLocation
2122 * @see #setBounds
2123 * @see #invalidate
2124 * @since 1.1
2125 */
2126 public void setLocation(int x, int y) {
2127 move(x, y);
2128 }
2129
2130 /**
2131 * Moves this component to a new location.
2132 *
2133 * @param x the <i>x</i>-coordinate of the new location's
2134 * top-left corner in the parent's coordinate space
2135 * @param y the <i>y</i>-coordinate of the new location's
2136 * top-left corner in the parent's coordinate space
2137 *
2138 * @deprecated As of JDK version 1.1,
2139 * replaced by {@code setLocation(int, int)}.
2140 */
2141 @Deprecated
2142 public void move(int x, int y) {
2143 synchronized(getTreeLock()) {
2144 setBoundsOp(ComponentPeer.SET_LOCATION);
2145 setBounds(x, y, width, height);
2146 }
2147 }
2148
2149 /**
2150 * Moves this component to a new location. The top-left corner of
2151 * the new location is specified by point {@code p}. Point
2152 * {@code p} is given in the parent's coordinate space.
2153 * <p>
2154 * This method changes layout-related information, and therefore,
2155 * invalidates the component hierarchy.
2156 *
2157 * @param p the point defining the top-left corner
2158 * of the new location, given in the coordinate space of this
2159 * component's parent
2160 * @see #getLocation
2161 * @see #setBounds
2162 * @see #invalidate
2163 * @since 1.1
2164 */
2165 public void setLocation(Point p) {
2166 setLocation(p.x, p.y);
2167 }
2168
2169 /**
2170 * Returns the size of this component in the form of a
2171 * {@code Dimension} object. The {@code height}
2172 * field of the {@code Dimension} object contains
2173 * this component's height, and the {@code width}
2174 * field of the {@code Dimension} object contains
2175 * this component's width.
2176 * @return a {@code Dimension} object that indicates the
2177 * size of this component
2178 * @see #setSize
2179 * @since 1.1
2180 */
2181 public Dimension getSize() {
2182 return size();
2183 }
2184
2185 /**
2186 * Returns the size of this component in the form of a
2187 * {@code Dimension} object.
2188 *
2189 * @return the {@code Dimension} object that indicates the
2190 * size of this component
2191 * @deprecated As of JDK version 1.1,
2192 * replaced by {@code getSize()}.
2193 */
2194 @Deprecated
2195 public Dimension size() {
2196 return new Dimension(width, height);
2197 }
2198
2199 /**
2200 * Resizes this component so that it has width {@code width}
2201 * and height {@code height}.
2202 * <p>
2203 * This method changes layout-related information, and therefore,
2204 * invalidates the component hierarchy.
2205 *
2206 * @param width the new width of this component in pixels
2207 * @param height the new height of this component in pixels
2208 * @see #getSize
2209 * @see #setBounds
2210 * @see #invalidate
2211 * @since 1.1
2212 */
2213 public void setSize(int width, int height) {
2214 resize(width, height);
2215 }
2216
2217 /**
2218 * Resizes this component.
2219 *
2220 * @param width the new width of the component
2221 * @param height the new height of the component
2222 * @deprecated As of JDK version 1.1,
2223 * replaced by {@code setSize(int, int)}.
2224 */
2225 @Deprecated
2226 public void resize(int width, int height) {
2227 synchronized(getTreeLock()) {
2228 setBoundsOp(ComponentPeer.SET_SIZE);
2229 setBounds(x, y, width, height);
2230 }
2231 }
2232
2233 /**
2234 * Resizes this component so that it has width {@code d.width}
2235 * and height {@code d.height}.
2236 * <p>
2237 * This method changes layout-related information, and therefore,
2238 * invalidates the component hierarchy.
2239 *
2240 * @param d the dimension specifying the new size
2241 * of this component
2242 * @throws NullPointerException if {@code d} is {@code null}
2243 * @see #setSize
2244 * @see #setBounds
2245 * @see #invalidate
2246 * @since 1.1
2247 */
2248 public void setSize(Dimension d) {
2249 resize(d);
2250 }
2251
2252 /**
2253 * Resizes this component so that it has width {@code d.width}
2254 * and height {@code d.height}.
2255 *
2256 * @param d the new size of this component
2257 * @deprecated As of JDK version 1.1,
2258 * replaced by {@code setSize(Dimension)}.
2259 */
2260 @Deprecated
2261 public void resize(Dimension d) {
2262 setSize(d.width, d.height);
2263 }
2264
2265 /**
2266 * Gets the bounds of this component in the form of a
2267 * {@code Rectangle} object. The bounds specify this
2268 * component's width, height, and location relative to
2269 * its parent.
2270 * @return a rectangle indicating this component's bounds
2271 * @see #setBounds
2272 * @see #getLocation
2273 * @see #getSize
2274 */
2275 public Rectangle getBounds() {
2276 return bounds();
2277 }
2278
2279 /**
2280 * Returns the bounding rectangle of this component.
2281 *
2282 * @return the bounding rectangle for this component
2283 * @deprecated As of JDK version 1.1,
2284 * replaced by {@code getBounds()}.
2285 */
2286 @Deprecated
2287 public Rectangle bounds() {
2288 return new Rectangle(x, y, width, height);
2289 }
2290
2291 /**
2292 * Moves and resizes this component. The new location of the top-left
2293 * corner is specified by {@code x} and {@code y}, and the
2294 * new size is specified by {@code width} and {@code height}.
2295 * <p>
2296 * This method changes layout-related information, and therefore,
2297 * invalidates the component hierarchy.
2298 *
2299 * @param x the new <i>x</i>-coordinate of this component
2300 * @param y the new <i>y</i>-coordinate of this component
2301 * @param width the new {@code width} of this component
2302 * @param height the new {@code height} of this
2303 * component
2304 * @see #getBounds
2305 * @see #setLocation(int, int)
2306 * @see #setLocation(Point)
2307 * @see #setSize(int, int)
2308 * @see #setSize(Dimension)
2309 * @see #invalidate
2310 * @since 1.1
2311 */
2312 public void setBounds(int x, int y, int width, int height) {
2313 reshape(x, y, width, height);
2314 }
2315
2316 /**
2317 * Reshapes the bounding rectangle for this component.
2318 *
2319 * @param x the <i>x</i> coordinate of the upper left corner of the rectangle
2320 * @param y the <i>y</i> coordinate of the upper left corner of the rectangle
2321 * @param width the width of the rectangle
2322 * @param height the height of the rectangle
2323 *
2324 * @deprecated As of JDK version 1.1,
2325 * replaced by {@code setBounds(int, int, int, int)}.
2326 */
2327 @Deprecated
2328 public void reshape(int x, int y, int width, int height) {
2329 synchronized (getTreeLock()) {
2330 try {
2331 setBoundsOp(ComponentPeer.SET_BOUNDS);
2332 boolean resized = (this.width != width) || (this.height != height);
2333 boolean moved = (this.x != x) || (this.y != y);
2334 if (!resized && !moved) {
2335 return;
2336 }
2337 int oldX = this.x;
2338 int oldY = this.y;
2339 int oldWidth = this.width;
2340 int oldHeight = this.height;
2341 this.x = x;
2342 this.y = y;
2343 this.width = width;
2344 this.height = height;
2345
2425 }
2426 } else {
2427 if (this instanceof Container && ((Container)this).countComponents() > 0) {
2428 boolean enabledOnToolkit =
2429 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
2430 if (resized) {
2431
2432 ((Container)this).createChildHierarchyEvents(
2433 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);
2434 }
2435 if (moved) {
2436 ((Container)this).createChildHierarchyEvents(
2437 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);
2438 }
2439 }
2440 }
2441 }
2442
2443 /**
2444 * Moves and resizes this component to conform to the new
2445 * bounding rectangle {@code r}. This component's new
2446 * position is specified by {@code r.x} and {@code r.y},
2447 * and its new size is specified by {@code r.width} and
2448 * {@code r.height}
2449 * <p>
2450 * This method changes layout-related information, and therefore,
2451 * invalidates the component hierarchy.
2452 *
2453 * @param r the new bounding rectangle for this component
2454 * @throws NullPointerException if {@code r} is {@code null}
2455 * @see #getBounds
2456 * @see #setLocation(int, int)
2457 * @see #setLocation(Point)
2458 * @see #setSize(int, int)
2459 * @see #setSize(Dimension)
2460 * @see #invalidate
2461 * @since 1.1
2462 */
2463 public void setBounds(Rectangle r) {
2464 setBounds(r.x, r.y, r.width, r.height);
2465 }
2466
2467
2468 /**
2469 * Returns the current x coordinate of the components origin.
2470 * This method is preferable to writing
2471 * {@code component.getBounds().x},
2472 * or {@code component.getLocation().x} because it doesn't
2473 * cause any heap allocations.
2474 *
2475 * @return the current x coordinate of the components origin
2476 * @since 1.2
2477 */
2478 public int getX() {
2479 return x;
2480 }
2481
2482
2483 /**
2484 * Returns the current y coordinate of the components origin.
2485 * This method is preferable to writing
2486 * {@code component.getBounds().y},
2487 * or {@code component.getLocation().y} because it
2488 * doesn't cause any heap allocations.
2489 *
2490 * @return the current y coordinate of the components origin
2491 * @since 1.2
2492 */
2493 public int getY() {
2494 return y;
2495 }
2496
2497
2498 /**
2499 * Returns the current width of this component.
2500 * This method is preferable to writing
2501 * {@code component.getBounds().width},
2502 * or {@code component.getSize().width} because it
2503 * doesn't cause any heap allocations.
2504 *
2505 * @return the current width of this component
2506 * @since 1.2
2507 */
2508 public int getWidth() {
2509 return width;
2510 }
2511
2512
2513 /**
2514 * Returns the current height of this component.
2515 * This method is preferable to writing
2516 * {@code component.getBounds().height},
2517 * or {@code component.getSize().height} because it
2518 * doesn't cause any heap allocations.
2519 *
2520 * @return the current height of this component
2521 * @since 1.2
2522 */
2523 public int getHeight() {
2524 return height;
2525 }
2526
2527 /**
2528 * Stores the bounds of this component into "return value" <b>rv</b> and
2529 * return <b>rv</b>. If rv is {@code null} a new
2530 * {@code Rectangle} is allocated.
2531 * This version of {@code getBounds} is useful if the caller
2532 * wants to avoid allocating a new {@code Rectangle} object
2533 * on the heap.
2534 *
2535 * @param rv the return value, modified to the components bounds
2536 * @return rv
2537 */
2538 public Rectangle getBounds(Rectangle rv) {
2539 if (rv == null) {
2540 return new Rectangle(getX(), getY(), getWidth(), getHeight());
2541 }
2542 else {
2543 rv.setBounds(getX(), getY(), getWidth(), getHeight());
2544 return rv;
2545 }
2546 }
2547
2548 /**
2549 * Stores the width/height of this component into "return value" <b>rv</b>
2550 * and return <b>rv</b>. If rv is {@code null} a new
2551 * {@code Dimension} object is allocated. This version of
2552 * {@code getSize} is useful if the caller wants to avoid
2553 * allocating a new {@code Dimension} object on the heap.
2554 *
2555 * @param rv the return value, modified to the components size
2556 * @return rv
2557 */
2558 public Dimension getSize(Dimension rv) {
2559 if (rv == null) {
2560 return new Dimension(getWidth(), getHeight());
2561 }
2562 else {
2563 rv.setSize(getWidth(), getHeight());
2564 return rv;
2565 }
2566 }
2567
2568 /**
2569 * Stores the x,y origin of this component into "return value" <b>rv</b>
2570 * and return <b>rv</b>. If rv is {@code null} a new
2571 * {@code Point} is allocated.
2572 * This version of {@code getLocation} is useful if the
2573 * caller wants to avoid allocating a new {@code Point}
2574 * object on the heap.
2575 *
2576 * @param rv the return value, modified to the components location
2577 * @return rv
2578 */
2579 public Point getLocation(Point rv) {
2580 if (rv == null) {
2581 return new Point(getX(), getY());
2582 }
2583 else {
2584 rv.setLocation(getX(), getY());
2585 return rv;
2586 }
2587 }
2588
2589 /**
2590 * Returns true if this component is completely opaque, returns
2591 * false by default.
2592 * <p>
2593 * An opaque component paints every pixel within its
2598 * <p>
2599 * Subclasses that guarantee to always completely paint their
2600 * contents should override this method and return true.
2601 *
2602 * @return true if this component is completely opaque
2603 * @see #isLightweight
2604 * @since 1.2
2605 */
2606 public boolean isOpaque() {
2607 if (peer == null) {
2608 return false;
2609 }
2610 else {
2611 return !isLightweight();
2612 }
2613 }
2614
2615
2616 /**
2617 * A lightweight component doesn't have a native toolkit peer.
2618 * Subclasses of {@code Component} and {@code Container},
2619 * other than the ones defined in this package like {@code Button}
2620 * or {@code Scrollbar}, are lightweight.
2621 * All of the Swing components are lightweights.
2622 * <p>
2623 * This method will always return {@code false} if this component
2624 * is not displayable because it is impossible to determine the
2625 * weight of an undisplayable component.
2626 *
2627 * @return true if this component has a lightweight peer; false if
2628 * it has a native peer or no peer
2629 * @see #isDisplayable
2630 * @since 1.2
2631 */
2632 public boolean isLightweight() {
2633 return peer instanceof LightweightPeer;
2634 }
2635
2636
2637 /**
2638 * Sets the preferred size of this component to a constant
2639 * value. Subsequent calls to {@code getPreferredSize} will always
2640 * return this value. Setting the preferred size to {@code null}
2641 * restores the default behavior.
2642 *
2643 * @param preferredSize The new preferred size, or null
2644 * @see #getPreferredSize
2645 * @see #isPreferredSizeSet
2646 * @since 1.5
2647 */
2648 public void setPreferredSize(Dimension preferredSize) {
2649 Dimension old;
2650 // If the preferred size was set, use it as the old value, otherwise
2651 // use null to indicate we didn't previously have a set preferred
2652 // size.
2653 if (prefSizeSet) {
2654 old = this.prefSize;
2655 }
2656 else {
2657 old = null;
2658 }
2659 this.prefSize = preferredSize;
2660 prefSizeSet = (preferredSize != null);
2661 firePropertyChange("preferredSize", old, preferredSize);
2662 }
2663
2664
2665 /**
2666 * Returns true if the preferred size has been set to a
2667 * non-{@code null} value otherwise returns false.
2668 *
2669 * @return true if {@code setPreferredSize} has been invoked
2670 * with a non-null value.
2671 * @since 1.5
2672 */
2673 public boolean isPreferredSizeSet() {
2674 return prefSizeSet;
2675 }
2676
2677
2678 /**
2679 * Gets the preferred size of this component.
2680 * @return a dimension object indicating this component's preferred size
2681 * @see #getMinimumSize
2682 * @see LayoutManager
2683 */
2684 public Dimension getPreferredSize() {
2685 return preferredSize();
2686 }
2687
2688
2689 /**
2690 * Returns the component's preferred size.
2691 *
2692 * @return the component's preferred size
2693 * @deprecated As of JDK version 1.1,
2694 * replaced by {@code getPreferredSize()}.
2695 */
2696 @Deprecated
2697 public Dimension preferredSize() {
2698 /* Avoid grabbing the lock if a reasonable cached size value
2699 * is available.
2700 */
2701 Dimension dim = prefSize;
2702 if (dim == null || !(isPreferredSizeSet() || isValid())) {
2703 synchronized (getTreeLock()) {
2704 prefSize = (peer != null) ?
2705 peer.getPreferredSize() :
2706 getMinimumSize();
2707 dim = prefSize;
2708 }
2709 }
2710 return new Dimension(dim);
2711 }
2712
2713 /**
2714 * Sets the minimum size of this component to a constant
2715 * value. Subsequent calls to {@code getMinimumSize} will always
2716 * return this value. Setting the minimum size to {@code null}
2717 * restores the default behavior.
2718 *
2719 * @param minimumSize the new minimum size of this component
2720 * @see #getMinimumSize
2721 * @see #isMinimumSizeSet
2722 * @since 1.5
2723 */
2724 public void setMinimumSize(Dimension minimumSize) {
2725 Dimension old;
2726 // If the minimum size was set, use it as the old value, otherwise
2727 // use null to indicate we didn't previously have a set minimum
2728 // size.
2729 if (minSizeSet) {
2730 old = this.minSize;
2731 }
2732 else {
2733 old = null;
2734 }
2735 this.minSize = minimumSize;
2736 minSizeSet = (minimumSize != null);
2737 firePropertyChange("minimumSize", old, minimumSize);
2738 }
2739
2740 /**
2741 * Returns whether or not {@code setMinimumSize} has been
2742 * invoked with a non-null value.
2743 *
2744 * @return true if {@code setMinimumSize} has been invoked with a
2745 * non-null value.
2746 * @since 1.5
2747 */
2748 public boolean isMinimumSizeSet() {
2749 return minSizeSet;
2750 }
2751
2752 /**
2753 * Gets the minimum size of this component.
2754 * @return a dimension object indicating this component's minimum size
2755 * @see #getPreferredSize
2756 * @see LayoutManager
2757 */
2758 public Dimension getMinimumSize() {
2759 return minimumSize();
2760 }
2761
2762 /**
2763 * Returns the minimum size of this component.
2764 *
2765 * @return the minimum size of this component
2766 * @deprecated As of JDK version 1.1,
2767 * replaced by {@code getMinimumSize()}.
2768 */
2769 @Deprecated
2770 public Dimension minimumSize() {
2771 /* Avoid grabbing the lock if a reasonable cached size value
2772 * is available.
2773 */
2774 Dimension dim = minSize;
2775 if (dim == null || !(isMinimumSizeSet() || isValid())) {
2776 synchronized (getTreeLock()) {
2777 minSize = (peer != null) ?
2778 peer.getMinimumSize() :
2779 size();
2780 dim = minSize;
2781 }
2782 }
2783 return new Dimension(dim);
2784 }
2785
2786 /**
2787 * Sets the maximum size of this component to a constant
2788 * value. Subsequent calls to {@code getMaximumSize} will always
2789 * return this value. Setting the maximum size to {@code null}
2790 * restores the default behavior.
2791 *
2792 * @param maximumSize a {@code Dimension} containing the
2793 * desired maximum allowable size
2794 * @see #getMaximumSize
2795 * @see #isMaximumSizeSet
2796 * @since 1.5
2797 */
2798 public void setMaximumSize(Dimension maximumSize) {
2799 // If the maximum size was set, use it as the old value, otherwise
2800 // use null to indicate we didn't previously have a set maximum
2801 // size.
2802 Dimension old;
2803 if (maxSizeSet) {
2804 old = this.maxSize;
2805 }
2806 else {
2807 old = null;
2808 }
2809 this.maxSize = maximumSize;
2810 maxSizeSet = (maximumSize != null);
2811 firePropertyChange("maximumSize", old, maximumSize);
2812 }
2813
2814 /**
2815 * Returns true if the maximum size has been set to a non-{@code null}
2816 * value otherwise returns false.
2817 *
2818 * @return true if {@code maximumSize} is non-{@code null},
2819 * false otherwise
2820 * @since 1.5
2821 */
2822 public boolean isMaximumSizeSet() {
2823 return maxSizeSet;
2824 }
2825
2826 /**
2827 * Gets the maximum size of this component.
2828 * @return a dimension object indicating this component's maximum size
2829 * @see #getMinimumSize
2830 * @see #getPreferredSize
2831 * @see LayoutManager
2832 */
2833 public Dimension getMaximumSize() {
2834 if (isMaximumSizeSet()) {
2835 return new Dimension(maxSize);
2836 }
2837 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
2838 }
2849 public float getAlignmentX() {
2850 return CENTER_ALIGNMENT;
2851 }
2852
2853 /**
2854 * Returns the alignment along the y axis. This specifies how
2855 * the component would like to be aligned relative to other
2856 * components. The value should be a number between 0 and 1
2857 * where 0 represents alignment along the origin, 1 is aligned
2858 * the furthest away from the origin, 0.5 is centered, etc.
2859 *
2860 * @return the vertical alignment of this component
2861 */
2862 public float getAlignmentY() {
2863 return CENTER_ALIGNMENT;
2864 }
2865
2866 /**
2867 * Returns the baseline. The baseline is measured from the top of
2868 * the component. This method is primarily meant for
2869 * {@code LayoutManager}s to align components along their
2870 * baseline. A return value less than 0 indicates this component
2871 * does not have a reasonable baseline and that
2872 * {@code LayoutManager}s should not align this component on
2873 * its baseline.
2874 * <p>
2875 * The default implementation returns -1. Subclasses that support
2876 * baseline should override appropriately. If a value >= 0 is
2877 * returned, then the component has a valid baseline for any
2878 * size >= the minimum size and {@code getBaselineResizeBehavior}
2879 * can be used to determine how the baseline changes with size.
2880 *
2881 * @param width the width to get the baseline for
2882 * @param height the height to get the baseline for
2883 * @return the baseline or < 0 indicating there is no reasonable
2884 * baseline
2885 * @throws IllegalArgumentException if width or height is < 0
2886 * @see #getBaselineResizeBehavior
2887 * @see java.awt.FontMetrics
2888 * @since 1.6
2889 */
2890 public int getBaseline(int width, int height) {
2891 if (width < 0 || height < 0) {
2892 throw new IllegalArgumentException(
2893 "Width and height must be >= 0");
2894 }
2895 return -1;
2896 }
2897
2898 /**
2899 * Returns an enum indicating how the baseline of the component
2900 * changes as the size changes. This method is primarily meant for
2901 * layout managers and GUI builders.
2902 * <p>
2903 * The default implementation returns
2904 * {@code BaselineResizeBehavior.OTHER}. Subclasses that have a
2905 * baseline should override appropriately. Subclasses should
2906 * never return {@code null}; if the baseline can not be
2907 * calculated return {@code BaselineResizeBehavior.OTHER}. Callers
2908 * should first ask for the baseline using
2909 * {@code getBaseline} and if a value >= 0 is returned use
2910 * this method. It is acceptable for this method to return a
2911 * value other than {@code BaselineResizeBehavior.OTHER} even if
2912 * {@code getBaseline} returns a value less than 0.
2913 *
2914 * @return an enum indicating how the baseline changes as the component
2915 * size changes
2916 * @see #getBaseline(int, int)
2917 * @since 1.6
2918 */
2919 public BaselineResizeBehavior getBaselineResizeBehavior() {
2920 return BaselineResizeBehavior.OTHER;
2921 }
2922
2923 /**
2924 * Prompts the layout manager to lay out this component. This is
2925 * usually called when the component (more specifically, container)
2926 * is validated.
2927 * @see #validate
2928 * @see LayoutManager
2929 */
2930 public void doLayout() {
2931 layout();
2932 }
2933
2934 /**
2935 * @deprecated As of JDK version 1.1,
2936 * replaced by {@code doLayout()}.
2937 */
2938 @Deprecated
2939 public void layout() {
2940 }
2941
2942 /**
2943 * Validates this component.
2944 * <p>
2945 * The meaning of the term <i>validating</i> is defined by the ancestors of
2946 * this class. See {@link Container#validate} for more details.
2947 *
2948 * @see #invalidate
2949 * @see #doLayout()
2950 * @see LayoutManager
2951 * @see Container#validate
2952 * @since 1.0
2953 */
2954 public void validate() {
2955 synchronized (getTreeLock()) {
2956 ComponentPeer peer = this.peer;
3065 // There's no parents. Just validate itself.
3066 validate();
3067 } else {
3068 while (!root.isValidateRoot()) {
3069 if (root.getContainer() == null) {
3070 // If there's no validate roots, we'll validate the
3071 // topmost container
3072 break;
3073 }
3074
3075 root = root.getContainer();
3076 }
3077
3078 root.validate();
3079 }
3080 }
3081 }
3082
3083 /**
3084 * Creates a graphics context for this component. This method will
3085 * return {@code null} if this component is currently not
3086 * displayable.
3087 * @return a graphics context for this component, or {@code null}
3088 * if it has none
3089 * @see #paint
3090 * @since 1.0
3091 */
3092 public Graphics getGraphics() {
3093 if (peer instanceof LightweightPeer) {
3094 // This is for a lightweight component, need to
3095 // translate coordinate spaces and clip relative
3096 // to the parent.
3097 if (parent == null) return null;
3098 Graphics g = parent.getGraphics();
3099 if (g == null) return null;
3100 if (g instanceof ConstrainableGraphics) {
3101 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3102 } else {
3103 g.translate(x,y);
3104 g.setClip(0, 0, width, height);
3105 }
3106 g.setFont(getFont());
3107 return g;
3129 }
3130 g.setFont(getFont_NoClientCode());
3131 return g;
3132 } else {
3133 return (peer != null) ? peer.getGraphics() : null;
3134 }
3135 }
3136
3137 /**
3138 * Gets the font metrics for the specified font.
3139 * Warning: Since Font metrics are affected by the
3140 * {@link java.awt.font.FontRenderContext FontRenderContext} and
3141 * this method does not provide one, it can return only metrics for
3142 * the default render context which may not match that used when
3143 * rendering on the Component if {@link Graphics2D} functionality is being
3144 * used. Instead metrics can be obtained at rendering time by calling
3145 * {@link Graphics#getFontMetrics()} or text measurement APIs on the
3146 * {@link Font Font} class.
3147 * @param font the font for which font metrics is to be
3148 * obtained
3149 * @return the font metrics for {@code font}
3150 * @see #getFont
3151 * @see java.awt.peer.ComponentPeer#getFontMetrics(Font)
3152 * @see Toolkit#getFontMetrics(Font)
3153 * @since 1.0
3154 */
3155 public FontMetrics getFontMetrics(Font font) {
3156 // This is an unsupported hack, but left in for a customer.
3157 // Do not remove.
3158 FontManager fm = FontManagerFactory.getInstance();
3159 if (fm instanceof SunFontManager
3160 && ((SunFontManager) fm).usePlatformFontMetrics()) {
3161
3162 if (peer != null &&
3163 !(peer instanceof LightweightPeer)) {
3164 return peer.getFontMetrics(font);
3165 }
3166 }
3167 return sun.font.FontDesignMetrics.getMetrics(font);
3168 }
3169
3170 /**
3171 * Sets the cursor image to the specified cursor. This cursor
3172 * image is displayed when the {@code contains} method for
3173 * this component returns true for the current cursor location, and
3174 * this Component is visible, displayable, and enabled. Setting the
3175 * cursor of a {@code Container} causes that cursor to be displayed
3176 * within all of the container's subcomponents, except for those
3177 * that have a non-{@code null} cursor.
3178 * <p>
3179 * The method may have no visual effect if the Java platform
3180 * implementation and/or the native system do not support
3181 * changing the mouse cursor shape.
3182 * @param cursor One of the constants defined
3183 * by the {@code Cursor} class;
3184 * if this parameter is {@code null}
3185 * then this component will inherit
3186 * the cursor of its parent
3187 * @see #isEnabled
3188 * @see #isShowing
3189 * @see #getCursor
3190 * @see #contains
3191 * @see Toolkit#createCustomCursor
3192 * @see Cursor
3193 * @since 1.1
3194 */
3195 public void setCursor(Cursor cursor) {
3196 this.cursor = cursor;
3197 updateCursorImmediately();
3198 }
3199
3200 /**
3201 * Updates the cursor. May not be invoked from the native
3202 * message pump.
3203 */
3204 final void updateCursorImmediately() {
3205 if (peer instanceof LightweightPeer) {
3206 Container nativeContainer = getNativeContainer();
3207
3208 if (nativeContainer == null) return;
3209
3210 ComponentPeer cPeer = nativeContainer.peer;
3211
3212 if (cPeer != null) {
3213 cPeer.updateCursorImmediately();
3214 }
3215 } else if (peer != null) {
3216 peer.updateCursorImmediately();
3217 }
3218 }
3219
3220 /**
3221 * Gets the cursor set in the component. If the component does
3222 * not have a cursor set, the cursor of its parent is returned.
3223 * If no cursor is set in the entire hierarchy,
3224 * {@code Cursor.DEFAULT_CURSOR} is returned.
3225 *
3226 * @return the cursor for this component
3227 * @see #setCursor
3228 * @since 1.1
3229 */
3230 public Cursor getCursor() {
3231 return getCursor_NoClientCode();
3232 }
3233
3234 final Cursor getCursor_NoClientCode() {
3235 Cursor cursor = this.cursor;
3236 if (cursor != null) {
3237 return cursor;
3238 }
3239 Container parent = this.parent;
3240 if (parent != null) {
3241 return parent.getCursor_NoClientCode();
3242 } else {
3243 return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
3244 }
3245 }
3246
3247 /**
3248 * Returns whether the cursor has been explicitly set for this Component.
3249 * If this method returns {@code false}, this Component is inheriting
3250 * its cursor from an ancestor.
3251 *
3252 * @return {@code true} if the cursor has been explicitly set for this
3253 * Component; {@code false} otherwise.
3254 * @since 1.4
3255 */
3256 public boolean isCursorSet() {
3257 return (cursor != null);
3258 }
3259
3260 /**
3261 * Paints this component.
3262 * <p>
3263 * This method is called when the contents of the component should
3264 * be painted; such as when the component is first being shown or
3265 * is damaged and in need of repair. The clip rectangle in the
3266 * {@code Graphics} parameter is set to the area
3267 * which needs to be painted.
3268 * Subclasses of {@code Component} that override this
3269 * method need not call {@code super.paint(g)}.
3270 * <p>
3271 * For performance reasons, {@code Component}s with zero width
3272 * or height aren't considered to need painting when they are first shown,
3273 * and also aren't considered to need repair.
3274 * <p>
3275 * <b>Note</b>: For more information on the paint mechanisms utilitized
3276 * by AWT and Swing, including information on how to write the most
3277 * efficient painting code, see
3278 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3279 *
3280 * @param g the graphics context to use for painting
3281 * @see #update
3282 * @since 1.0
3283 */
3284 public void paint(Graphics g) {
3285 }
3286
3287 /**
3288 * Updates this component.
3289 * <p>
3290 * If this component is not a lightweight component, the
3291 * AWT calls the {@code update} method in response to
3292 * a call to {@code repaint}. You can assume that
3293 * the background is not cleared.
3294 * <p>
3295 * The {@code update} method of {@code Component}
3296 * calls this component's {@code paint} method to redraw
3297 * this component. This method is commonly overridden by subclasses
3298 * which need to do additional work in response to a call to
3299 * {@code repaint}.
3300 * Subclasses of Component that override this method should either
3301 * call {@code super.update(g)}, or call {@code paint(g)}
3302 * directly from their {@code update} method.
3303 * <p>
3304 * The origin of the graphics context, its
3305 * ({@code 0}, {@code 0}) coordinate point, is the
3306 * top-left corner of this component. The clipping region of the
3307 * graphics context is the bounding rectangle of this component.
3308 *
3309 * <p>
3310 * <b>Note</b>: For more information on the paint mechanisms utilitized
3311 * by AWT and Swing, including information on how to write the most
3312 * efficient painting code, see
3313 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3314 *
3315 * @param g the specified context to use for updating
3316 * @see #paint
3317 * @see #repaint()
3318 * @since 1.0
3319 */
3320 public void update(Graphics g) {
3321 paint(g);
3322 }
3323
3324 /**
3325 * Paints this component and all of its subcomponents.
3326 * <p>
3327 * The origin of the graphics context, its
3328 * ({@code 0}, {@code 0}) coordinate point, is the
3329 * top-left corner of this component. The clipping region of the
3330 * graphics context is the bounding rectangle of this component.
3331 *
3332 * @param g the graphics context to use for painting
3333 * @see #paint
3334 * @since 1.0
3335 */
3336 public void paintAll(Graphics g) {
3337 if (isShowing()) {
3338 GraphicsCallback.PeerPaintCallback.getInstance().
3339 runOneComponent(this, new Rectangle(0, 0, width, height),
3340 g, g.getClip(),
3341 GraphicsCallback.LIGHTWEIGHTS |
3342 GraphicsCallback.HEAVYWEIGHTS);
3343 }
3344 }
3345
3346 /**
3347 * Simulates the peer callbacks into java.awt for painting of
3348 * lightweight Components.
3349 * @param g the graphics context to use for painting
3350 * @see #paintAll
3351 */
3352 void lightweightPaint(Graphics g) {
3353 paint(g);
3354 }
3355
3356 /**
3357 * Paints all the heavyweight subcomponents.
3358 */
3359 void paintHeavyweightComponents(Graphics g) {
3360 }
3361
3362 /**
3363 * Repaints this component.
3364 * <p>
3365 * If this component is a lightweight component, this method
3366 * causes a call to this component's {@code paint}
3367 * method as soon as possible. Otherwise, this method causes
3368 * a call to this component's {@code update} method as soon
3369 * as possible.
3370 * <p>
3371 * <b>Note</b>: For more information on the paint mechanisms utilitized
3372 * by AWT and Swing, including information on how to write the most
3373 * efficient painting code, see
3374 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3375
3376 *
3377 * @see #update(Graphics)
3378 * @since 1.0
3379 */
3380 public void repaint() {
3381 repaint(0, 0, 0, width, height);
3382 }
3383
3384 /**
3385 * Repaints the component. If this component is a lightweight
3386 * component, this results in a call to {@code paint}
3387 * within {@code tm} milliseconds.
3388 * <p>
3389 * <b>Note</b>: For more information on the paint mechanisms utilitized
3390 * by AWT and Swing, including information on how to write the most
3391 * efficient painting code, see
3392 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3393 *
3394 * @param tm maximum time in milliseconds before update
3395 * @see #paint
3396 * @see #update(Graphics)
3397 * @since 1.0
3398 */
3399 public void repaint(long tm) {
3400 repaint(tm, 0, 0, width, height);
3401 }
3402
3403 /**
3404 * Repaints the specified rectangle of this component.
3405 * <p>
3406 * If this component is a lightweight component, this method
3407 * causes a call to this component's {@code paint} method
3408 * as soon as possible. Otherwise, this method causes a call to
3409 * this component's {@code update} method as soon as possible.
3410 * <p>
3411 * <b>Note</b>: For more information on the paint mechanisms utilitized
3412 * by AWT and Swing, including information on how to write the most
3413 * efficient painting code, see
3414 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3415 *
3416 * @param x the <i>x</i> coordinate
3417 * @param y the <i>y</i> coordinate
3418 * @param width the width
3419 * @param height the height
3420 * @see #update(Graphics)
3421 * @since 1.0
3422 */
3423 public void repaint(int x, int y, int width, int height) {
3424 repaint(0, x, y, width, height);
3425 }
3426
3427 /**
3428 * Repaints the specified rectangle of this component within
3429 * {@code tm} milliseconds.
3430 * <p>
3431 * If this component is a lightweight component, this method causes
3432 * a call to this component's {@code paint} method.
3433 * Otherwise, this method causes a call to this component's
3434 * {@code update} method.
3435 * <p>
3436 * <b>Note</b>: For more information on the paint mechanisms utilitized
3437 * by AWT and Swing, including information on how to write the most
3438 * efficient painting code, see
3439 * <a href="http://www.oracle.com/technetwork/java/painting-140037.html">Painting in AWT and Swing</a>.
3440 *
3441 * @param tm maximum time in milliseconds before update
3442 * @param x the <i>x</i> coordinate
3443 * @param y the <i>y</i> coordinate
3444 * @param width the width
3445 * @param height the height
3446 * @see #update(Graphics)
3447 * @since 1.0
3448 */
3449 public void repaint(long tm, int x, int y, int width, int height) {
3450 if (this.peer instanceof LightweightPeer) {
3451 // Needs to be translated to parent coordinates since
3452 // a parent native container provides the actual repaint
3453 // services. Additionally, the request is restricted to
3454 // the bounds of the component.
3472 int px = this.x + x;
3473 int py = this.y + y;
3474 parent.repaint(tm, px, py, pwidth, pheight);
3475 }
3476 } else {
3477 if (isVisible() && (this.peer != null) &&
3478 (width > 0) && (height > 0)) {
3479 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
3480 new Rectangle(x, y, width, height));
3481 SunToolkit.postEvent(SunToolkit.targetToAppContext(this), e);
3482 }
3483 }
3484 }
3485
3486 /**
3487 * Prints this component. Applications should override this method
3488 * for components that must do special processing before being
3489 * printed or should be printed differently than they are painted.
3490 * <p>
3491 * The default implementation of this method calls the
3492 * {@code paint} method.
3493 * <p>
3494 * The origin of the graphics context, its
3495 * ({@code 0}, {@code 0}) coordinate point, is the
3496 * top-left corner of this component. The clipping region of the
3497 * graphics context is the bounding rectangle of this component.
3498 * @param g the graphics context to use for printing
3499 * @see #paint(Graphics)
3500 * @since 1.0
3501 */
3502 public void print(Graphics g) {
3503 paint(g);
3504 }
3505
3506 /**
3507 * Prints this component and all of its subcomponents.
3508 * <p>
3509 * The origin of the graphics context, its
3510 * ({@code 0}, {@code 0}) coordinate point, is the
3511 * top-left corner of this component. The clipping region of the
3512 * graphics context is the bounding rectangle of this component.
3513 * @param g the graphics context to use for printing
3514 * @see #print(Graphics)
3515 * @since 1.0
3516 */
3517 public void printAll(Graphics g) {
3518 if (isShowing()) {
3519 GraphicsCallback.PeerPrintCallback.getInstance().
3520 runOneComponent(this, new Rectangle(0, 0, width, height),
3521 g, g.getClip(),
3522 GraphicsCallback.LIGHTWEIGHTS |
3523 GraphicsCallback.HEAVYWEIGHTS);
3524 }
3525 }
3526
3527 /**
3528 * Simulates the peer callbacks into java.awt for printing of
3529 * lightweight Components.
3530 * @param g the graphics context to use for printing
3533 void lightweightPrint(Graphics g) {
3534 print(g);
3535 }
3536
3537 /**
3538 * Prints all the heavyweight subcomponents.
3539 */
3540 void printHeavyweightComponents(Graphics g) {
3541 }
3542
3543 private Insets getInsets_NoClientCode() {
3544 ComponentPeer peer = this.peer;
3545 if (peer instanceof ContainerPeer) {
3546 return (Insets)((ContainerPeer)peer).getInsets().clone();
3547 }
3548 return new Insets(0, 0, 0, 0);
3549 }
3550
3551 /**
3552 * Repaints the component when the image has changed.
3553 * This {@code imageUpdate} method of an {@code ImageObserver}
3554 * is called when more information about an
3555 * image which had been previously requested using an asynchronous
3556 * routine such as the {@code drawImage} method of
3557 * {@code Graphics} becomes available.
3558 * See the definition of {@code imageUpdate} for
3559 * more information on this method and its arguments.
3560 * <p>
3561 * The {@code imageUpdate} method of {@code Component}
3562 * incrementally draws an image on the component as more of the bits
3563 * of the image are available.
3564 * <p>
3565 * If the system property {@code awt.image.incrementaldraw}
3566 * is missing or has the value {@code true}, the image is
3567 * incrementally drawn. If the system property has any other value,
3568 * then the image is not drawn until it has been completely loaded.
3569 * <p>
3570 * Also, if incremental drawing is in effect, the value of the
3571 * system property {@code awt.image.redrawrate} is interpreted
3572 * as an integer to give the maximum redraw rate, in milliseconds. If
3573 * the system property is missing or cannot be interpreted as an
3574 * integer, the redraw rate is once every 100ms.
3575 * <p>
3576 * The interpretation of the {@code x}, {@code y},
3577 * {@code width}, and {@code height} arguments depends on
3578 * the value of the {@code infoflags} argument.
3579 *
3580 * @param img the image being observed
3581 * @param infoflags see {@code imageUpdate} for more information
3582 * @param x the <i>x</i> coordinate
3583 * @param y the <i>y</i> coordinate
3584 * @param w the width
3585 * @param h the height
3586 * @return {@code false} if the infoflags indicate that the
3587 * image is completely loaded; {@code true} otherwise.
3588 *
3589 * @see java.awt.image.ImageObserver
3590 * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
3591 * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)
3592 * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
3593 * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
3594 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
3595 * @since 1.0
3596 */
3597 public boolean imageUpdate(Image img, int infoflags,
3598 int x, int y, int w, int h) {
3599 int rate = -1;
3600 if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
3601 rate = 0;
3602 } else if ((infoflags & SOMEBITS) != 0) {
3603 if (isInc) {
3604 rate = incRate;
3605 if (rate < 0) {
3606 rate = 0;
3607 }
3616 /**
3617 * Creates an image from the specified image producer.
3618 * @param producer the image producer
3619 * @return the image produced
3620 * @since 1.0
3621 */
3622 public Image createImage(ImageProducer producer) {
3623 ComponentPeer peer = this.peer;
3624 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
3625 return peer.createImage(producer);
3626 }
3627 return getToolkit().createImage(producer);
3628 }
3629
3630 /**
3631 * Creates an off-screen drawable image
3632 * to be used for double buffering.
3633 * @param width the specified width
3634 * @param height the specified height
3635 * @return an off-screen drawable image, which can be used for double
3636 * buffering. The return value may be {@code null} if the
3637 * component is not displayable. This will always happen if
3638 * {@code GraphicsEnvironment.isHeadless()} returns
3639 * {@code true}.
3640 * @see #isDisplayable
3641 * @see GraphicsEnvironment#isHeadless
3642 * @since 1.0
3643 */
3644 public Image createImage(int width, int height) {
3645 ComponentPeer peer = this.peer;
3646 if (peer instanceof LightweightPeer) {
3647 if (parent != null) { return parent.createImage(width, height); }
3648 else { return null;}
3649 } else {
3650 return (peer != null) ? peer.createImage(width, height) : null;
3651 }
3652 }
3653
3654 /**
3655 * Creates a volatile off-screen drawable image
3656 * to be used for double buffering.
3657 * @param width the specified width.
3658 * @param height the specified height.
3659 * @return an off-screen drawable image, which can be used for double
3660 * buffering. The return value may be {@code null} if the
3661 * component is not displayable. This will always happen if
3662 * {@code GraphicsEnvironment.isHeadless()} returns
3663 * {@code true}.
3664 * @see java.awt.image.VolatileImage
3665 * @see #isDisplayable
3666 * @see GraphicsEnvironment#isHeadless
3667 * @since 1.4
3668 */
3669 public VolatileImage createVolatileImage(int width, int height) {
3670 ComponentPeer peer = this.peer;
3671 if (peer instanceof LightweightPeer) {
3672 if (parent != null) {
3673 return parent.createVolatileImage(width, height);
3674 }
3675 else { return null;}
3676 } else {
3677 return (peer != null) ?
3678 peer.createVolatileImage(width, height) : null;
3679 }
3680 }
3681
3682 /**
3683 * Creates a volatile off-screen drawable image, with the given capabilities.
3684 * The contents of this image may be lost at any time due
3685 * to operating system issues, so the image must be managed
3686 * via the {@code VolatileImage} interface.
3687 * @param width the specified width.
3688 * @param height the specified height.
3689 * @param caps the image capabilities
3690 * @exception AWTException if an image with the specified capabilities cannot
3691 * be created
3692 * @return a VolatileImage object, which can be used
3693 * to manage surface contents loss and capabilities.
3694 * @see java.awt.image.VolatileImage
3695 * @since 1.4
3696 */
3697 public VolatileImage createVolatileImage(int width, int height,
3698 ImageCapabilities caps) throws AWTException {
3699 // REMIND : check caps
3700 return createVolatileImage(width, height);
3701 }
3702
3703 /**
3704 * Prepares an image for rendering on this component. The image
3705 * data is downloaded asynchronously in another thread and the
3706 * appropriate screen representation of the image is generated.
3707 * @param image the {@code Image} for which to
3708 * prepare a screen representation
3709 * @param observer the {@code ImageObserver} object
3710 * to be notified as the image is being prepared
3711 * @return {@code true} if the image has already been fully
3712 * prepared; {@code false} otherwise
3713 * @since 1.0
3714 */
3715 public boolean prepareImage(Image image, ImageObserver observer) {
3716 return prepareImage(image, -1, -1, observer);
3717 }
3718
3719 /**
3720 * Prepares an image for rendering on this component at the
3721 * specified width and height.
3722 * <p>
3723 * The image data is downloaded asynchronously in another thread,
3724 * and an appropriately scaled screen representation of the image is
3725 * generated.
3726 * @param image the instance of {@code Image}
3727 * for which to prepare a screen representation
3728 * @param width the width of the desired screen representation
3729 * @param height the height of the desired screen representation
3730 * @param observer the {@code ImageObserver} object
3731 * to be notified as the image is being prepared
3732 * @return {@code true} if the image has already been fully
3733 * prepared; {@code false} otherwise
3734 * @see java.awt.image.ImageObserver
3735 * @since 1.0
3736 */
3737 public boolean prepareImage(Image image, int width, int height,
3738 ImageObserver observer) {
3739 ComponentPeer peer = this.peer;
3740 if (peer instanceof LightweightPeer) {
3741 return (parent != null)
3742 ? parent.prepareImage(image, width, height, observer)
3743 : getToolkit().prepareImage(image, width, height, observer);
3744 } else {
3745 return (peer != null)
3746 ? peer.prepareImage(image, width, height, observer)
3747 : getToolkit().prepareImage(image, width, height, observer);
3748 }
3749 }
3750
3751 /**
3752 * Returns the status of the construction of a screen representation
3753 * of the specified image.
3754 * <p>
3755 * This method does not cause the image to begin loading. An
3756 * application must use the {@code prepareImage} method
3757 * to force the loading of an image.
3758 * <p>
3759 * Information on the flags returned by this method can be found
3760 * with the discussion of the {@code ImageObserver} interface.
3761 * @param image the {@code Image} object whose status
3762 * is being checked
3763 * @param observer the {@code ImageObserver}
3764 * object to be notified as the image is being prepared
3765 * @return the bitwise inclusive <b>OR</b> of
3766 * {@code ImageObserver} flags indicating what
3767 * information about the image is currently available
3768 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3769 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3770 * @see java.awt.image.ImageObserver
3771 * @since 1.0
3772 */
3773 public int checkImage(Image image, ImageObserver observer) {
3774 return checkImage(image, -1, -1, observer);
3775 }
3776
3777 /**
3778 * Returns the status of the construction of a screen representation
3779 * of the specified image.
3780 * <p>
3781 * This method does not cause the image to begin loading. An
3782 * application must use the {@code prepareImage} method
3783 * to force the loading of an image.
3784 * <p>
3785 * The {@code checkImage} method of {@code Component}
3786 * calls its peer's {@code checkImage} method to calculate
3787 * the flags. If this component does not yet have a peer, the
3788 * component's toolkit's {@code checkImage} method is called
3789 * instead.
3790 * <p>
3791 * Information on the flags returned by this method can be found
3792 * with the discussion of the {@code ImageObserver} interface.
3793 * @param image the {@code Image} object whose status
3794 * is being checked
3795 * @param width the width of the scaled version
3796 * whose status is to be checked
3797 * @param height the height of the scaled version
3798 * whose status is to be checked
3799 * @param observer the {@code ImageObserver} object
3800 * to be notified as the image is being prepared
3801 * @return the bitwise inclusive <b>OR</b> of
3802 * {@code ImageObserver} flags indicating what
3803 * information about the image is currently available
3804 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3805 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3806 * @see java.awt.image.ImageObserver
3807 * @since 1.0
3808 */
3809 public int checkImage(Image image, int width, int height,
3810 ImageObserver observer) {
3811 ComponentPeer peer = this.peer;
3812 if (peer instanceof LightweightPeer) {
3813 return (parent != null)
3814 ? parent.checkImage(image, width, height, observer)
3815 : getToolkit().checkImage(image, width, height, observer);
3816 } else {
3817 return (peer != null)
3818 ? peer.checkImage(image, width, height, observer)
3819 : getToolkit().checkImage(image, width, height, observer);
3820 }
3821 }
3822
3823 /**
3824 * Creates a new strategy for multi-buffering on this component.
3825 * Multi-buffering is useful for rendering performance. This method
3826 * attempts to create the best strategy available with the number of
3827 * buffers supplied. It will always create a {@code BufferStrategy}
3828 * with that number of buffers.
3829 * A page-flipping strategy is attempted first, then a blitting strategy
3830 * using accelerated buffers. Finally, an unaccelerated blitting
3831 * strategy is used.
3832 * <p>
3833 * Each time this method is called,
3834 * the existing buffer strategy for this component is discarded.
3835 * @param numBuffers number of buffers to create, including the front buffer
3836 * @exception IllegalArgumentException if numBuffers is less than 1.
3837 * @exception IllegalStateException if the component is not displayable
3838 * @see #isDisplayable
3839 * @see Window#getBufferStrategy()
3840 * @see Canvas#getBufferStrategy()
3841 * @since 1.4
3842 */
3843 void createBufferStrategy(int numBuffers) {
3844 BufferCapabilities bufferCaps;
3845 if (numBuffers > 1) {
3846 // Try to create a page-flipping strategy
3847 bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3868 bufferCaps = new BufferCapabilities(new ImageCapabilities(false),
3869 new ImageCapabilities(false),
3870 null);
3871 try {
3872 createBufferStrategy(numBuffers, bufferCaps);
3873 return; // Success
3874 } catch (AWTException e) {
3875 // Code should never reach here (an unaccelerated blitting
3876 // strategy should always work)
3877 throw new InternalError("Could not create a buffer strategy", e);
3878 }
3879 }
3880
3881 /**
3882 * Creates a new strategy for multi-buffering on this component with the
3883 * required buffer capabilities. This is useful, for example, if only
3884 * accelerated memory or page flipping is desired (as specified by the
3885 * buffer capabilities).
3886 * <p>
3887 * Each time this method
3888 * is called, {@code dispose} will be invoked on the existing
3889 * {@code BufferStrategy}.
3890 * @param numBuffers number of buffers to create
3891 * @param caps the required capabilities for creating the buffer strategy;
3892 * cannot be {@code null}
3893 * @exception AWTException if the capabilities supplied could not be
3894 * supported or met; this may happen, for example, if there is not enough
3895 * accelerated memory currently available, or if page flipping is specified
3896 * but not possible.
3897 * @exception IllegalArgumentException if numBuffers is less than 1, or if
3898 * caps is {@code null}
3899 * @see Window#getBufferStrategy()
3900 * @see Canvas#getBufferStrategy()
3901 * @since 1.4
3902 */
3903 void createBufferStrategy(int numBuffers,
3904 BufferCapabilities caps) throws AWTException {
3905 // Check arguments
3906 if (numBuffers < 1) {
3907 throw new IllegalArgumentException(
3908 "Number of buffers must be at least 1");
3909 }
3910 if (caps == null) {
3911 throw new IllegalArgumentException("No capabilities specified");
3912 }
3913 // Destroy old buffers
3914 if (bufferStrategy != null) {
3915 bufferStrategy.dispose();
3916 }
3917 if (numBuffers == 1) {
3918 bufferStrategy = new SingleBufferStrategy(caps);
3963 /**
3964 * @return the back buffer currently used by this component's
3965 * BufferStrategy. If there is no BufferStrategy or no
3966 * back buffer, this method returns null.
3967 */
3968 Image getBackBuffer() {
3969 if (bufferStrategy != null) {
3970 if (bufferStrategy instanceof BltBufferStrategy) {
3971 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;
3972 return bltBS.getBackBuffer();
3973 } else if (bufferStrategy instanceof FlipBufferStrategy) {
3974 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;
3975 return flipBS.getBackBuffer();
3976 }
3977 }
3978 return null;
3979 }
3980
3981 /**
3982 * Inner class for flipping buffers on a component. That component must
3983 * be a {@code Canvas} or {@code Window} or {@code Applet}.
3984 * @see Canvas
3985 * @see Window
3986 * @see Applet
3987 * @see java.awt.image.BufferStrategy
3988 * @author Michael Martak
3989 * @since 1.4
3990 */
3991 protected class FlipBufferStrategy extends BufferStrategy {
3992 /**
3993 * The number of buffers
3994 */
3995 protected int numBuffers; // = 0
3996 /**
3997 * The buffering capabilities
3998 */
3999 protected BufferCapabilities caps; // = null
4000 /**
4001 * The drawing buffer
4002 */
4003 protected Image drawBuffer; // = null
4014 /**
4015 * Size of the back buffers. (Note: these fields were added in 6.0
4016 * but kept package-private to avoid exposing them in the spec.
4017 * None of these fields/methods really should have been marked
4018 * protected when they were introduced in 1.4, but now we just have
4019 * to live with that decision.)
4020 */
4021
4022 /**
4023 * The width of the back buffers
4024 */
4025 int width;
4026
4027 /**
4028 * The height of the back buffers
4029 */
4030 int height;
4031
4032 /**
4033 * Creates a new flipping buffer strategy for this component.
4034 * The component must be a {@code Canvas} or {@code Window} or
4035 * {@code Applet}.
4036 * @see Canvas
4037 * @see Window
4038 * @see Applet
4039 * @param numBuffers the number of buffers
4040 * @param caps the capabilities of the buffers
4041 * @exception AWTException if the capabilities supplied could not be
4042 * supported or met
4043 * @exception ClassCastException if the component is not a canvas or
4044 * window.
4045 * @exception IllegalStateException if the component has no peer
4046 * @exception IllegalArgumentException if {@code numBuffers} is less than two,
4047 * or if {@code BufferCapabilities.isPageFlipping} is not
4048 * {@code true}.
4049 * @see #createBuffers(int, BufferCapabilities)
4050 */
4051 protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)
4052 throws AWTException
4053 {
4054 if (!(Component.this instanceof Window) &&
4055 !(Component.this instanceof Canvas) &&
4056 !(Component.this instanceof Applet))
4057 {
4058 throw new ClassCastException(
4059 "Component must be a Canvas or Window or Applet");
4060 }
4061 this.numBuffers = numBuffers;
4062 this.caps = caps;
4063 createBuffers(numBuffers, caps);
4064 }
4065
4066 /**
4067 * Creates one or more complex, flipping buffers with the given
4068 * capabilities.
4069 * @param numBuffers number of buffers to create; must be greater than
4070 * one
4071 * @param caps the capabilities of the buffers.
4072 * {@code BufferCapabilities.isPageFlipping} must be
4073 * {@code true}.
4074 * @exception AWTException if the capabilities supplied could not be
4075 * supported or met
4076 * @exception IllegalStateException if the component has no peer
4077 * @exception IllegalArgumentException if numBuffers is less than two,
4078 * or if {@code BufferCapabilities.isPageFlipping} is not
4079 * {@code true}.
4080 * @see java.awt.BufferCapabilities#isPageFlipping()
4081 */
4082 protected void createBuffers(int numBuffers, BufferCapabilities caps)
4083 throws AWTException
4084 {
4085 if (numBuffers < 2) {
4086 throw new IllegalArgumentException(
4087 "Number of buffers cannot be less than two");
4088 } else if (peer == null) {
4089 throw new IllegalStateException(
4090 "Component must have a valid peer");
4091 } else if (caps == null || !caps.isPageFlipping()) {
4092 throw new IllegalArgumentException(
4093 "Page flipping capabilities must be specified");
4094 }
4095
4096 // save the current bounds
4097 width = getWidth();
4098 height = getHeight();
4099
4140
4141 /**
4142 * @return direct access to the back buffer, as an image.
4143 * @exception IllegalStateException if the buffers have not yet
4144 * been created
4145 */
4146 protected Image getBackBuffer() {
4147 if (peer != null) {
4148 return peer.getBackBuffer();
4149 } else {
4150 throw new IllegalStateException(
4151 "Component must have a valid peer");
4152 }
4153 }
4154
4155 /**
4156 * Flipping moves the contents of the back buffer to the front buffer,
4157 * either by copying or by moving the video pointer.
4158 * @param flipAction an integer value describing the flipping action
4159 * for the contents of the back buffer. This should be one of the
4160 * values of the {@code BufferCapabilities.FlipContents}
4161 * property.
4162 * @exception IllegalStateException if the buffers have not yet
4163 * been created
4164 * @see java.awt.BufferCapabilities#getFlipContents()
4165 */
4166 protected void flip(BufferCapabilities.FlipContents flipAction) {
4167 if (peer != null) {
4168 Image backBuffer = getBackBuffer();
4169 if (backBuffer != null) {
4170 peer.flip(0, 0,
4171 backBuffer.getWidth(null),
4172 backBuffer.getHeight(null), flipAction);
4173 }
4174 } else {
4175 throw new IllegalStateException(
4176 "Component must have a valid peer");
4177 }
4178 }
4179
4180 void flipSubRegion(int x1, int y1, int x2, int y2,
4254 int returnCode = drawVBuffer.validate(gc);
4255 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4256 try {
4257 createBuffers(numBuffers, caps);
4258 } catch (AWTException e) {
4259 // shouldn't be possible
4260 }
4261 if (drawVBuffer != null) {
4262 // backbuffers were recreated, so validate again
4263 drawVBuffer.validate(gc);
4264 }
4265 validatedContents = true;
4266 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4267 validatedContents = true;
4268 }
4269 }
4270 }
4271
4272 /**
4273 * @return whether the drawing buffer was lost since the last call to
4274 * {@code getDrawGraphics}
4275 */
4276 public boolean contentsLost() {
4277 if (drawVBuffer == null) {
4278 return false;
4279 }
4280 return drawVBuffer.contentsLost();
4281 }
4282
4283 /**
4284 * @return whether the drawing buffer was recently restored from a lost
4285 * state and reinitialized to the default background color (white)
4286 */
4287 public boolean contentsRestored() {
4288 return validatedContents;
4289 }
4290
4291 /**
4292 * Makes the next available buffer visible by either blitting or
4293 * flipping.
4294 */
4541 int returnCode =
4542 backBuffers[backBuffers.length - 1].validate(gc);
4543 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4544 if (checkSize) {
4545 createBackBuffers(backBuffers.length);
4546 // backbuffers were recreated, so validate again
4547 backBuffers[backBuffers.length - 1].validate(gc);
4548 }
4549 // else case means we're called from Swing on the toolkit
4550 // thread, don't recreate buffers as that'll deadlock
4551 // (creating VolatileImages invokes getting GraphicsConfig
4552 // which grabs treelock).
4553 validatedContents = true;
4554 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4555 validatedContents = true;
4556 }
4557 }
4558
4559 /**
4560 * @return whether the drawing buffer was lost since the last call to
4561 * {@code getDrawGraphics}
4562 */
4563 public boolean contentsLost() {
4564 if (backBuffers == null) {
4565 return false;
4566 } else {
4567 return backBuffers[backBuffers.length - 1].contentsLost();
4568 }
4569 }
4570
4571 /**
4572 * @return whether the drawing buffer was recently restored from a lost
4573 * state and reinitialized to the default background color (white)
4574 */
4575 public boolean contentsRestored() {
4576 return validatedContents;
4577 }
4578 } // Inner class BltBufferStrategy
4579
4580 /**
4581 * Private class to perform sub-region flipping.
4620 {
4621 super(numBuffers, caps);
4622 }
4623
4624 public void show(int x1, int y1, int x2, int y2) {
4625 showSubRegion(x1, y1, x2, y2);
4626 }
4627
4628 // This method is called by Swing on the toolkit thread.
4629 public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4630 if (!contentsLost()) {
4631 showSubRegion(x1, y1, x2, y2);
4632 return !contentsLost();
4633 }
4634 return false;
4635 }
4636 }
4637
4638 /**
4639 * Inner class for flipping buffers on a component. That component must
4640 * be a {@code Canvas} or {@code Window}.
4641 * @see Canvas
4642 * @see Window
4643 * @see java.awt.image.BufferStrategy
4644 * @author Michael Martak
4645 * @since 1.4
4646 */
4647 private class SingleBufferStrategy extends BufferStrategy {
4648
4649 private BufferCapabilities caps;
4650
4651 public SingleBufferStrategy(BufferCapabilities caps) {
4652 this.caps = caps;
4653 }
4654 public BufferCapabilities getCapabilities() {
4655 return caps;
4656 }
4657 public Graphics getDrawGraphics() {
4658 return getGraphics();
4659 }
4660 public boolean contentsLost() {
4688 * @see java.awt.image.BufferStrategy
4689 * @see GraphicsDevice#setFullScreenWindow
4690 */
4691 public void setIgnoreRepaint(boolean ignoreRepaint) {
4692 this.ignoreRepaint = ignoreRepaint;
4693 }
4694
4695 /**
4696 * @return whether or not paint messages received from the operating system
4697 * should be ignored.
4698 *
4699 * @since 1.4
4700 * @see #setIgnoreRepaint
4701 */
4702 public boolean getIgnoreRepaint() {
4703 return ignoreRepaint;
4704 }
4705
4706 /**
4707 * Checks whether this component "contains" the specified point,
4708 * where {@code x} and {@code y} are defined to be
4709 * relative to the coordinate system of this component.
4710 *
4711 * @param x the <i>x</i> coordinate of the point
4712 * @param y the <i>y</i> coordinate of the point
4713 * @return {@code true} if the point is within the component;
4714 * otherwise {@code false}
4715 * @see #getComponentAt(int, int)
4716 * @since 1.1
4717 */
4718 public boolean contains(int x, int y) {
4719 return inside(x, y);
4720 }
4721
4722 /**
4723 * Checks whether the point is inside of this component.
4724 *
4725 * @param x the <i>x</i> coordinate of the point
4726 * @param y the <i>y</i> coordinate of the point
4727 * @return {@code true} if the point is within the component;
4728 * otherwise {@code false}
4741 *
4742 * @param p the point
4743 * @return {@code true} if the point is within the component;
4744 * otherwise {@code false}
4745 * @throws NullPointerException if {@code p} is {@code null}
4746 * @see #getComponentAt(Point)
4747 * @since 1.1
4748 */
4749 public boolean contains(Point p) {
4750 return contains(p.x, p.y);
4751 }
4752
4753 /**
4754 * Determines if this component or one of its immediate
4755 * subcomponents contains the (<i>x</i>, <i>y</i>) location,
4756 * and if so, returns the containing component. This method only
4757 * looks one level deep. If the point (<i>x</i>, <i>y</i>) is
4758 * inside a subcomponent that itself has subcomponents, it does not
4759 * go looking down the subcomponent tree.
4760 * <p>
4761 * The {@code locate} method of {@code Component} simply
4762 * returns the component itself if the (<i>x</i>, <i>y</i>)
4763 * coordinate location is inside its bounding box, and {@code null}
4764 * otherwise.
4765 * @param x the <i>x</i> coordinate
4766 * @param y the <i>y</i> coordinate
4767 * @return the component or subcomponent that contains the
4768 * (<i>x</i>, <i>y</i>) location;
4769 * {@code null} if the location
4770 * is outside this component
4771 * @see #contains(int, int)
4772 * @since 1.0
4773 */
4774 public Component getComponentAt(int x, int y) {
4775 return locate(x, y);
4776 }
4777
4778 /**
4779 * Returns the component occupying the position specified (this component,
4780 * or immediate child component, or null if neither
4781 * of the first two occupies the location).
4782 *
4783 * @param x the <i>x</i> coordinate to search for components at
4784 * @param y the <i>y</i> coordinate to search for components at
4785 * @return the component at the specified location or {@code null}
4786 * @deprecated As of JDK version 1.1,
4787 * replaced by getComponentAt(int, int).
4788 */
4789 @Deprecated
4790 public Component locate(int x, int y) {
4791 return contains(x, y) ? this : null;
4792 }
4793
4794 /**
4795 * Returns the component or subcomponent that contains the
4796 * specified point.
4797 * @param p the point
4798 * @return the component at the specified location or {@code null}
4799 * @see java.awt.Component#contains
4800 * @since 1.1
4801 */
4802 public Component getComponentAt(Point p) {
4803 return getComponentAt(p.x, p.y);
4804 }
4805
4806 /**
4807 * @param e the event to deliver
4808 * @deprecated As of JDK version 1.1,
4809 * replaced by {@code dispatchEvent(AWTEvent e)}.
4810 */
4811 @Deprecated
4812 public void deliverEvent(Event e) {
4813 postEvent(e);
4814 }
4815
4816 /**
4817 * Dispatches an event to this component or one of its sub components.
4818 * Calls {@code processEvent} before returning for 1.1-style
4819 * events which have been enabled for the {@code Component}.
4820 * @param e the event
4821 */
4822 public final void dispatchEvent(AWTEvent e) {
4823 dispatchEventImpl(e);
4824 }
4825
4826 @SuppressWarnings("deprecation")
4827 void dispatchEventImpl(AWTEvent e) {
4828 int id = e.getID();
4829
4830 // Check that this component belongs to this app-context
4831 AppContext compContext = appContext;
4832 if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
4833 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
4834 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");
4835 }
4836 }
4837
4838 if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) {
4839 eventLog.finest("{0}", e);
5267 int eventx = e.x;
5268 int eventy = e.y;
5269 if (parent != null) {
5270 e.translate(x, y);
5271 if (parent.postEvent(e)) {
5272 e.consume();
5273 return true;
5274 }
5275 // restore coords
5276 e.x = eventx;
5277 e.y = eventy;
5278 }
5279 return false;
5280 }
5281
5282 // Event source interfaces
5283
5284 /**
5285 * Adds the specified component listener to receive component events from
5286 * this component.
5287 * If listener {@code l} is {@code null},
5288 * no exception is thrown and no action is performed.
5289 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5290 * >AWT Threading Issues</a> for details on AWT's threading model.
5291 *
5292 * @param l the component listener
5293 * @see java.awt.event.ComponentEvent
5294 * @see java.awt.event.ComponentListener
5295 * @see #removeComponentListener
5296 * @see #getComponentListeners
5297 * @since 1.1
5298 */
5299 public synchronized void addComponentListener(ComponentListener l) {
5300 if (l == null) {
5301 return;
5302 }
5303 componentListener = AWTEventMulticaster.add(componentListener, l);
5304 newEventsOnly = true;
5305 }
5306
5307 /**
5308 * Removes the specified component listener so that it no longer
5309 * receives component events from this component. This method performs
5310 * no function, nor does it throw an exception, if the listener
5311 * specified by the argument was not previously added to this component.
5312 * If listener {@code l} is {@code null},
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 * @param l the component listener
5317 * @see java.awt.event.ComponentEvent
5318 * @see java.awt.event.ComponentListener
5319 * @see #addComponentListener
5320 * @see #getComponentListeners
5321 * @since 1.1
5322 */
5323 public synchronized void removeComponentListener(ComponentListener l) {
5324 if (l == null) {
5325 return;
5326 }
5327 componentListener = AWTEventMulticaster.remove(componentListener, l);
5328 }
5329
5330 /**
5331 * Returns an array of all the component listeners
5332 * registered on this component.
5333 *
5334 * @return all {@code ComponentListener}s of this component
5335 * or an empty array if no component
5336 * listeners are currently registered
5337 *
5338 * @see #addComponentListener
5339 * @see #removeComponentListener
5340 * @since 1.4
5341 */
5342 public synchronized ComponentListener[] getComponentListeners() {
5343 return getListeners(ComponentListener.class);
5344 }
5345
5346 /**
5347 * Adds the specified focus listener to receive focus events from
5348 * this component when this component gains input focus.
5349 * If listener {@code l} is {@code null},
5350 * no exception is thrown and no action is performed.
5351 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5352 * >AWT Threading Issues</a> for details on AWT's threading model.
5353 *
5354 * @param l the focus listener
5355 * @see java.awt.event.FocusEvent
5356 * @see java.awt.event.FocusListener
5357 * @see #removeFocusListener
5358 * @see #getFocusListeners
5359 * @since 1.1
5360 */
5361 public synchronized void addFocusListener(FocusListener l) {
5362 if (l == null) {
5363 return;
5364 }
5365 focusListener = AWTEventMulticaster.add(focusListener, l);
5366 newEventsOnly = true;
5367
5368 // if this is a lightweight component, enable focus events
5369 // in the native container.
5370 if (peer instanceof LightweightPeer) {
5371 parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK);
5372 }
5373 }
5374
5375 /**
5376 * Removes the specified focus listener so that it no longer
5377 * receives focus events from this component. This method performs
5378 * no function, nor does it throw an exception, if the listener
5379 * specified by the argument was not previously added to this component.
5380 * If listener {@code l} is {@code null},
5381 * no exception is thrown and no action is performed.
5382 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5383 * >AWT Threading Issues</a> for details on AWT's threading model.
5384 *
5385 * @param l the focus listener
5386 * @see java.awt.event.FocusEvent
5387 * @see java.awt.event.FocusListener
5388 * @see #addFocusListener
5389 * @see #getFocusListeners
5390 * @since 1.1
5391 */
5392 public synchronized void removeFocusListener(FocusListener l) {
5393 if (l == null) {
5394 return;
5395 }
5396 focusListener = AWTEventMulticaster.remove(focusListener, l);
5397 }
5398
5399 /**
5400 * Returns an array of all the focus listeners
5401 * registered on this component.
5402 *
5403 * @return all of this component's {@code FocusListener}s
5404 * or an empty array if no component
5405 * listeners are currently registered
5406 *
5407 * @see #addFocusListener
5408 * @see #removeFocusListener
5409 * @since 1.4
5410 */
5411 public synchronized FocusListener[] getFocusListeners() {
5412 return getListeners(FocusListener.class);
5413 }
5414
5415 /**
5416 * Adds the specified hierarchy listener to receive hierarchy changed
5417 * events from this component when the hierarchy to which this container
5418 * belongs changes.
5419 * If listener {@code l} is {@code null},
5420 * no exception is thrown and no action is performed.
5421 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5422 * >AWT Threading Issues</a> for details on AWT's threading model.
5423 *
5424 * @param l the hierarchy listener
5425 * @see java.awt.event.HierarchyEvent
5426 * @see java.awt.event.HierarchyListener
5427 * @see #removeHierarchyListener
5428 * @see #getHierarchyListeners
5429 * @since 1.3
5430 */
5431 public void addHierarchyListener(HierarchyListener l) {
5432 if (l == null) {
5433 return;
5434 }
5435 boolean notifyAncestors;
5436 synchronized (this) {
5437 notifyAncestors =
5438 (hierarchyListener == null &&
5439 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5440 hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l);
5441 notifyAncestors = (notifyAncestors && hierarchyListener != null);
5442 newEventsOnly = true;
5443 }
5444 if (notifyAncestors) {
5445 synchronized (getTreeLock()) {
5446 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5447 1);
5448 }
5449 }
5450 }
5451
5452 /**
5453 * Removes the specified hierarchy listener so that it no longer
5454 * receives hierarchy changed events from this component. This method
5455 * performs no function, nor does it throw an exception, if the listener
5456 * specified by the argument was not previously added to this component.
5457 * If listener {@code l} is {@code null},
5458 * no exception is thrown and no action is performed.
5459 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5460 * >AWT Threading Issues</a> for details on AWT's threading model.
5461 *
5462 * @param l the hierarchy listener
5463 * @see java.awt.event.HierarchyEvent
5464 * @see java.awt.event.HierarchyListener
5465 * @see #addHierarchyListener
5466 * @see #getHierarchyListeners
5467 * @since 1.3
5468 */
5469 public void removeHierarchyListener(HierarchyListener l) {
5470 if (l == null) {
5471 return;
5472 }
5473 boolean notifyAncestors;
5474 synchronized (this) {
5475 notifyAncestors =
5476 (hierarchyListener != null &&
5477 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0);
5478 hierarchyListener =
5479 AWTEventMulticaster.remove(hierarchyListener, l);
5480 notifyAncestors = (notifyAncestors && hierarchyListener == null);
5481 }
5482 if (notifyAncestors) {
5483 synchronized (getTreeLock()) {
5484 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK,
5485 -1);
5486 }
5487 }
5488 }
5489
5490 /**
5491 * Returns an array of all the hierarchy listeners
5492 * registered on this component.
5493 *
5494 * @return all of this component's {@code HierarchyListener}s
5495 * or an empty array if no hierarchy
5496 * listeners are currently registered
5497 *
5498 * @see #addHierarchyListener
5499 * @see #removeHierarchyListener
5500 * @since 1.4
5501 */
5502 public synchronized HierarchyListener[] getHierarchyListeners() {
5503 return getListeners(HierarchyListener.class);
5504 }
5505
5506 /**
5507 * Adds the specified hierarchy bounds listener to receive hierarchy
5508 * bounds events from this component when the hierarchy to which this
5509 * container belongs changes.
5510 * If listener {@code l} is {@code null},
5511 * no exception is thrown and no action is performed.
5512 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5513 * >AWT Threading Issues</a> for details on AWT's threading model.
5514 *
5515 * @param l the hierarchy bounds listener
5516 * @see java.awt.event.HierarchyEvent
5517 * @see java.awt.event.HierarchyBoundsListener
5518 * @see #removeHierarchyBoundsListener
5519 * @see #getHierarchyBoundsListeners
5520 * @since 1.3
5521 */
5522 public void addHierarchyBoundsListener(HierarchyBoundsListener l) {
5523 if (l == null) {
5524 return;
5525 }
5526 boolean notifyAncestors;
5527 synchronized (this) {
5528 notifyAncestors =
5529 (hierarchyBoundsListener == null &&
5530 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5531 hierarchyBoundsListener =
5532 AWTEventMulticaster.add(hierarchyBoundsListener, l);
5533 notifyAncestors = (notifyAncestors &&
5534 hierarchyBoundsListener != null);
5535 newEventsOnly = true;
5536 }
5537 if (notifyAncestors) {
5538 synchronized (getTreeLock()) {
5539 adjustListeningChildrenOnParent(
5540 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1);
5541 }
5542 }
5543 }
5544
5545 /**
5546 * Removes the specified hierarchy bounds listener so that it no longer
5547 * receives hierarchy bounds events from this component. This method
5548 * performs no function, nor does it throw an exception, if the listener
5549 * specified by the argument was not previously added to this component.
5550 * If listener {@code l} is {@code null},
5551 * no exception is thrown and no action is performed.
5552 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5553 * >AWT Threading Issues</a> for details on AWT's threading model.
5554 *
5555 * @param l the hierarchy bounds listener
5556 * @see java.awt.event.HierarchyEvent
5557 * @see java.awt.event.HierarchyBoundsListener
5558 * @see #addHierarchyBoundsListener
5559 * @see #getHierarchyBoundsListeners
5560 * @since 1.3
5561 */
5562 public void removeHierarchyBoundsListener(HierarchyBoundsListener l) {
5563 if (l == null) {
5564 return;
5565 }
5566 boolean notifyAncestors;
5567 synchronized (this) {
5568 notifyAncestors =
5569 (hierarchyBoundsListener != null &&
5570 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0);
5636 HierarchyEvent e = new HierarchyEvent(this, id, changed,
5637 changedParent);
5638 dispatchEvent(e);
5639 return 1;
5640 }
5641 break;
5642 default:
5643 // assert false
5644 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) {
5645 eventLog.fine("This code must never be reached");
5646 }
5647 break;
5648 }
5649 return 0;
5650 }
5651
5652 /**
5653 * Returns an array of all the hierarchy bounds listeners
5654 * registered on this component.
5655 *
5656 * @return all of this component's {@code HierarchyBoundsListener}s
5657 * or an empty array if no hierarchy bounds
5658 * listeners are currently registered
5659 *
5660 * @see #addHierarchyBoundsListener
5661 * @see #removeHierarchyBoundsListener
5662 * @since 1.4
5663 */
5664 public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() {
5665 return getListeners(HierarchyBoundsListener.class);
5666 }
5667
5668 /*
5669 * Should only be called while holding the tree lock.
5670 * It's added only for overriding in java.awt.Window
5671 * because parent in Window is owner.
5672 */
5673 void adjustListeningChildrenOnParent(long mask, int num) {
5674 if (parent != null) {
5675 parent.adjustListeningChildren(mask, num);
5676 }
5692 */
5693 public synchronized void addKeyListener(KeyListener l) {
5694 if (l == null) {
5695 return;
5696 }
5697 keyListener = AWTEventMulticaster.add(keyListener, l);
5698 newEventsOnly = true;
5699
5700 // if this is a lightweight component, enable key events
5701 // in the native container.
5702 if (peer instanceof LightweightPeer) {
5703 parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK);
5704 }
5705 }
5706
5707 /**
5708 * Removes the specified key listener so that it no longer
5709 * receives key events from this component. This method performs
5710 * no function, nor does it throw an exception, if the listener
5711 * specified by the argument was not previously added to this component.
5712 * If listener {@code l} is {@code null},
5713 * no exception is thrown and no action is performed.
5714 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5715 * >AWT Threading Issues</a> for details on AWT's threading model.
5716 *
5717 * @param l the key listener
5718 * @see java.awt.event.KeyEvent
5719 * @see java.awt.event.KeyListener
5720 * @see #addKeyListener
5721 * @see #getKeyListeners
5722 * @since 1.1
5723 */
5724 public synchronized void removeKeyListener(KeyListener l) {
5725 if (l == null) {
5726 return;
5727 }
5728 keyListener = AWTEventMulticaster.remove(keyListener, l);
5729 }
5730
5731 /**
5732 * Returns an array of all the key listeners
5733 * registered on this component.
5734 *
5735 * @return all of this component's {@code KeyListener}s
5736 * or an empty array if no key
5737 * listeners are currently registered
5738 *
5739 * @see #addKeyListener
5740 * @see #removeKeyListener
5741 * @since 1.4
5742 */
5743 public synchronized KeyListener[] getKeyListeners() {
5744 return getListeners(KeyListener.class);
5745 }
5746
5747 /**
5748 * Adds the specified mouse listener to receive mouse events from
5749 * this component.
5750 * If listener {@code l} is {@code null},
5751 * no exception is thrown and no action is performed.
5752 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5753 * >AWT Threading Issues</a> for details on AWT's threading model.
5754 *
5755 * @param l the mouse listener
5756 * @see java.awt.event.MouseEvent
5757 * @see java.awt.event.MouseListener
5758 * @see #removeMouseListener
5759 * @see #getMouseListeners
5760 * @since 1.1
5761 */
5762 public synchronized void addMouseListener(MouseListener l) {
5763 if (l == null) {
5764 return;
5765 }
5766 mouseListener = AWTEventMulticaster.add(mouseListener,l);
5767 newEventsOnly = true;
5768
5769 // if this is a lightweight component, enable mouse events
5770 // in the native container.
5771 if (peer instanceof LightweightPeer) {
5772 parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK);
5773 }
5774 }
5775
5776 /**
5777 * Removes the specified mouse listener so that it no longer
5778 * receives mouse events from this component. This method performs
5779 * no function, nor does it throw an exception, if the listener
5780 * specified by the argument was not previously added to this component.
5781 * If listener {@code l} is {@code null},
5782 * no exception is thrown and no action is performed.
5783 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5784 * >AWT Threading Issues</a> for details on AWT's threading model.
5785 *
5786 * @param l the mouse listener
5787 * @see java.awt.event.MouseEvent
5788 * @see java.awt.event.MouseListener
5789 * @see #addMouseListener
5790 * @see #getMouseListeners
5791 * @since 1.1
5792 */
5793 public synchronized void removeMouseListener(MouseListener l) {
5794 if (l == null) {
5795 return;
5796 }
5797 mouseListener = AWTEventMulticaster.remove(mouseListener, l);
5798 }
5799
5800 /**
5801 * Returns an array of all the mouse listeners
5802 * registered on this component.
5803 *
5804 * @return all of this component's {@code MouseListener}s
5805 * or an empty array if no mouse
5806 * listeners are currently registered
5807 *
5808 * @see #addMouseListener
5809 * @see #removeMouseListener
5810 * @since 1.4
5811 */
5812 public synchronized MouseListener[] getMouseListeners() {
5813 return getListeners(MouseListener.class);
5814 }
5815
5816 /**
5817 * Adds the specified mouse motion listener to receive mouse motion
5818 * events from this component.
5819 * If listener {@code l} is {@code null},
5820 * no exception is thrown and no action is performed.
5821 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5822 * >AWT Threading Issues</a> for details on AWT's threading model.
5823 *
5824 * @param l the mouse motion listener
5825 * @see java.awt.event.MouseEvent
5826 * @see java.awt.event.MouseMotionListener
5827 * @see #removeMouseMotionListener
5828 * @see #getMouseMotionListeners
5829 * @since 1.1
5830 */
5831 public synchronized void addMouseMotionListener(MouseMotionListener l) {
5832 if (l == null) {
5833 return;
5834 }
5835 mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l);
5836 newEventsOnly = true;
5837
5838 // if this is a lightweight component, enable mouse events
5839 // in the native container.
5840 if (peer instanceof LightweightPeer) {
5841 parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
5842 }
5843 }
5844
5845 /**
5846 * Removes the specified mouse motion listener so that it no longer
5847 * receives mouse motion events from this component. This method performs
5848 * no function, nor does it throw an exception, if the listener
5849 * specified by the argument was not previously added to this component.
5850 * If listener {@code l} is {@code null},
5851 * no exception is thrown and no action is performed.
5852 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5853 * >AWT Threading Issues</a> for details on AWT's threading model.
5854 *
5855 * @param l the mouse motion listener
5856 * @see java.awt.event.MouseEvent
5857 * @see java.awt.event.MouseMotionListener
5858 * @see #addMouseMotionListener
5859 * @see #getMouseMotionListeners
5860 * @since 1.1
5861 */
5862 public synchronized void removeMouseMotionListener(MouseMotionListener l) {
5863 if (l == null) {
5864 return;
5865 }
5866 mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l);
5867 }
5868
5869 /**
5870 * Returns an array of all the mouse motion listeners
5871 * registered on this component.
5872 *
5873 * @return all of this component's {@code MouseMotionListener}s
5874 * or an empty array if no mouse motion
5875 * listeners are currently registered
5876 *
5877 * @see #addMouseMotionListener
5878 * @see #removeMouseMotionListener
5879 * @since 1.4
5880 */
5881 public synchronized MouseMotionListener[] getMouseMotionListeners() {
5882 return getListeners(MouseMotionListener.class);
5883 }
5884
5885 /**
5886 * Adds the specified mouse wheel listener to receive mouse wheel events
5887 * from this component. Containers also receive mouse wheel events from
5888 * sub-components.
5889 * <p>
5890 * For information on how mouse wheel events are dispatched, see
5891 * the class description for {@link MouseWheelEvent}.
5892 * <p>
5893 * If l is {@code null}, no exception is thrown and no
5894 * action is performed.
5895 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5896 * >AWT Threading Issues</a> for details on AWT's threading model.
5897 *
5898 * @param l the mouse wheel listener
5899 * @see java.awt.event.MouseWheelEvent
5900 * @see java.awt.event.MouseWheelListener
5901 * @see #removeMouseWheelListener
5902 * @see #getMouseWheelListeners
5903 * @since 1.4
5904 */
5905 public synchronized void addMouseWheelListener(MouseWheelListener l) {
5906 if (l == null) {
5907 return;
5908 }
5909 mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l);
5910 newEventsOnly = true;
5911
5912 // if this is a lightweight component, enable mouse events
5913 // in the native container.
5926 * >AWT Threading Issues</a> for details on AWT's threading model.
5927 *
5928 * @param l the mouse wheel listener.
5929 * @see java.awt.event.MouseWheelEvent
5930 * @see java.awt.event.MouseWheelListener
5931 * @see #addMouseWheelListener
5932 * @see #getMouseWheelListeners
5933 * @since 1.4
5934 */
5935 public synchronized void removeMouseWheelListener(MouseWheelListener l) {
5936 if (l == null) {
5937 return;
5938 }
5939 mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l);
5940 }
5941
5942 /**
5943 * Returns an array of all the mouse wheel listeners
5944 * registered on this component.
5945 *
5946 * @return all of this component's {@code MouseWheelListener}s
5947 * or an empty array if no mouse wheel
5948 * listeners are currently registered
5949 *
5950 * @see #addMouseWheelListener
5951 * @see #removeMouseWheelListener
5952 * @since 1.4
5953 */
5954 public synchronized MouseWheelListener[] getMouseWheelListeners() {
5955 return getListeners(MouseWheelListener.class);
5956 }
5957
5958 /**
5959 * Adds the specified input method listener to receive
5960 * input method events from this component. A component will
5961 * only receive input method events from input methods
5962 * if it also overrides {@code getInputMethodRequests} to return an
5963 * {@code InputMethodRequests} instance.
5964 * If listener {@code l} is {@code null},
5965 * no exception is thrown and no action is performed.
5966 * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads"
5967 * >AWT Threading Issues</a> for details on AWT's threading model.
5968 *
5969 * @param l the input method listener
5970 * @see java.awt.event.InputMethodEvent
5971 * @see java.awt.event.InputMethodListener
5972 * @see #removeInputMethodListener
5973 * @see #getInputMethodListeners
5974 * @see #getInputMethodRequests
5975 * @since 1.2
5976 */
5977 public synchronized void addInputMethodListener(InputMethodListener l) {
5978 if (l == null) {
5979 return;
5980 }
5981 inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l);
5982 newEventsOnly = true;
5983 }
5984
5985 /**
5986 * Removes the specified input method listener so that it no longer
5987 * receives input method events from this component. This method performs
5988 * no function, nor does it throw an exception, if the listener
5989 * specified by the argument was not previously added to this component.
5990 * If listener {@code l} is {@code null},
5991 * no exception is thrown and no action is performed.
5992 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
5993 * >AWT Threading Issues</a> for details on AWT's threading model.
5994 *
5995 * @param l the input method listener
5996 * @see java.awt.event.InputMethodEvent
5997 * @see java.awt.event.InputMethodListener
5998 * @see #addInputMethodListener
5999 * @see #getInputMethodListeners
6000 * @since 1.2
6001 */
6002 public synchronized void removeInputMethodListener(InputMethodListener l) {
6003 if (l == null) {
6004 return;
6005 }
6006 inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l);
6007 }
6008
6009 /**
6010 * Returns an array of all the input method listeners
6011 * registered on this component.
6012 *
6013 * @return all of this component's {@code InputMethodListener}s
6014 * or an empty array if no input method
6015 * listeners are currently registered
6016 *
6017 * @see #addInputMethodListener
6018 * @see #removeInputMethodListener
6019 * @since 1.4
6020 */
6021 public synchronized InputMethodListener[] getInputMethodListeners() {
6022 return getListeners(InputMethodListener.class);
6023 }
6024
6025 /**
6026 * Returns an array of all the objects currently registered
6027 * as <code><em>Foo</em>Listener</code>s
6028 * upon this {@code Component}.
6029 * <code><em>Foo</em>Listener</code>s are registered using the
6030 * <code>add<em>Foo</em>Listener</code> method.
6031 *
6032 * <p>
6033 * You can specify the {@code listenerType} argument
6034 * with a class literal, such as
6035 * <code><em>Foo</em>Listener.class</code>.
6036 * For example, you can query a
6037 * {@code Component c}
6038 * for its mouse listeners with the following code:
6039 *
6040 * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
6041 *
6042 * If no such listeners exist, this method returns an empty array.
6043 *
6044 * @param <T> the type of the listeners
6045 * @param listenerType the type of listeners requested; this parameter
6046 * should specify an interface that descends from
6047 * {@code java.util.EventListener}
6048 * @return an array of all objects registered as
6049 * <code><em>Foo</em>Listener</code>s on this component,
6050 * or an empty array if no such listeners have been added
6051 * @exception ClassCastException if {@code listenerType}
6052 * doesn't specify a class or interface that implements
6053 * {@code java.util.EventListener}
6054 * @throws NullPointerException if {@code listenerType} is {@code null}
6055 * @see #getComponentListeners
6056 * @see #getFocusListeners
6057 * @see #getHierarchyListeners
6058 * @see #getHierarchyBoundsListeners
6059 * @see #getKeyListeners
6060 * @see #getMouseListeners
6061 * @see #getMouseMotionListeners
6062 * @see #getMouseWheelListeners
6063 * @see #getInputMethodListeners
6064 * @see #getPropertyChangeListeners
6065 *
6066 * @since 1.3
6067 */
6068 @SuppressWarnings("unchecked")
6069 public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
6070 EventListener l = null;
6071 if (listenerType == ComponentListener.class) {
6072 l = componentListener;
6073 } else if (listenerType == FocusListener.class) {
6079 } else if (listenerType == KeyListener.class) {
6080 l = keyListener;
6081 } else if (listenerType == MouseListener.class) {
6082 l = mouseListener;
6083 } else if (listenerType == MouseMotionListener.class) {
6084 l = mouseMotionListener;
6085 } else if (listenerType == MouseWheelListener.class) {
6086 l = mouseWheelListener;
6087 } else if (listenerType == InputMethodListener.class) {
6088 l = inputMethodListener;
6089 } else if (listenerType == PropertyChangeListener.class) {
6090 return (T[])getPropertyChangeListeners();
6091 }
6092 return AWTEventMulticaster.getListeners(l, listenerType);
6093 }
6094
6095 /**
6096 * Gets the input method request handler which supports
6097 * requests from input methods for this component. A component
6098 * that supports on-the-spot text input must override this
6099 * method to return an {@code InputMethodRequests} instance.
6100 * At the same time, it also has to handle input method events.
6101 *
6102 * @return the input method request handler for this component,
6103 * {@code null} by default
6104 * @see #addInputMethodListener
6105 * @since 1.2
6106 */
6107 public InputMethodRequests getInputMethodRequests() {
6108 return null;
6109 }
6110
6111 /**
6112 * Gets the input context used by this component for handling
6113 * the communication with input methods when text is entered
6114 * in this component. By default, the input context used for
6115 * the parent component is returned. Components may
6116 * override this to return a private input context.
6117 *
6118 * @return the input context used by this component;
6119 * {@code null} if no context can be determined
6120 * @since 1.2
6121 */
6122 public InputContext getInputContext() {
6123 Container parent = this.parent;
6124 if (parent == null) {
6125 return null;
6126 } else {
6127 return parent.getInputContext();
6128 }
6129 }
6130
6131 /**
6132 * Enables the events defined by the specified event mask parameter
6133 * to be delivered to this component.
6134 * <p>
6135 * Event types are automatically enabled when a listener for
6136 * that event type is added to the component.
6137 * <p>
6138 * This method only needs to be invoked by subclasses of
6139 * {@code Component} which desire to have the specified event
6140 * types delivered to {@code processEvent} regardless of whether
6141 * or not a listener is registered.
6142 * @param eventsToEnable the event mask defining the event types
6143 * @see #processEvent
6144 * @see #disableEvents
6145 * @see AWTEvent
6146 * @since 1.1
6147 */
6148 protected final void enableEvents(long eventsToEnable) {
6149 long notifyAncestors = 0;
6150 synchronized (this) {
6151 if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 &&
6152 hierarchyListener == null &&
6153 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) {
6154 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK;
6155 }
6156 if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 &&
6157 hierarchyBoundsListener == null &&
6158 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) {
6159 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK;
6160 }
6292 clazz.getDeclaredMethod(
6293 "coalesceEvents", coalesceEventsParams
6294 );
6295 return true;
6296 } catch (NoSuchMethodException e) {
6297 // Not present in this class.
6298 return false;
6299 }
6300 }
6301
6302 /**
6303 * Indicates whether coalesceEvents may do something.
6304 */
6305 final boolean isCoalescingEnabled() {
6306 return coalescingEnabled;
6307 }
6308
6309
6310 /**
6311 * Potentially coalesce an event being posted with an existing
6312 * event. This method is called by {@code EventQueue.postEvent}
6313 * if an event with the same ID as the event to be posted is found in
6314 * the queue (both events must have this component as their source).
6315 * This method either returns a coalesced event which replaces
6316 * the existing event (and the new event is then discarded), or
6317 * {@code null} to indicate that no combining should be done
6318 * (add the second event to the end of the queue). Either event
6319 * parameter may be modified and returned, as the other one is discarded
6320 * unless {@code null} is returned.
6321 * <p>
6322 * This implementation of {@code coalesceEvents} coalesces
6323 * two event types: mouse move (and drag) events,
6324 * and paint (and update) events.
6325 * For mouse move events the last event is always returned, causing
6326 * intermediate moves to be discarded. For paint events, the new
6327 * event is coalesced into a complex {@code RepaintArea} in the peer.
6328 * The new {@code AWTEvent} is always returned.
6329 *
6330 * @param existingEvent the event already on the {@code EventQueue}
6331 * @param newEvent the event being posted to the
6332 * {@code EventQueue}
6333 * @return a coalesced event, or {@code null} indicating that no
6334 * coalescing was done
6335 */
6336 protected AWTEvent coalesceEvents(AWTEvent existingEvent,
6337 AWTEvent newEvent) {
6338 return null;
6339 }
6340
6341 /**
6342 * Processes events occurring on this component. By default this
6343 * method calls the appropriate
6344 * <code>process<event type>Event</code>
6345 * method for the given class of event.
6346 * <p>Note that if the event parameter is {@code null}
6347 * the behavior is unspecified and may result in an
6348 * exception.
6349 *
6350 * @param e the event
6351 * @see #processComponentEvent
6352 * @see #processFocusEvent
6353 * @see #processKeyEvent
6354 * @see #processMouseEvent
6355 * @see #processMouseMotionEvent
6356 * @see #processInputMethodEvent
6357 * @see #processHierarchyEvent
6358 * @see #processMouseWheelEvent
6359 * @since 1.1
6360 */
6361 protected void processEvent(AWTEvent e) {
6362 if (e instanceof FocusEvent) {
6363 processFocusEvent((FocusEvent)e);
6364
6365 } else if (e instanceof MouseEvent) {
6366 switch(e.getID()) {
6386 } else if (e instanceof ComponentEvent) {
6387 processComponentEvent((ComponentEvent)e);
6388 } else if (e instanceof InputMethodEvent) {
6389 processInputMethodEvent((InputMethodEvent)e);
6390 } else if (e instanceof HierarchyEvent) {
6391 switch (e.getID()) {
6392 case HierarchyEvent.HIERARCHY_CHANGED:
6393 processHierarchyEvent((HierarchyEvent)e);
6394 break;
6395 case HierarchyEvent.ANCESTOR_MOVED:
6396 case HierarchyEvent.ANCESTOR_RESIZED:
6397 processHierarchyBoundsEvent((HierarchyEvent)e);
6398 break;
6399 }
6400 }
6401 }
6402
6403 /**
6404 * Processes component events occurring on this component by
6405 * dispatching them to any registered
6406 * {@code ComponentListener} objects.
6407 * <p>
6408 * This method is not called unless component events are
6409 * enabled for this component. Component events are enabled
6410 * when one of the following occurs:
6411 * <ul>
6412 * <li>A {@code ComponentListener} object is registered
6413 * via {@code addComponentListener}.
6414 * <li>Component events are enabled via {@code enableEvents}.
6415 * </ul>
6416 * <p>Note that if the event parameter is {@code null}
6417 * the behavior is unspecified and may result in an
6418 * exception.
6419 *
6420 * @param e the component event
6421 * @see java.awt.event.ComponentEvent
6422 * @see java.awt.event.ComponentListener
6423 * @see #addComponentListener
6424 * @see #enableEvents
6425 * @since 1.1
6426 */
6427 protected void processComponentEvent(ComponentEvent e) {
6428 ComponentListener listener = componentListener;
6429 if (listener != null) {
6430 int id = e.getID();
6431 switch(id) {
6432 case ComponentEvent.COMPONENT_RESIZED:
6433 listener.componentResized(e);
6434 break;
6435 case ComponentEvent.COMPONENT_MOVED:
6436 listener.componentMoved(e);
6437 break;
6438 case ComponentEvent.COMPONENT_SHOWN:
6439 listener.componentShown(e);
6440 break;
6441 case ComponentEvent.COMPONENT_HIDDEN:
6442 listener.componentHidden(e);
6443 break;
6444 }
6445 }
6446 }
6447
6448 /**
6449 * Processes focus events occurring on this component by
6450 * dispatching them to any registered
6451 * {@code FocusListener} objects.
6452 * <p>
6453 * This method is not called unless focus events are
6454 * enabled for this component. Focus events are enabled
6455 * when one of the following occurs:
6456 * <ul>
6457 * <li>A {@code FocusListener} object is registered
6458 * via {@code addFocusListener}.
6459 * <li>Focus events are enabled via {@code enableEvents}.
6460 * </ul>
6461 * <p>
6462 * If focus events are enabled for a {@code Component},
6463 * the current {@code KeyboardFocusManager} determines
6464 * whether or not a focus event should be dispatched to
6465 * registered {@code FocusListener} objects. If the
6466 * events are to be dispatched, the {@code KeyboardFocusManager}
6467 * calls the {@code Component}'s {@code dispatchEvent}
6468 * method, which results in a call to the {@code Component}'s
6469 * {@code processFocusEvent} method.
6470 * <p>
6471 * If focus events are enabled for a {@code Component}, calling
6472 * the {@code Component}'s {@code dispatchEvent} method
6473 * with a {@code FocusEvent} as the argument will result in a
6474 * call to the {@code Component}'s {@code processFocusEvent}
6475 * method regardless of the current {@code KeyboardFocusManager}.
6476 *
6477 * <p>Note that if the event parameter is {@code null}
6478 * the behavior is unspecified and may result in an
6479 * exception.
6480 *
6481 * @param e the focus event
6482 * @see java.awt.event.FocusEvent
6483 * @see java.awt.event.FocusListener
6484 * @see java.awt.KeyboardFocusManager
6485 * @see #addFocusListener
6486 * @see #enableEvents
6487 * @see #dispatchEvent
6488 * @since 1.1
6489 */
6490 protected void processFocusEvent(FocusEvent e) {
6491 FocusListener listener = focusListener;
6492 if (listener != null) {
6493 int id = e.getID();
6494 switch(id) {
6495 case FocusEvent.FOCUS_GAINED:
6496 listener.focusGained(e);
6497 break;
6498 case FocusEvent.FOCUS_LOST:
6499 listener.focusLost(e);
6500 break;
6501 }
6502 }
6503 }
6504
6505 /**
6506 * Processes key events occurring on this component by
6507 * dispatching them to any registered
6508 * {@code KeyListener} objects.
6509 * <p>
6510 * This method is not called unless key events are
6511 * enabled for this component. Key events are enabled
6512 * when one of the following occurs:
6513 * <ul>
6514 * <li>A {@code KeyListener} object is registered
6515 * via {@code addKeyListener}.
6516 * <li>Key events are enabled via {@code enableEvents}.
6517 * </ul>
6518 *
6519 * <p>
6520 * If key events are enabled for a {@code Component},
6521 * the current {@code KeyboardFocusManager} determines
6522 * whether or not a key event should be dispatched to
6523 * registered {@code KeyListener} objects. The
6524 * {@code DefaultKeyboardFocusManager} will not dispatch
6525 * key events to a {@code Component} that is not the focus
6526 * owner or is not showing.
6527 * <p>
6528 * As of J2SE 1.4, {@code KeyEvent}s are redirected to
6529 * the focus owner. Please see the
6530 * <a href="doc-files/FocusSpec.html">Focus Specification</a>
6531 * for further information.
6532 * <p>
6533 * Calling a {@code Component}'s {@code dispatchEvent}
6534 * method with a {@code KeyEvent} as the argument will
6535 * result in a call to the {@code Component}'s
6536 * {@code processKeyEvent} method regardless of the
6537 * current {@code KeyboardFocusManager} as long as the
6538 * component is showing, focused, and enabled, and key events
6539 * are enabled on it.
6540 * <p>If the event parameter is {@code null}
6541 * the behavior is unspecified and may result in an
6542 * exception.
6543 *
6544 * @param e the key event
6545 * @see java.awt.event.KeyEvent
6546 * @see java.awt.event.KeyListener
6547 * @see java.awt.KeyboardFocusManager
6548 * @see java.awt.DefaultKeyboardFocusManager
6549 * @see #processEvent
6550 * @see #dispatchEvent
6551 * @see #addKeyListener
6552 * @see #enableEvents
6553 * @see #isShowing
6554 * @since 1.1
6555 */
6556 protected void processKeyEvent(KeyEvent e) {
6557 KeyListener listener = keyListener;
6558 if (listener != null) {
6559 int id = e.getID();
6560 switch(id) {
6561 case KeyEvent.KEY_TYPED:
6562 listener.keyTyped(e);
6563 break;
6564 case KeyEvent.KEY_PRESSED:
6565 listener.keyPressed(e);
6566 break;
6567 case KeyEvent.KEY_RELEASED:
6568 listener.keyReleased(e);
6569 break;
6570 }
6571 }
6572 }
6573
6574 /**
6575 * Processes mouse events occurring on this component by
6576 * dispatching them to any registered
6577 * {@code MouseListener} objects.
6578 * <p>
6579 * This method is not called unless mouse events are
6580 * enabled for this component. Mouse events are enabled
6581 * when one of the following occurs:
6582 * <ul>
6583 * <li>A {@code MouseListener} object is registered
6584 * via {@code addMouseListener}.
6585 * <li>Mouse events are enabled via {@code enableEvents}.
6586 * </ul>
6587 * <p>Note that if the event parameter is {@code null}
6588 * the behavior is unspecified and may result in an
6589 * exception.
6590 *
6591 * @param e the mouse event
6592 * @see java.awt.event.MouseEvent
6593 * @see java.awt.event.MouseListener
6594 * @see #addMouseListener
6595 * @see #enableEvents
6596 * @since 1.1
6597 */
6598 protected void processMouseEvent(MouseEvent e) {
6599 MouseListener listener = mouseListener;
6600 if (listener != null) {
6601 int id = e.getID();
6602 switch(id) {
6603 case MouseEvent.MOUSE_PRESSED:
6604 listener.mousePressed(e);
6605 break;
6606 case MouseEvent.MOUSE_RELEASED:
6607 listener.mouseReleased(e);
6608 break;
6609 case MouseEvent.MOUSE_CLICKED:
6610 listener.mouseClicked(e);
6611 break;
6612 case MouseEvent.MOUSE_EXITED:
6613 listener.mouseExited(e);
6614 break;
6615 case MouseEvent.MOUSE_ENTERED:
6616 listener.mouseEntered(e);
6617 break;
6618 }
6619 }
6620 }
6621
6622 /**
6623 * Processes mouse motion events occurring on this component by
6624 * dispatching them to any registered
6625 * {@code MouseMotionListener} objects.
6626 * <p>
6627 * This method is not called unless mouse motion events are
6628 * enabled for this component. Mouse motion events are enabled
6629 * when one of the following occurs:
6630 * <ul>
6631 * <li>A {@code MouseMotionListener} object is registered
6632 * via {@code addMouseMotionListener}.
6633 * <li>Mouse motion events are enabled via {@code enableEvents}.
6634 * </ul>
6635 * <p>Note that if the event parameter is {@code null}
6636 * the behavior is unspecified and may result in an
6637 * exception.
6638 *
6639 * @param e the mouse motion event
6640 * @see java.awt.event.MouseEvent
6641 * @see java.awt.event.MouseMotionListener
6642 * @see #addMouseMotionListener
6643 * @see #enableEvents
6644 * @since 1.1
6645 */
6646 protected void processMouseMotionEvent(MouseEvent e) {
6647 MouseMotionListener listener = mouseMotionListener;
6648 if (listener != null) {
6649 int id = e.getID();
6650 switch(id) {
6651 case MouseEvent.MOUSE_MOVED:
6652 listener.mouseMoved(e);
6653 break;
6654 case MouseEvent.MOUSE_DRAGGED:
6655 listener.mouseDragged(e);
6656 break;
6657 }
6658 }
6659 }
6660
6661 /**
6662 * Processes mouse wheel events occurring on this component by
6663 * dispatching them to any registered
6664 * {@code MouseWheelListener} objects.
6665 * <p>
6666 * This method is not called unless mouse wheel events are
6667 * enabled for this component. Mouse wheel events are enabled
6668 * when one of the following occurs:
6669 * <ul>
6670 * <li>A {@code MouseWheelListener} object is registered
6671 * via {@code addMouseWheelListener}.
6672 * <li>Mouse wheel events are enabled via {@code enableEvents}.
6673 * </ul>
6674 * <p>
6675 * For information on how mouse wheel events are dispatched, see
6676 * the class description for {@link MouseWheelEvent}.
6677 * <p>
6678 * Note that if the event parameter is {@code null}
6679 * the behavior is unspecified and may result in an
6680 * exception.
6681 *
6682 * @param e the mouse wheel event
6683 * @see java.awt.event.MouseWheelEvent
6684 * @see java.awt.event.MouseWheelListener
6685 * @see #addMouseWheelListener
6686 * @see #enableEvents
6687 * @since 1.4
6688 */
6689 protected void processMouseWheelEvent(MouseWheelEvent e) {
6690 MouseWheelListener listener = mouseWheelListener;
6691 if (listener != null) {
6692 int id = e.getID();
6693 switch(id) {
6694 case MouseEvent.MOUSE_WHEEL:
6695 listener.mouseWheelMoved(e);
6696 break;
6697 }
6698 }
6699 }
6700
6701 boolean postsOldMouseEvents() {
6702 return false;
6703 }
6704
6705 /**
6706 * Processes input method events occurring on this component by
6707 * dispatching them to any registered
6708 * {@code InputMethodListener} objects.
6709 * <p>
6710 * This method is not called unless input method events
6711 * are enabled for this component. Input method events are enabled
6712 * when one of the following occurs:
6713 * <ul>
6714 * <li>An {@code InputMethodListener} object is registered
6715 * via {@code addInputMethodListener}.
6716 * <li>Input method events are enabled via {@code enableEvents}.
6717 * </ul>
6718 * <p>Note that if the event parameter is {@code null}
6719 * the behavior is unspecified and may result in an
6720 * exception.
6721 *
6722 * @param e the input method event
6723 * @see java.awt.event.InputMethodEvent
6724 * @see java.awt.event.InputMethodListener
6725 * @see #addInputMethodListener
6726 * @see #enableEvents
6727 * @since 1.2
6728 */
6729 protected void processInputMethodEvent(InputMethodEvent e) {
6730 InputMethodListener listener = inputMethodListener;
6731 if (listener != null) {
6732 int id = e.getID();
6733 switch (id) {
6734 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED:
6735 listener.inputMethodTextChanged(e);
6736 break;
6737 case InputMethodEvent.CARET_POSITION_CHANGED:
6738 listener.caretPositionChanged(e);
6739 break;
6740 }
6741 }
6742 }
6743
6744 /**
6745 * Processes hierarchy events occurring on this component by
6746 * dispatching them to any registered
6747 * {@code HierarchyListener} objects.
6748 * <p>
6749 * This method is not called unless hierarchy events
6750 * are enabled for this component. Hierarchy events are enabled
6751 * when one of the following occurs:
6752 * <ul>
6753 * <li>An {@code HierarchyListener} object is registered
6754 * via {@code addHierarchyListener}.
6755 * <li>Hierarchy events are enabled via {@code enableEvents}.
6756 * </ul>
6757 * <p>Note that if the event parameter is {@code null}
6758 * the behavior is unspecified and may result in an
6759 * exception.
6760 *
6761 * @param e the hierarchy event
6762 * @see java.awt.event.HierarchyEvent
6763 * @see java.awt.event.HierarchyListener
6764 * @see #addHierarchyListener
6765 * @see #enableEvents
6766 * @since 1.3
6767 */
6768 protected void processHierarchyEvent(HierarchyEvent e) {
6769 HierarchyListener listener = hierarchyListener;
6770 if (listener != null) {
6771 int id = e.getID();
6772 switch (id) {
6773 case HierarchyEvent.HIERARCHY_CHANGED:
6774 listener.hierarchyChanged(e);
6775 break;
6776 }
6777 }
6778 }
6779
6780 /**
6781 * Processes hierarchy bounds events occurring on this component by
6782 * dispatching them to any registered
6783 * {@code HierarchyBoundsListener} objects.
6784 * <p>
6785 * This method is not called unless hierarchy bounds events
6786 * are enabled for this component. Hierarchy bounds events are enabled
6787 * when one of the following occurs:
6788 * <ul>
6789 * <li>An {@code HierarchyBoundsListener} object is registered
6790 * via {@code addHierarchyBoundsListener}.
6791 * <li>Hierarchy bounds events are enabled via {@code enableEvents}.
6792 * </ul>
6793 * <p>Note that if the event parameter is {@code null}
6794 * the behavior is unspecified and may result in an
6795 * exception.
6796 *
6797 * @param e the hierarchy event
6798 * @see java.awt.event.HierarchyEvent
6799 * @see java.awt.event.HierarchyBoundsListener
6800 * @see #addHierarchyBoundsListener
6801 * @see #enableEvents
6802 * @since 1.3
6803 */
6804 protected void processHierarchyBoundsEvent(HierarchyEvent e) {
6805 HierarchyBoundsListener listener = hierarchyBoundsListener;
6806 if (listener != null) {
6807 int id = e.getID();
6808 switch (id) {
6809 case HierarchyEvent.ANCESTOR_MOVED:
6810 listener.ancestorMoved(e);
6811 break;
6812 case HierarchyEvent.ANCESTOR_RESIZED:
6813 listener.ancestorResized(e);
6960 */
6961 @Deprecated
6962 public boolean keyUp(Event evt, int key) {
6963 return false;
6964 }
6965
6966 /**
6967 * @param evt the event to handle
6968 * @param what the object acted on
6969 * @return {@code false}
6970 * @deprecated As of JDK version 1.1,
6971 * should register this component as ActionListener on component
6972 * which fires action events.
6973 */
6974 @Deprecated
6975 public boolean action(Event evt, Object what) {
6976 return false;
6977 }
6978
6979 /**
6980 * Makes this {@code Component} displayable by connecting it to a
6981 * native screen resource.
6982 * This method is called internally by the toolkit and should
6983 * not be called directly by programs.
6984 * <p>
6985 * This method changes layout-related information, and therefore,
6986 * invalidates the component hierarchy.
6987 *
6988 * @see #isDisplayable
6989 * @see #removeNotify
6990 * @see #invalidate
6991 * @since 1.0
6992 */
6993 public void addNotify() {
6994 synchronized (getTreeLock()) {
6995 ComponentPeer peer = this.peer;
6996 if (peer == null || peer instanceof LightweightPeer){
6997 if (peer == null) {
6998 // Update both the Component's peer variable and the local
6999 // variable we use for thread safety.
7000 this.peer = peer = getComponentFactory().createComponent(this);
7064 }
7065
7066 isAddNotifyComplete = true;
7067
7068 if (hierarchyListener != null ||
7069 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 ||
7070 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) {
7071 HierarchyEvent e =
7072 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED,
7073 this, parent,
7074 HierarchyEvent.DISPLAYABILITY_CHANGED |
7075 ((isRecursivelyVisible())
7076 ? HierarchyEvent.SHOWING_CHANGED
7077 : 0));
7078 dispatchEvent(e);
7079 }
7080 }
7081 }
7082
7083 /**
7084 * Makes this {@code Component} undisplayable by destroying it native
7085 * screen resource.
7086 * <p>
7087 * This method is called by the toolkit internally and should
7088 * not be called directly by programs. Code overriding
7089 * this method should call {@code super.removeNotify} as
7090 * the first line of the overriding method.
7091 *
7092 * @see #isDisplayable
7093 * @see #addNotify
7094 * @since 1.0
7095 */
7096 public void removeNotify() {
7097 KeyboardFocusManager.clearMostRecentFocusOwner(this);
7098 if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
7099 getPermanentFocusOwner() == this)
7100 {
7101 KeyboardFocusManager.getCurrentKeyboardFocusManager().
7102 setGlobalPermanentFocusOwner(null);
7103 }
7104
7105 synchronized (getTreeLock()) {
7106 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) {
7107 transferFocus(true);
7108 }
7109
7181 * replaced by processFocusEvent(FocusEvent).
7182 */
7183 @Deprecated
7184 public boolean gotFocus(Event evt, Object what) {
7185 return false;
7186 }
7187
7188 /**
7189 * @param evt the event to handle
7190 * @param what the object focused
7191 * @return {@code false}
7192 * @deprecated As of JDK version 1.1,
7193 * replaced by processFocusEvent(FocusEvent).
7194 */
7195 @Deprecated
7196 public boolean lostFocus(Event evt, Object what) {
7197 return false;
7198 }
7199
7200 /**
7201 * Returns whether this {@code Component} can become the focus
7202 * owner.
7203 *
7204 * @return {@code true} if this {@code Component} is
7205 * focusable; {@code false} otherwise
7206 * @see #setFocusable
7207 * @since 1.1
7208 * @deprecated As of 1.4, replaced by {@code isFocusable()}.
7209 */
7210 @Deprecated
7211 public boolean isFocusTraversable() {
7212 if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) {
7213 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT;
7214 }
7215 return focusable;
7216 }
7217
7218 /**
7219 * Returns whether this Component can be focused.
7220 *
7221 * @return {@code true} if this Component is focusable;
7222 * {@code false} otherwise.
7223 * @see #setFocusable
7224 * @since 1.4
7225 */
7226 public boolean isFocusable() {
7227 return isFocusTraversable();
7228 }
7229
7230 /**
7231 * Sets the focusable state of this Component to the specified value. This
7232 * value overrides the Component's default focusability.
7233 *
7234 * @param focusable indicates whether this Component is focusable
7235 * @see #isFocusable
7236 * @since 1.4
7237 * @beaninfo
7238 * bound: true
7239 */
7240 public void setFocusable(boolean focusable) {
7241 boolean oldFocusable;
7242 synchronized (this) {
7326 * contains null, or if any keystroke represents a KEY_TYPED event,
7327 * or if any keystroke already maps to another focus traversal
7328 * operation for this Component
7329 * @since 1.4
7330 * @beaninfo
7331 * bound: true
7332 */
7333 public void setFocusTraversalKeys(int id,
7334 Set<? extends AWTKeyStroke> keystrokes)
7335 {
7336 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7337 throw new IllegalArgumentException("invalid focus traversal key identifier");
7338 }
7339
7340 setFocusTraversalKeys_NoIDCheck(id, keystrokes);
7341 }
7342
7343 /**
7344 * Returns the Set of focus traversal keys for a given traversal operation
7345 * for this Component. (See
7346 * {@code setFocusTraversalKeys} for a full description of each key.)
7347 * <p>
7348 * If a Set of traversal keys has not been explicitly defined for this
7349 * Component, then this Component's parent's Set is returned. If no Set
7350 * has been explicitly defined for any of this Component's ancestors, then
7351 * the current KeyboardFocusManager's default Set is returned.
7352 *
7353 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7354 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7355 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7356 * @return the Set of AWTKeyStrokes for the specified operation. The Set
7357 * will be unmodifiable, and may be empty. null will never be
7358 * returned.
7359 * @see #setFocusTraversalKeys
7360 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS
7361 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS
7362 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS
7363 * @throws IllegalArgumentException if id is not one of
7364 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7365 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7366 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7426 Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null)
7427 ? focusTraversalKeys[id]
7428 : null;
7429
7430 if (keystrokes != null) {
7431 return keystrokes;
7432 } else {
7433 Container parent = this.parent;
7434 if (parent != null) {
7435 return parent.getFocusTraversalKeys(id);
7436 } else {
7437 return KeyboardFocusManager.getCurrentKeyboardFocusManager().
7438 getDefaultFocusTraversalKeys(id);
7439 }
7440 }
7441 }
7442
7443 /**
7444 * Returns whether the Set of focus traversal keys for the given focus
7445 * traversal operation has been explicitly defined for this Component. If
7446 * this method returns {@code false}, this Component is inheriting the
7447 * Set from an ancestor, or from the current KeyboardFocusManager.
7448 *
7449 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7450 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7451 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7452 * @return {@code true} if the Set of focus traversal keys for the
7453 * given focus traversal operation has been explicitly defined for
7454 * this Component; {@code false} otherwise.
7455 * @throws IllegalArgumentException if id is not one of
7456 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
7457 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or
7458 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS
7459 * @since 1.4
7460 */
7461 public boolean areFocusTraversalKeysSet(int id) {
7462 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) {
7463 throw new IllegalArgumentException("invalid focus traversal key identifier");
7464 }
7465
7466 return (focusTraversalKeys != null && focusTraversalKeys[id] != null);
7467 }
7468
7469 /**
7470 * Sets whether focus traversal keys are enabled for this Component.
7471 * Components for which focus traversal keys are disabled receive key
7472 * events for focus traversal keys. Components for which focus traversal
7473 * keys are enabled do not see these events; instead, the events are
7474 * automatically converted to traversal operations.
7509 */
7510 public boolean getFocusTraversalKeysEnabled() {
7511 return focusTraversalKeysEnabled;
7512 }
7513
7514 /**
7515 * Requests that this Component get the input focus, and that this
7516 * Component's top-level ancestor become the focused Window. This
7517 * component must be displayable, focusable, visible and all of
7518 * its ancestors (with the exception of the top-level Window) must
7519 * be visible for the request to be granted. Every effort will be
7520 * made to honor the request; however, in some cases it may be
7521 * impossible to do so. Developers must never assume that this
7522 * Component is the focus owner until this Component receives a
7523 * FOCUS_GAINED event. If this request is denied because this
7524 * Component's top-level Window cannot become the focused Window,
7525 * the request will be remembered and will be granted when the
7526 * Window is later focused by the user.
7527 * <p>
7528 * This method cannot be used to set the focus owner to no Component at
7529 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7530 * instead.
7531 * <p>
7532 * Because the focus behavior of this method is platform-dependent,
7533 * developers are strongly encouraged to use
7534 * {@code requestFocusInWindow} when possible.
7535 *
7536 * <p>Note: Not all focus transfers result from invoking this method. As
7537 * such, a component may receive focus without this or any of the other
7538 * {@code requestFocus} methods of {@code Component} being invoked.
7539 *
7540 * @see #requestFocusInWindow
7541 * @see java.awt.event.FocusEvent
7542 * @see #addFocusListener
7543 * @see #isFocusable
7544 * @see #isDisplayable
7545 * @see KeyboardFocusManager#clearGlobalFocusOwner
7546 * @since 1.0
7547 */
7548 public void requestFocus() {
7549 requestFocusHelper(false, true);
7550 }
7551
7552 boolean requestFocus(CausedFocusEvent.Cause cause) {
7553 return requestFocusHelper(false, true, cause);
7554 }
7555
7556 /**
7557 * Requests that this {@code Component} get the input focus,
7558 * and that this {@code Component}'s top-level ancestor
7559 * become the focused {@code Window}. This component must be
7560 * displayable, focusable, visible and all of its ancestors (with
7561 * the exception of the top-level Window) must be visible for the
7562 * request to be granted. Every effort will be made to honor the
7563 * request; however, in some cases it may be impossible to do
7564 * so. Developers must never assume that this component is the
7565 * focus owner until this component receives a FOCUS_GAINED
7566 * event. If this request is denied because this component's
7567 * top-level window cannot become the focused window, the request
7568 * will be remembered and will be granted when the window is later
7569 * focused by the user.
7570 * <p>
7571 * This method returns a boolean value. If {@code false} is returned,
7572 * the request is <b>guaranteed to fail</b>. If {@code true} is
7573 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7574 * extraordinary event, such as disposal of the component's peer, occurs
7575 * before the request can be granted by the native windowing system. Again,
7576 * while a return value of {@code true} indicates that the request is
7577 * likely to succeed, developers must never assume that this component is
7578 * the focus owner until this component receives a FOCUS_GAINED event.
7579 * <p>
7580 * This method cannot be used to set the focus owner to no component at
7581 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner}
7582 * instead.
7583 * <p>
7584 * Because the focus behavior of this method is platform-dependent,
7585 * developers are strongly encouraged to use
7586 * {@code requestFocusInWindow} when possible.
7587 * <p>
7588 * Every effort will be made to ensure that {@code FocusEvent}s
7589 * generated as a
7590 * result of this request will have the specified temporary value. However,
7591 * because specifying an arbitrary temporary state may not be implementable
7592 * on all native windowing systems, correct behavior for this method can be
7593 * guaranteed only for lightweight {@code Component}s.
7594 * This method is not intended
7595 * for general use, but exists instead as a hook for lightweight component
7596 * libraries, such as Swing.
7597 *
7598 * <p>Note: Not all focus transfers result from invoking this method. As
7599 * such, a component may receive focus without this or any of the other
7600 * {@code requestFocus} methods of {@code Component} being invoked.
7601 *
7602 * @param temporary true if the focus change is temporary,
7603 * such as when the window loses the focus; for
7604 * more information on temporary focus changes see the
7605 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7606 * @return {@code false} if the focus change request is guaranteed to
7607 * fail; {@code true} if it is likely to succeed
7608 * @see java.awt.event.FocusEvent
7609 * @see #addFocusListener
7610 * @see #isFocusable
7611 * @see #isDisplayable
7612 * @see KeyboardFocusManager#clearGlobalFocusOwner
7613 * @since 1.4
7614 */
7615 protected boolean requestFocus(boolean temporary) {
7616 return requestFocusHelper(temporary, true);
7617 }
7618
7619 boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) {
7620 return requestFocusHelper(temporary, true, cause);
7621 }
7622 /**
7623 * Requests that this Component get the input focus, if this
7624 * Component's top-level ancestor is already the focused
7625 * Window. This component must be displayable, focusable, visible
7626 * and all of its ancestors (with the exception of the top-level
7627 * Window) must be visible for the request to be granted. Every
7628 * effort will be made to honor the request; however, in some
7629 * cases it may be impossible to do so. Developers must never
7630 * assume that this Component is the focus owner until this
7631 * Component receives a FOCUS_GAINED event.
7632 * <p>
7633 * This method returns a boolean value. If {@code false} is returned,
7634 * the request is <b>guaranteed to fail</b>. If {@code true} is
7635 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7636 * extraordinary event, such as disposal of the Component's peer, occurs
7637 * before the request can be granted by the native windowing system. Again,
7638 * while a return value of {@code true} indicates that the request is
7639 * likely to succeed, developers must never assume that this Component is
7640 * the focus owner until this Component receives a FOCUS_GAINED event.
7641 * <p>
7642 * This method cannot be used to set the focus owner to no Component at
7643 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()}
7644 * instead.
7645 * <p>
7646 * The focus behavior of this method can be implemented uniformly across
7647 * platforms, and thus developers are strongly encouraged to use this
7648 * method over {@code requestFocus} when possible. Code which relies
7649 * on {@code requestFocus} may exhibit different focus behavior on
7650 * different platforms.
7651 *
7652 * <p>Note: Not all focus transfers result from invoking this method. As
7653 * such, a component may receive focus without this or any of the other
7654 * {@code requestFocus} methods of {@code Component} being invoked.
7655 *
7656 * @return {@code false} if the focus change request is guaranteed to
7657 * fail; {@code true} if it is likely to succeed
7658 * @see #requestFocus
7659 * @see java.awt.event.FocusEvent
7660 * @see #addFocusListener
7661 * @see #isFocusable
7662 * @see #isDisplayable
7663 * @see KeyboardFocusManager#clearGlobalFocusOwner
7664 * @since 1.4
7665 */
7666 public boolean requestFocusInWindow() {
7667 return requestFocusHelper(false, false);
7668 }
7669
7670 boolean requestFocusInWindow(CausedFocusEvent.Cause cause) {
7671 return requestFocusHelper(false, false, cause);
7672 }
7673
7674 /**
7675 * Requests that this {@code Component} get the input focus,
7676 * if this {@code Component}'s top-level ancestor is already
7677 * the focused {@code Window}. This component must be
7678 * displayable, focusable, visible and all of its ancestors (with
7679 * the exception of the top-level Window) must be visible for the
7680 * request to be granted. Every effort will be made to honor the
7681 * request; however, in some cases it may be impossible to do
7682 * so. Developers must never assume that this component is the
7683 * focus owner until this component receives a FOCUS_GAINED event.
7684 * <p>
7685 * This method returns a boolean value. If {@code false} is returned,
7686 * the request is <b>guaranteed to fail</b>. If {@code true} is
7687 * returned, the request will succeed <b>unless</b> it is vetoed, or an
7688 * extraordinary event, such as disposal of the component's peer, occurs
7689 * before the request can be granted by the native windowing system. Again,
7690 * while a return value of {@code true} indicates that the request is
7691 * likely to succeed, developers must never assume that this component is
7692 * the focus owner until this component receives a FOCUS_GAINED event.
7693 * <p>
7694 * This method cannot be used to set the focus owner to no component at
7695 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner}
7696 * instead.
7697 * <p>
7698 * The focus behavior of this method can be implemented uniformly across
7699 * platforms, and thus developers are strongly encouraged to use this
7700 * method over {@code requestFocus} when possible. Code which relies
7701 * on {@code requestFocus} may exhibit different focus behavior on
7702 * different platforms.
7703 * <p>
7704 * Every effort will be made to ensure that {@code FocusEvent}s
7705 * generated as a
7706 * result of this request will have the specified temporary value. However,
7707 * because specifying an arbitrary temporary state may not be implementable
7708 * on all native windowing systems, correct behavior for this method can be
7709 * guaranteed only for lightweight components. This method is not intended
7710 * for general use, but exists instead as a hook for lightweight component
7711 * libraries, such as Swing.
7712 *
7713 * <p>Note: Not all focus transfers result from invoking this method. As
7714 * such, a component may receive focus without this or any of the other
7715 * {@code requestFocus} methods of {@code Component} being invoked.
7716 *
7717 * @param temporary true if the focus change is temporary,
7718 * such as when the window loses the focus; for
7719 * more information on temporary focus changes see the
7720 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
7721 * @return {@code false} if the focus change request is guaranteed to
7722 * fail; {@code true} if it is likely to succeed
7723 * @see #requestFocus
7724 * @see java.awt.event.FocusEvent
7725 * @see #addFocusListener
7726 * @see #isFocusable
7727 * @see #isDisplayable
7728 * @see KeyboardFocusManager#clearGlobalFocusOwner
7729 * @since 1.4
7730 */
7731 protected boolean requestFocusInWindow(boolean temporary) {
7732 return requestFocusHelper(temporary, false);
7733 }
7734
7735 boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) {
7736 return requestFocusHelper(temporary, false, cause);
7737 }
7738
7739 final boolean requestFocusHelper(boolean temporary,
7740 boolean focusedWindowChangeAllowed) {
7741 return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN);
7742 }
7937 *
7938 * @return this Component's nearest focus-cycle-root ancestor
7939 * @see Container#isFocusCycleRoot()
7940 * @since 1.4
7941 */
7942 public Container getFocusCycleRootAncestor() {
7943 Container rootAncestor = this.parent;
7944 while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) {
7945 rootAncestor = rootAncestor.parent;
7946 }
7947 return rootAncestor;
7948 }
7949
7950 /**
7951 * Returns whether the specified Container is the focus cycle root of this
7952 * Component's focus traversal cycle. Each focus traversal cycle has only
7953 * a single focus cycle root and each Component which is not a Container
7954 * belongs to only a single focus traversal cycle.
7955 *
7956 * @param container the Container to be tested
7957 * @return {@code true} if the specified Container is a focus-cycle-
7958 * root of this Component; {@code false} otherwise
7959 * @see Container#isFocusCycleRoot()
7960 * @since 1.4
7961 */
7962 public boolean isFocusCycleRoot(Container container) {
7963 Container rootAncestor = getFocusCycleRootAncestor();
7964 return (rootAncestor == container);
7965 }
7966
7967 Container getTraversalRoot() {
7968 return getFocusCycleRootAncestor();
7969 }
7970
7971 /**
7972 * Transfers the focus to the next component, as though this Component were
7973 * the focus owner.
7974 * @see #requestFocus()
7975 * @since 1.1
7976 */
7977 public void transferFocus() {
7978 nextFocus();
8119
8120 KeyboardFocusManager.getCurrentKeyboardFocusManager().
8121 setGlobalCurrentFocusCycleRootPriv(fcr);
8122 rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
8123 } else {
8124 Window window = getContainingWindow();
8125
8126 if (window != null) {
8127 Component toFocus = window.getFocusTraversalPolicy().
8128 getDefaultComponent(window);
8129 if (toFocus != null) {
8130 KeyboardFocusManager.getCurrentKeyboardFocusManager().
8131 setGlobalCurrentFocusCycleRootPriv(window);
8132 toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP);
8133 }
8134 }
8135 }
8136 }
8137
8138 /**
8139 * Returns {@code true} if this {@code Component} is the
8140 * focus owner. This method is obsolete, and has been replaced by
8141 * {@code isFocusOwner()}.
8142 *
8143 * @return {@code true} if this {@code Component} is the
8144 * focus owner; {@code false} otherwise
8145 * @since 1.2
8146 */
8147 public boolean hasFocus() {
8148 return (KeyboardFocusManager.getCurrentKeyboardFocusManager().
8149 getFocusOwner() == this);
8150 }
8151
8152 /**
8153 * Returns {@code true} if this {@code Component} is the
8154 * focus owner.
8155 *
8156 * @return {@code true} if this {@code Component} is the
8157 * focus owner; {@code false} otherwise
8158 * @since 1.4
8159 */
8160 public boolean isFocusOwner() {
8161 return hasFocus();
8162 }
8163
8164 /*
8165 * Used to disallow auto-focus-transfer on disposal of the focus owner
8166 * in the process of disposing its parent container.
8167 */
8168 private boolean autoFocusTransferOnDisposal = true;
8169
8170 void setAutoFocusTransferOnDisposal(boolean value) {
8171 autoFocusTransferOnDisposal = value;
8172 }
8173
8174 boolean isAutoFocusTransferOnDisposal() {
8175 return autoFocusTransferOnDisposal;
8176 }
8177
8216 int index = popups.indexOf(popup);
8217 if (index >= 0) {
8218 PopupMenu pmenu = (PopupMenu)popup;
8219 if (pmenu.peer != null) {
8220 pmenu.removeNotify();
8221 }
8222 pmenu.parent = null;
8223 popups.removeElementAt(index);
8224 if (popups.size() == 0) {
8225 popups = null;
8226 }
8227 }
8228 }
8229 }
8230
8231 /**
8232 * Returns a string representing the state of this component. This
8233 * method is intended to be used only for debugging purposes, and the
8234 * content and format of the returned string may vary between
8235 * implementations. The returned string may be empty but may not be
8236 * {@code null}.
8237 *
8238 * @return a string representation of this component's state
8239 * @since 1.0
8240 */
8241 protected String paramString() {
8242 final String thisName = Objects.toString(getName(), "");
8243 final String invalid = isValid() ? "" : ",invalid";
8244 final String hidden = visible ? "" : ",hidden";
8245 final String disabled = enabled ? "" : ",disabled";
8246 return thisName + ',' + x + ',' + y + ',' + width + 'x' + height
8247 + invalid + hidden + disabled;
8248 }
8249
8250 /**
8251 * Returns a string representation of this component and its values.
8252 * @return a string representation of this component
8253 * @since 1.0
8254 */
8255 public String toString() {
8256 return getClass().getName() + '[' + paramString() + ']';
8257 }
8258
8259 /**
8260 * Prints a listing of this component to the standard system output
8261 * stream {@code System.out}.
8262 * @see java.lang.System#out
8263 * @since 1.0
8264 */
8265 public void list() {
8266 list(System.out, 0);
8267 }
8268
8269 /**
8270 * Prints a listing of this component to the specified output
8271 * stream.
8272 * @param out a print stream
8273 * @throws NullPointerException if {@code out} is {@code null}
8274 * @since 1.0
8275 */
8276 public void list(PrintStream out) {
8277 list(out, 0);
8278 }
8279
8280 /**
8281 * Prints out a list, starting at the specified indentation, to the
8336 * registered for all bound properties of this class, including the
8337 * following:
8338 * <ul>
8339 * <li>this Component's font ("font")</li>
8340 * <li>this Component's background color ("background")</li>
8341 * <li>this Component's foreground color ("foreground")</li>
8342 * <li>this Component's focusability ("focusable")</li>
8343 * <li>this Component's focus traversal keys enabled state
8344 * ("focusTraversalKeysEnabled")</li>
8345 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8346 * ("forwardFocusTraversalKeys")</li>
8347 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8348 * ("backwardFocusTraversalKeys")</li>
8349 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8350 * ("upCycleFocusTraversalKeys")</li>
8351 * <li>this Component's preferred size ("preferredSize")</li>
8352 * <li>this Component's minimum size ("minimumSize")</li>
8353 * <li>this Component's maximum size ("maximumSize")</li>
8354 * <li>this Component's name ("name")</li>
8355 * </ul>
8356 * Note that if this {@code Component} is inheriting a bound property, then no
8357 * event will be fired in response to a change in the inherited property.
8358 * <p>
8359 * If {@code listener} is {@code null},
8360 * no exception is thrown and no action is performed.
8361 *
8362 * @param listener the property change listener to be added
8363 *
8364 * @see #removePropertyChangeListener
8365 * @see #getPropertyChangeListeners
8366 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8367 */
8368 public void addPropertyChangeListener(
8369 PropertyChangeListener listener) {
8370 synchronized (getObjectLock()) {
8371 if (listener == null) {
8372 return;
8373 }
8374 if (changeSupport == null) {
8375 changeSupport = new PropertyChangeSupport(this);
8376 }
8377 changeSupport.addPropertyChangeListener(listener);
8378 }
8379 }
8388 * @param listener the PropertyChangeListener to be removed
8389 *
8390 * @see #addPropertyChangeListener
8391 * @see #getPropertyChangeListeners
8392 * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener)
8393 */
8394 public void removePropertyChangeListener(
8395 PropertyChangeListener listener) {
8396 synchronized (getObjectLock()) {
8397 if (listener == null || changeSupport == null) {
8398 return;
8399 }
8400 changeSupport.removePropertyChangeListener(listener);
8401 }
8402 }
8403
8404 /**
8405 * Returns an array of all the property change listeners
8406 * registered on this component.
8407 *
8408 * @return all of this component's {@code PropertyChangeListener}s
8409 * or an empty array if no property change
8410 * listeners are currently registered
8411 *
8412 * @see #addPropertyChangeListener
8413 * @see #removePropertyChangeListener
8414 * @see #getPropertyChangeListeners(java.lang.String)
8415 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners
8416 * @since 1.4
8417 */
8418 public PropertyChangeListener[] getPropertyChangeListeners() {
8419 synchronized (getObjectLock()) {
8420 if (changeSupport == null) {
8421 return new PropertyChangeListener[0];
8422 }
8423 return changeSupport.getPropertyChangeListeners();
8424 }
8425 }
8426
8427 /**
8428 * Adds a PropertyChangeListener to the listener list for a specific
8429 * property. The specified property may be user-defined, or one of the
8430 * following:
8431 * <ul>
8432 * <li>this Component's font ("font")</li>
8433 * <li>this Component's background color ("background")</li>
8434 * <li>this Component's foreground color ("foreground")</li>
8435 * <li>this Component's focusability ("focusable")</li>
8436 * <li>this Component's focus traversal keys enabled state
8437 * ("focusTraversalKeysEnabled")</li>
8438 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS
8439 * ("forwardFocusTraversalKeys")</li>
8440 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS
8441 * ("backwardFocusTraversalKeys")</li>
8442 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS
8443 * ("upCycleFocusTraversalKeys")</li>
8444 * </ul>
8445 * Note that if this {@code Component} is inheriting a bound property, then no
8446 * event will be fired in response to a change in the inherited property.
8447 * <p>
8448 * If {@code propertyName} or {@code listener} is {@code null},
8449 * no exception is thrown and no action is taken.
8450 *
8451 * @param propertyName one of the property names listed above
8452 * @param listener the property change listener to be added
8453 *
8454 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8455 * @see #getPropertyChangeListeners(java.lang.String)
8456 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8457 */
8458 public void addPropertyChangeListener(
8459 String propertyName,
8460 PropertyChangeListener listener) {
8461 synchronized (getObjectLock()) {
8462 if (listener == null) {
8463 return;
8464 }
8465 if (changeSupport == null) {
8466 changeSupport = new PropertyChangeSupport(this);
8467 }
8468 changeSupport.addPropertyChangeListener(propertyName, listener);
8469 }
8470 }
8471
8472 /**
8473 * Removes a {@code PropertyChangeListener} from the listener
8474 * list for a specific property. This method should be used to remove
8475 * {@code PropertyChangeListener}s
8476 * that were registered for a specific bound property.
8477 * <p>
8478 * If {@code propertyName} or {@code listener} is {@code null},
8479 * no exception is thrown and no action is taken.
8480 *
8481 * @param propertyName a valid property name
8482 * @param listener the PropertyChangeListener to be removed
8483 *
8484 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8485 * @see #getPropertyChangeListeners(java.lang.String)
8486 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener)
8487 */
8488 public void removePropertyChangeListener(
8489 String propertyName,
8490 PropertyChangeListener listener) {
8491 synchronized (getObjectLock()) {
8492 if (listener == null || changeSupport == null) {
8493 return;
8494 }
8495 changeSupport.removePropertyChangeListener(propertyName, listener);
8496 }
8497 }
8498
8499 /**
8500 * Returns an array of all the listeners which have been associated
8501 * with the named property.
8502 *
8503 * @param propertyName the property name
8504 * @return all of the {@code PropertyChangeListener}s associated with
8505 * the named property; if no such listeners have been added or
8506 * if {@code propertyName} is {@code null}, an empty
8507 * array is returned
8508 *
8509 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8510 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener)
8511 * @see #getPropertyChangeListeners
8512 * @since 1.4
8513 */
8514 public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
8515 synchronized (getObjectLock()) {
8516 if (changeSupport == null) {
8517 return new PropertyChangeListener[0];
8518 }
8519 return changeSupport.getPropertyChangeListeners(propertyName);
8520 }
8521 }
8522
8523 /**
8524 * Support for reporting bound property changes for Object properties.
8525 * This method can be called when a bound property has changed and it will
8526 * send the appropriate PropertyChangeEvent to any registered
8687 */
8688 public void firePropertyChange(String propertyName, double oldValue, double newValue) {
8689 if (changeSupport == null || oldValue == newValue) {
8690 return;
8691 }
8692 firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue));
8693 }
8694
8695
8696 // Serialization support.
8697
8698 /**
8699 * Component Serialized Data Version.
8700 *
8701 * @serial
8702 */
8703 private int componentSerializedDataVersion = 4;
8704
8705 /**
8706 * This hack is for Swing serialization. It will invoke
8707 * the Swing package private method {@code compWriteObjectNotify}.
8708 */
8709 private void doSwingSerialization() {
8710 Package swingPackage = Package.getPackage("javax.swing");
8711 // For Swing serialization to correctly work Swing needs to
8712 // be notified before Component does it's serialization. This
8713 // hack accommodates this.
8714 //
8715 // Swing classes MUST be loaded by the bootstrap class loader,
8716 // otherwise we don't consider them.
8717 for (Class<?> klass = Component.this.getClass(); klass != null;
8718 klass = klass.getSuperclass()) {
8719 if (klass.getPackage() == swingPackage &&
8720 klass.getClassLoader() == null) {
8721 final Class<?> swingClass = klass;
8722 // Find the first override of the compWriteObjectNotify method
8723 Method[] methods = AccessController.doPrivileged(
8724 new PrivilegedAction<Method[]>() {
8725 public Method[] run() {
8726 return swingClass.getDeclaredMethods();
8727 }
8741 // Invoke the method
8742 try {
8743 method.invoke(this, (Object[]) null);
8744 } catch (IllegalAccessException iae) {
8745 } catch (InvocationTargetException ite) {
8746 }
8747 // We're done, bail.
8748 return;
8749 }
8750 }
8751 }
8752 }
8753 }
8754
8755 /**
8756 * Writes default serializable fields to stream. Writes
8757 * a variety of serializable listeners as optional data.
8758 * The non-serializable listeners are detected and
8759 * no attempt is made to serialize them.
8760 *
8761 * @param s the {@code ObjectOutputStream} to write
8762 * @serialData {@code null} terminated sequence of
8763 * 0 or more pairs; the pair consists of a {@code String}
8764 * and an {@code Object}; the {@code String} indicates
8765 * the type of object and is one of the following (as of 1.4):
8766 * {@code componentListenerK} indicating an
8767 * {@code ComponentListener} object;
8768 * {@code focusListenerK} indicating an
8769 * {@code FocusListener} object;
8770 * {@code keyListenerK} indicating an
8771 * {@code KeyListener} object;
8772 * {@code mouseListenerK} indicating an
8773 * {@code MouseListener} object;
8774 * {@code mouseMotionListenerK} indicating an
8775 * {@code MouseMotionListener} object;
8776 * {@code inputMethodListenerK} indicating an
8777 * {@code InputMethodListener} object;
8778 * {@code hierarchyListenerK} indicating an
8779 * {@code HierarchyListener} object;
8780 * {@code hierarchyBoundsListenerK} indicating an
8781 * {@code HierarchyBoundsListener} object;
8782 * {@code mouseWheelListenerK} indicating an
8783 * {@code MouseWheelListener} object
8784 * @serialData an optional {@code ComponentOrientation}
8785 * (after {@code inputMethodListener}, as of 1.2)
8786 *
8787 * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener)
8788 * @see #componentListenerK
8789 * @see #focusListenerK
8790 * @see #keyListenerK
8791 * @see #mouseListenerK
8792 * @see #mouseMotionListenerK
8793 * @see #inputMethodListenerK
8794 * @see #hierarchyListenerK
8795 * @see #hierarchyBoundsListenerK
8796 * @see #mouseWheelListenerK
8797 * @see #readObject(ObjectInputStream)
8798 */
8799 private void writeObject(ObjectOutputStream s)
8800 throws IOException
8801 {
8802 doSwingSerialization();
8803
8804 s.defaultWriteObject();
8805
8807 AWTEventMulticaster.save(s, focusListenerK, focusListener);
8808 AWTEventMulticaster.save(s, keyListenerK, keyListener);
8809 AWTEventMulticaster.save(s, mouseListenerK, mouseListener);
8810 AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener);
8811 AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener);
8812
8813 s.writeObject(null);
8814 s.writeObject(componentOrientation);
8815
8816 AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener);
8817 AWTEventMulticaster.save(s, hierarchyBoundsListenerK,
8818 hierarchyBoundsListener);
8819 s.writeObject(null);
8820
8821 AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener);
8822 s.writeObject(null);
8823
8824 }
8825
8826 /**
8827 * Reads the {@code ObjectInputStream} and if it isn't
8828 * {@code null} adds a listener to receive a variety
8829 * of events fired by the component.
8830 * Unrecognized keys or values will be ignored.
8831 *
8832 * @param s the {@code ObjectInputStream} to read
8833 * @see #writeObject(ObjectOutputStream)
8834 */
8835 private void readObject(ObjectInputStream s)
8836 throws ClassNotFoundException, IOException
8837 {
8838 objectLock = new Object();
8839
8840 acc = AccessController.getContext();
8841
8842 s.defaultReadObject();
8843
8844 appContext = AppContext.getAppContext();
8845 coalescingEnabled = checkCoalescing();
8846 if (componentSerializedDataVersion < 4) {
8847 // These fields are non-transient and rely on default
8848 // serialization. However, the default values are insufficient,
8849 // so we need to set them explicitly for object data streams prior
8850 // to 1.4.
8851 focusable = true;
8852 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
8954 // might have been caused by reasons unrelated to
8955 // mouse wheel listeners
8956
8957 if (!e.eof) {
8958 throw (e);
8959 }
8960 }
8961
8962 if (popups != null) {
8963 int npopups = popups.size();
8964 for (int i = 0 ; i < npopups ; i++) {
8965 PopupMenu popup = popups.elementAt(i);
8966 popup.parent = this;
8967 }
8968 }
8969 }
8970
8971 /**
8972 * Sets the language-sensitive orientation that is to be used to order
8973 * the elements or text within this component. Language-sensitive
8974 * {@code LayoutManager} and {@code Component}
8975 * subclasses will use this property to
8976 * determine how to lay out and draw components.
8977 * <p>
8978 * At construction time, a component's orientation is set to
8979 * {@code ComponentOrientation.UNKNOWN},
8980 * indicating that it has not been specified
8981 * explicitly. The UNKNOWN orientation behaves the same as
8982 * {@code ComponentOrientation.LEFT_TO_RIGHT}.
8983 * <p>
8984 * To set the orientation of a single component, use this method.
8985 * To set the orientation of an entire component
8986 * hierarchy, use
8987 * {@link #applyComponentOrientation applyComponentOrientation}.
8988 * <p>
8989 * This method changes layout-related information, and therefore,
8990 * invalidates the component hierarchy.
8991 *
8992 * @param o the orientation to be set
8993 *
8994 * @see ComponentOrientation
8995 * @see #invalidate
8996 *
8997 * @author Laura Werner, IBM
8998 * @beaninfo
8999 * bound: true
9000 */
9001 public void setComponentOrientation(ComponentOrientation o) {
9002 ComponentOrientation oldValue = componentOrientation;
9003 componentOrientation = o;
9004
9005 // This is a bound property, so report the change to
9006 // any registered listeners. (Cheap if there are none.)
9007 firePropertyChange("componentOrientation", oldValue, o);
9008
9009 // This could change the preferred size of the Component.
9010 invalidateIfValid();
9011 }
9012
9013 /**
9014 * Retrieves the language-sensitive orientation that is to be used to order
9015 * the elements or text within this component. {@code LayoutManager}
9016 * and {@code Component}
9017 * subclasses that wish to respect orientation should call this method to
9018 * get the component's orientation before performing layout or drawing.
9019 *
9020 * @return the orientation to order the elements or text
9021 * @see ComponentOrientation
9022 *
9023 * @author Laura Werner, IBM
9024 */
9025 public ComponentOrientation getComponentOrientation() {
9026 return componentOrientation;
9027 }
9028
9029 /**
9030 * Sets the {@code ComponentOrientation} property of this component
9031 * and all components contained within it.
9032 * <p>
9033 * This method changes layout-related information, and therefore,
9034 * invalidates the component hierarchy.
9035 *
9036 *
9037 * @param orientation the new component orientation of this component and
9038 * the components contained within it.
9039 * @exception NullPointerException if {@code orientation} is null.
9040 * @see #setComponentOrientation
9041 * @see #getComponentOrientation
9042 * @see #invalidate
9043 * @since 1.4
9044 */
9045 public void applyComponentOrientation(ComponentOrientation orientation) {
9046 if (orientation == null) {
9047 throw new NullPointerException();
9048 }
9049 setComponentOrientation(orientation);
9050 }
9051
9052 final boolean canBeFocusOwner() {
9053 // It is enabled, visible, focusable.
9054 if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) {
9055 return true;
9056 }
9057 return false;
9058 }
9059
9087 final void relocateComponent() {
9088 synchronized (getTreeLock()) {
9089 if (peer == null) {
9090 return;
9091 }
9092 int nativeX = x;
9093 int nativeY = y;
9094 for (Component cont = getContainer();
9095 cont != null && cont.isLightweight();
9096 cont = cont.getContainer())
9097 {
9098 nativeX += cont.x;
9099 nativeY += cont.y;
9100 }
9101 peer.setBounds(nativeX, nativeY, width, height,
9102 ComponentPeer.SET_LOCATION);
9103 }
9104 }
9105
9106 /**
9107 * Returns the {@code Window} ancestor of the component.
9108 * @return Window ancestor of the component or component by itself if it is Window;
9109 * null, if component is not a part of window hierarchy
9110 */
9111 Window getContainingWindow() {
9112 return SunToolkit.getContainingWindow(this);
9113 }
9114
9115 /**
9116 * Initialize JNI field and method IDs
9117 */
9118 private static native void initIDs();
9119
9120 /*
9121 * --- Accessibility Support ---
9122 *
9123 * Component will contain all of the methods in interface Accessible,
9124 * though it won't actually implement the interface - that will be up
9125 * to the individual objects which extend Component.
9126 */
9127
9128 /**
9129 * The {@code AccessibleContext} associated with this {@code Component}.
9130 */
9131 protected AccessibleContext accessibleContext = null;
9132
9133 /**
9134 * Gets the {@code AccessibleContext} associated
9135 * with this {@code Component}.
9136 * The method implemented by this base
9137 * class returns null. Classes that extend {@code Component}
9138 * should implement this method to return the
9139 * {@code AccessibleContext} associated with the subclass.
9140 *
9141 *
9142 * @return the {@code AccessibleContext} of this
9143 * {@code Component}
9144 * @since 1.3
9145 */
9146 public AccessibleContext getAccessibleContext() {
9147 return accessibleContext;
9148 }
9149
9150 /**
9151 * Inner class of Component used to provide default support for
9152 * accessibility. This class is not meant to be used directly by
9153 * application developers, but is instead meant only to be
9154 * subclassed by component developers.
9155 * <p>
9156 * The class used to obtain the accessible role for this object.
9157 * @since 1.3
9158 */
9159 protected abstract class AccessibleAWTComponent extends AccessibleContext
9160 implements Serializable, AccessibleComponent {
9161
9162 private static final long serialVersionUID = 642321655757800191L;
9163
9224 */
9225 protected class AccessibleAWTFocusHandler implements FocusListener {
9226 public void focusGained(FocusEvent event) {
9227 if (accessibleContext != null) {
9228 accessibleContext.firePropertyChange(
9229 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9230 null, AccessibleState.FOCUSED);
9231 }
9232 }
9233 public void focusLost(FocusEvent event) {
9234 if (accessibleContext != null) {
9235 accessibleContext.firePropertyChange(
9236 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9237 AccessibleState.FOCUSED, null);
9238 }
9239 }
9240 } // inner class AccessibleAWTFocusHandler
9241
9242
9243 /**
9244 * Adds a {@code PropertyChangeListener} to the listener list.
9245 *
9246 * @param listener the property change listener to be added
9247 */
9248 public void addPropertyChangeListener(PropertyChangeListener listener) {
9249 if (accessibleAWTComponentHandler == null) {
9250 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler();
9251 }
9252 if (accessibleAWTFocusHandler == null) {
9253 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler();
9254 }
9255 if (propertyListenersCount++ == 0) {
9256 Component.this.addComponentListener(accessibleAWTComponentHandler);
9257 Component.this.addFocusListener(accessibleAWTFocusHandler);
9258 }
9259 super.addPropertyChangeListener(listener);
9260 }
9261
9262 /**
9263 * Remove a PropertyChangeListener from the listener list.
9264 * This removes a PropertyChangeListener that was registered
9265 * for all properties.
9266 *
9267 * @param listener The PropertyChangeListener to be removed
9268 */
9269 public void removePropertyChangeListener(PropertyChangeListener listener) {
9270 if (--propertyListenersCount == 0) {
9271 Component.this.removeComponentListener(accessibleAWTComponentHandler);
9272 Component.this.removeFocusListener(accessibleAWTFocusHandler);
9273 }
9274 super.removePropertyChangeListener(listener);
9275 }
9276
9277 // AccessibleContext methods
9278 //
9279 /**
9280 * Gets the accessible name of this object. This should almost never
9281 * return {@code java.awt.Component.getName()},
9282 * as that generally isn't a localized name,
9283 * and doesn't have meaning for the user. If the
9284 * object is fundamentally a text object (e.g. a menu item), the
9285 * accessible name should be the text of the object (e.g. "save").
9286 * If the object has a tooltip, the tooltip text may also be an
9287 * appropriate String to return.
9288 *
9289 * @return the localized name of the object -- can be
9290 * {@code null} if this
9291 * object does not have a name
9292 * @see javax.accessibility.AccessibleContext#setAccessibleName
9293 */
9294 public String getAccessibleName() {
9295 return accessibleName;
9296 }
9297
9298 /**
9299 * Gets the accessible description of this object. This should be
9300 * a concise, localized description of what this object is - what
9301 * is its meaning to the user. If the object has a tooltip, the
9302 * tooltip text may be an appropriate string to return, assuming
9303 * it contains a concise description of the object (instead of just
9304 * the name of the object - e.g. a "Save" icon on a toolbar that
9305 * had "save" as the tooltip text shouldn't return the tooltip
9306 * text as the description, but something like "Saves the current
9307 * text document" instead).
9308 *
9309 * @return the localized description of the object -- can be
9310 * {@code null} if this object does not have a description
9311 * @see javax.accessibility.AccessibleContext#setAccessibleDescription
9312 */
9313 public String getAccessibleDescription() {
9314 return accessibleDescription;
9315 }
9316
9317 /**
9318 * Gets the role of this object.
9319 *
9320 * @return an instance of {@code AccessibleRole}
9321 * describing the role of the object
9322 * @see javax.accessibility.AccessibleRole
9323 */
9324 public AccessibleRole getAccessibleRole() {
9325 return AccessibleRole.AWT_COMPONENT;
9326 }
9327
9328 /**
9329 * Gets the state of this object.
9330 *
9331 * @return an instance of {@code AccessibleStateSet}
9332 * containing the current state set of the object
9333 * @see javax.accessibility.AccessibleState
9334 */
9335 public AccessibleStateSet getAccessibleStateSet() {
9336 return Component.this.getAccessibleStateSet();
9337 }
9338
9339 /**
9340 * Gets the {@code Accessible} parent of this object.
9341 * If the parent of this object implements {@code Accessible},
9342 * this method should simply return {@code getParent}.
9343 *
9344 * @return the {@code Accessible} parent of this
9345 * object -- can be {@code null} if this
9346 * object does not have an {@code Accessible} parent
9347 */
9348 public Accessible getAccessibleParent() {
9349 if (accessibleParent != null) {
9350 return accessibleParent;
9351 } else {
9352 Container parent = getParent();
9353 if (parent instanceof Accessible) {
9354 return (Accessible) parent;
9355 }
9356 }
9357 return null;
9358 }
9359
9360 /**
9361 * Gets the index of this object in its accessible parent.
9362 *
9363 * @return the index of this object in its parent; or -1 if this
9364 * object does not have an accessible parent
9365 * @see #getAccessibleParent
9366 */
9367 public int getAccessibleIndexInParent() {
9368 return Component.this.getAccessibleIndexInParent();
9369 }
9370
9371 /**
9372 * Returns the number of accessible children in the object. If all
9373 * of the children of this object implement {@code Accessible},
9374 * then this method should return the number of children of this object.
9375 *
9376 * @return the number of accessible children in the object
9377 */
9378 public int getAccessibleChildrenCount() {
9379 return 0; // Components don't have children
9380 }
9381
9382 /**
9383 * Returns the nth {@code Accessible} child of the object.
9384 *
9385 * @param i zero-based index of child
9386 * @return the nth {@code Accessible} child of the object
9387 */
9388 public Accessible getAccessibleChild(int i) {
9389 return null; // Components don't have children
9390 }
9391
9392 /**
9393 * Returns the locale of this object.
9394 *
9395 * @return the locale of this object
9396 */
9397 public Locale getLocale() {
9398 return Component.this.getLocale();
9399 }
9400
9401 /**
9402 * Gets the {@code AccessibleComponent} associated
9403 * with this object if one exists.
9404 * Otherwise return {@code null}.
9405 *
9406 * @return the component
9407 */
9408 public AccessibleComponent getAccessibleComponent() {
9409 return this;
9410 }
9411
9412
9413 // AccessibleComponent methods
9414 //
9415 /**
9416 * Gets the background color of this object.
9417 *
9418 * @return the background color, if supported, of the object;
9419 * otherwise, {@code null}
9420 */
9421 public Color getBackground() {
9422 return Component.this.getBackground();
9423 }
9424
9425 /**
9426 * Sets the background color of this object.
9427 * (For transparency, see {@code isOpaque}.)
9428 *
9429 * @param c the new {@code Color} for the background
9430 * @see Component#isOpaque
9431 */
9432 public void setBackground(Color c) {
9433 Component.this.setBackground(c);
9434 }
9435
9436 /**
9437 * Gets the foreground color of this object.
9438 *
9439 * @return the foreground color, if supported, of the object;
9440 * otherwise, {@code null}
9441 */
9442 public Color getForeground() {
9443 return Component.this.getForeground();
9444 }
9445
9446 /**
9447 * Sets the foreground color of this object.
9448 *
9449 * @param c the new {@code Color} for the foreground
9450 */
9451 public void setForeground(Color c) {
9452 Component.this.setForeground(c);
9453 }
9454
9455 /**
9456 * Gets the {@code Cursor} of this object.
9457 *
9458 * @return the {@code Cursor}, if supported,
9459 * of the object; otherwise, {@code null}
9460 */
9461 public Cursor getCursor() {
9462 return Component.this.getCursor();
9463 }
9464
9465 /**
9466 * Sets the {@code Cursor} of this object.
9467 * <p>
9468 * The method may have no visual effect if the Java platform
9469 * implementation and/or the native system do not support
9470 * changing the mouse cursor shape.
9471 * @param cursor the new {@code Cursor} for the object
9472 */
9473 public void setCursor(Cursor cursor) {
9474 Component.this.setCursor(cursor);
9475 }
9476
9477 /**
9478 * Gets the {@code Font} of this object.
9479 *
9480 * @return the {@code Font}, if supported,
9481 * for the object; otherwise, {@code null}
9482 */
9483 public Font getFont() {
9484 return Component.this.getFont();
9485 }
9486
9487 /**
9488 * Sets the {@code Font} of this object.
9489 *
9490 * @param f the new {@code Font} for the object
9491 */
9492 public void setFont(Font f) {
9493 Component.this.setFont(f);
9494 }
9495
9496 /**
9497 * Gets the {@code FontMetrics} of this object.
9498 *
9499 * @param f the {@code Font}
9500 * @return the {@code FontMetrics}, if supported,
9501 * the object; otherwise, {@code null}
9502 * @see #getFont
9503 */
9504 public FontMetrics getFontMetrics(Font f) {
9505 if (f == null) {
9506 return null;
9507 } else {
9508 return Component.this.getFontMetrics(f);
9509 }
9510 }
9511
9512 /**
9513 * Determines if the object is enabled.
9514 *
9515 * @return true if object is enabled; otherwise, false
9516 */
9517 public boolean isEnabled() {
9518 return Component.this.isEnabled();
9519 }
9520
9521 /**
9529 if (b != old) {
9530 if (accessibleContext != null) {
9531 if (b) {
9532 accessibleContext.firePropertyChange(
9533 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9534 null, AccessibleState.ENABLED);
9535 } else {
9536 accessibleContext.firePropertyChange(
9537 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9538 AccessibleState.ENABLED, null);
9539 }
9540 }
9541 }
9542 }
9543
9544 /**
9545 * Determines if the object is visible. Note: this means that the
9546 * object intends to be visible; however, it may not in fact be
9547 * showing on the screen because one of the objects that this object
9548 * is contained by is not visible. To determine if an object is
9549 * showing on the screen, use {@code isShowing}.
9550 *
9551 * @return true if object is visible; otherwise, false
9552 */
9553 public boolean isVisible() {
9554 return Component.this.isVisible();
9555 }
9556
9557 /**
9558 * Sets the visible state of the object.
9559 *
9560 * @param b if true, shows this object; otherwise, hides it
9561 */
9562 public void setVisible(boolean b) {
9563 boolean old = Component.this.isVisible();
9564 Component.this.setVisible(b);
9565 if (b != old) {
9566 if (accessibleContext != null) {
9567 if (b) {
9568 accessibleContext.firePropertyChange(
9569 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
9578 }
9579
9580 /**
9581 * Determines if the object is showing. This is determined by checking
9582 * the visibility of the object and ancestors of the object. Note:
9583 * this will return true even if the object is obscured by another
9584 * (for example, it happens to be underneath a menu that was pulled
9585 * down).
9586 *
9587 * @return true if object is showing; otherwise, false
9588 */
9589 public boolean isShowing() {
9590 return Component.this.isShowing();
9591 }
9592
9593 /**
9594 * Checks whether the specified point is within this object's bounds,
9595 * where the point's x and y coordinates are defined to be relative to
9596 * the coordinate system of the object.
9597 *
9598 * @param p the {@code Point} relative to the
9599 * coordinate system of the object
9600 * @return true if object contains {@code Point}; otherwise false
9601 */
9602 public boolean contains(Point p) {
9603 return Component.this.contains(p);
9604 }
9605
9606 /**
9607 * Returns the location of the object on the screen.
9608 *
9609 * @return location of object on screen -- can be
9610 * {@code null} if this object is not on the screen
9611 */
9612 public Point getLocationOnScreen() {
9613 synchronized (Component.this.getTreeLock()) {
9614 if (Component.this.isShowing()) {
9615 return Component.this.getLocationOnScreen();
9616 } else {
9617 return null;
9618 }
9619 }
9620 }
9621
9622 /**
9623 * Gets the location of the object relative to the parent in the form
9624 * of a point specifying the object's top-left corner in the screen's
9625 * coordinate space.
9626 *
9627 * @return an instance of Point representing the top-left corner of
9628 * the object's bounds in the coordinate space of the screen;
9629 * {@code null} if this object or its parent are not on the screen
9630 */
9631 public Point getLocation() {
9632 return Component.this.getLocation();
9633 }
9634
9635 /**
9636 * Sets the location of the object relative to the parent.
9637 * @param p the coordinates of the object
9638 */
9639 public void setLocation(Point p) {
9640 Component.this.setLocation(p);
9641 }
9642
9643 /**
9644 * Gets the bounds of this object in the form of a Rectangle object.
9645 * The bounds specify this object's width, height, and location
9646 * relative to its parent.
9647 *
9648 * @return a rectangle indicating this component's bounds;
9649 * {@code null} if this object is not on the screen
9650 */
9651 public Rectangle getBounds() {
9652 return Component.this.getBounds();
9653 }
9654
9655 /**
9656 * Sets the bounds of this object in the form of a
9657 * {@code Rectangle} object.
9658 * The bounds specify this object's width, height, and location
9659 * relative to its parent.
9660 *
9661 * @param r a rectangle indicating this component's bounds
9662 */
9663 public void setBounds(Rectangle r) {
9664 Component.this.setBounds(r);
9665 }
9666
9667 /**
9668 * Returns the size of this object in the form of a
9669 * {@code Dimension} object. The height field of the
9670 * {@code Dimension} object contains this object's
9671 * height, and the width field of the {@code Dimension}
9672 * object contains this object's width.
9673 *
9674 * @return a {@code Dimension} object that indicates
9675 * the size of this component; {@code null} if
9676 * this object is not on the screen
9677 */
9678 public Dimension getSize() {
9679 return Component.this.getSize();
9680 }
9681
9682 /**
9683 * Resizes this object so that it has width and height.
9684 *
9685 * @param d - the dimension specifying the new size of the object
9686 */
9687 public void setSize(Dimension d) {
9688 Component.this.setSize(d);
9689 }
9690
9691 /**
9692 * Returns the {@code Accessible} child,
9693 * if one exists, contained at the local
9694 * coordinate {@code Point}. Otherwise returns
9695 * {@code null}.
9696 *
9697 * @param p the point defining the top-left corner of
9698 * the {@code Accessible}, given in the
9699 * coordinate space of the object's parent
9700 * @return the {@code Accessible}, if it exists,
9701 * at the specified location; else {@code null}
9702 */
9703 public Accessible getAccessibleAt(Point p) {
9704 return null; // Components don't have children
9705 }
9706
9707 /**
9708 * Returns whether this object can accept focus or not.
9709 *
9710 * @return true if object can accept focus; otherwise false
9711 */
9712 public boolean isFocusTraversable() {
9713 return Component.this.isFocusTraversable();
9714 }
9715
9716 /**
9717 * Requests focus for this object.
9718 */
9719 public void requestFocus() {
9720 Component.this.requestFocus();
9721 }
9755 int index = -1;
9756 Container parent = this.getParent();
9757 if (parent != null && parent instanceof Accessible) {
9758 Component ca[] = parent.getComponents();
9759 for (int i = 0; i < ca.length; i++) {
9760 if (ca[i] instanceof Accessible) {
9761 index++;
9762 }
9763 if (this.equals(ca[i])) {
9764 return index;
9765 }
9766 }
9767 }
9768 return -1;
9769 }
9770 }
9771
9772 /**
9773 * Gets the current state set of this object.
9774 *
9775 * @return an instance of {@code AccessibleStateSet}
9776 * containing the current state set of the object
9777 * @see AccessibleState
9778 */
9779 AccessibleStateSet getAccessibleStateSet() {
9780 synchronized (getTreeLock()) {
9781 AccessibleStateSet states = new AccessibleStateSet();
9782 if (this.isEnabled()) {
9783 states.add(AccessibleState.ENABLED);
9784 }
9785 if (this.isFocusTraversable()) {
9786 states.add(AccessibleState.FOCUSABLE);
9787 }
9788 if (this.isVisible()) {
9789 states.add(AccessibleState.VISIBLE);
9790 }
9791 if (this.isShowing()) {
9792 states.add(AccessibleState.SHOWING);
9793 }
9794 if (this.isFocusOwner()) {
9795 states.add(AccessibleState.FOCUSED);
|