History

My first initial commit with all of mine experimental changes.

Dmitry Kabak (userdima committed 13 years ago

Commit d37b88d1 parent 3f5b46618352 files · +2598093 −-8690Browse files

Showing the changes to java/pkg/java/awt/Component.java (1 of 18352 files). Show all

Unified · Split

java/pkg/java/awt/Component.java+10099−0
@@ -0,0 +1,10099 @@
1/*
2 * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25package java.awt;
26
27import java.io.PrintStream;
28import java.io.PrintWriter;
29import java.util.Vector;
30import java.util.Locale;
31import java.util.EventListener;
32import java.util.Iterator;
33import java.util.HashSet;
34import java.util.Map;
35import java.util.Set;
36import java.util.Collections;
37import java.awt.peer.ComponentPeer;
38import java.awt.peer.ContainerPeer;
39import java.awt.peer.LightweightPeer;
40import java.awt.image.BufferStrategy;
41import java.awt.image.ImageObserver;
42import java.awt.image.ImageProducer;
43import java.awt.image.ColorModel;
44import java.awt.image.VolatileImage;
45import java.awt.event.*;
46import java.io.Serializable;
47import java.io.ObjectOutputStream;
48import java.io.ObjectInputStream;
49import java.io.IOException;
50import java.beans.PropertyChangeListener;
51import java.beans.PropertyChangeSupport;
52import java.beans.Transient;
53import java.awt.event.InputMethodListener;
54import java.awt.event.InputMethodEvent;
55import java.awt.im.InputContext;
56import java.awt.im.InputMethodRequests;
57import java.awt.dnd.DropTarget;
58import java.lang.reflect.InvocationTargetException;
59import java.lang.reflect.Method;
60import java.security.AccessController;
61import java.security.PrivilegedAction;
62import java.security.AccessControlContext;
63import javax.accessibility.*;
64import java.applet.Applet;
65
66import sun.security.action.GetPropertyAction;
67import sun.awt.AppContext;
68import sun.awt.AWTAccessor;
69import sun.awt.ConstrainableGraphics;
70import sun.awt.SubRegionShowable;
71import sun.awt.SunToolkit;
72import sun.awt.WindowClosingListener;
73import sun.awt.CausedFocusEvent;
74import sun.awt.EmbeddedFrame;
75import sun.awt.dnd.SunDropTargetEvent;
76import sun.awt.im.CompositionArea;
77import sun.font.FontManager;
78import sun.font.FontManagerFactory;
79import sun.font.SunFontManager;
80import sun.java2d.SunGraphics2D;
81import sun.java2d.pipe.Region;
82import sun.awt.image.VSyncedBSManager;
83import sun.java2d.pipe.hw.ExtendedBufferCapabilities;
84import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*;
85import sun.awt.RequestFocusController;
86import sun.java2d.SunGraphicsEnvironment;
87import sun.util.logging.PlatformLogger;
88
89/**
90 * A <em>component</em> is an object having a graphical representation
91 * that can be displayed on the screen and that can interact with the
92 * user. Examples of components are the buttons, checkboxes, and scrollbars
93 * of a typical graphical user interface. <p>
94 * The <code>Component</code> class is the abstract superclass of
95 * the nonmenu-related Abstract Window Toolkit components. Class
96 * <code>Component</code> can also be extended directly to create a
97 * lightweight component. A lightweight component is a component that is
98 * not associated with a native window. On the contrary, a heavyweight
99 * component is associated with a native window. The {@link #isLightweight()}
100 * method may be used to distinguish between the two kinds of the components.
101 * <p>
102 * Lightweight and heavyweight components may be mixed in a single component
103 * hierarchy. However, for correct operating of such a mixed hierarchy of
104 * components, the whole hierarchy must be valid. When the hierarchy gets
105 * invalidated, like after changing the bounds of components, or
106 * adding/removing components to/from containers, the whole hierarchy must be
107 * validated afterwards by means of the {@link Container#validate()} method
108 * invoked on the top-most invalid container of the hierarchy.
109 * <p>
110 * <h3>Serialization</h3>
111 * It is important to note that only AWT listeners which conform
112 * to the <code>Serializable</code> protocol will be saved when
113 * the object is stored. If an AWT object has listeners that
114 * aren't marked serializable, they will be dropped at
115 * <code>writeObject</code> time. Developers will need, as always,
116 * to consider the implications of making an object serializable.
117 * One situation to watch out for is this:
118 * <pre>
119 * import java.awt.*;
120 * import java.awt.event.*;
121 * import java.io.Serializable;
122 *
123 * class MyApp implements ActionListener, Serializable
124 * {
125 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
126 * Button aButton = new Button();
127 *
128 * MyApp()
129 * {
130 * // Oops, now aButton has a listener with a reference
131 * // to bigOne!
132 * aButton.addActionListener(this);
133 * }
134 *
135 * public void actionPerformed(ActionEvent e)
136 * {
137 * System.out.println("Hello There");
138 * }
139 * }
140 * </pre>
141 * In this example, serializing <code>aButton</code> by itself
142 * will cause <code>MyApp</code> and everything it refers to
143 * to be serialized as well. The problem is that the listener
144 * is serializable by coincidence, not by design. To separate
145 * the decisions about <code>MyApp</code> and the
146 * <code>ActionListener</code> being serializable one can use a
147 * nested class, as in the following example:
148 * <pre>
149 * import java.awt.*;
150 * import java.awt.event.*;
151 * import java.io.Serializable;
152 *
153 * class MyApp java.io.Serializable
154 * {
155 * BigObjectThatShouldNotBeSerializedWithAButton bigOne;
156 * Button aButton = new Button();
157 *
158 * static class MyActionListener implements ActionListener
159 * {
160 * public void actionPerformed(ActionEvent e)
161 * {
162 * System.out.println("Hello There");
163 * }
164 * }
165 *
166 * MyApp()
167 * {
168 * aButton.addActionListener(new MyActionListener());
169 * }
170 * }
171 * </pre>
172 * <p>
173 * <b>Note</b>: For more information on the paint mechanisms utilitized
174 * by AWT and Swing, including information on how to write the most
175 * efficient painting code, see
176 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
177 * <p>
178 * For details on the focus subsystem, see
179 * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html">
180 * How to Use the Focus Subsystem</a>,
181 * a section in <em>The Java Tutorial</em>, and the
182 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
183 * for more information.
184 *
185 * @author Arthur van Hoff
186 * @author Sami Shaio
187 */
188public abstract class Component implements ImageObserver, MenuContainer,
189 Serializable
190{
191
192 private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component");
193 private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component");
194 private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component");
195 private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component");
196
197 /**
198 * The peer of the component. The peer implements the component's
199 * behavior. The peer is set when the <code>Component</code> is
200 * added to a container that also is a peer.
201 * @see #addNotify
202 * @see #removeNotify
203 */
204 transient ComponentPeer peer;
205
206 /**
207 * The parent of the object. It may be <code>null</code>
208 * for top-level components.
209 * @see #getParent
210 */
211 transient Container parent;
212
213 /**
214 * The <code>AppContext</code> of the component. Applets/Plugin may
215 * change the AppContext.
216 */
217 transient AppContext appContext;
218
219 /**
220 * The x position of the component in the parent's coordinate system.
221 *
222 * @serial
223 * @see #getLocation
224 */
225 int x;
226
227 /**
228 * The y position of the component in the parent's coordinate system.
229 *
230 * @serial
231 * @see #getLocation
232 */
233 int y;
234
235 /**
236 * The width of the component.
237 *
238 * @serial
239 * @see #getSize
240 */
241 int width;
242
243 /**
244 * The height of the component.
245 *
246 * @serial
247 * @see #getSize
248 */
249 int height;
250
251 /**
252 * The foreground color for this component.
253 * <code>foreground</code> can be <code>null</code>.
254 *
255 * @serial
256 * @see #getForeground
257 * @see #setForeground
258 */
259 Color foreground;
260
261 /**
262 * The background color for this component.
263 * <code>background</code> can be <code>null</code>.
264 *
265 * @serial
266 * @see #getBackground
267 * @see #setBackground
268 */
269 Color background;
270
271 /**
272 * The font used by this component.
273 * The <code>font</code> can be <code>null</code>.
274 *
275 * @serial
276 * @see #getFont
277 * @see #setFont
278 */
279 Font font;
280
281 /**
282 * The font which the peer is currently using.
283 * (<code>null</code> if no peer exists.)
284 */
285 Font peerFont;
286
287 /**
288 * The cursor displayed when pointer is over this component.
289 * This value can be <code>null</code>.
290 *
291 * @serial
292 * @see #getCursor
293 * @see #setCursor
294 */
295 Cursor cursor;
296
297 /**
298 * The locale for the component.
299 *
300 * @serial
301 * @see #getLocale
302 * @see #setLocale
303 */
304 Locale locale;
305
306 /**
307 * A reference to a <code>GraphicsConfiguration</code> object
308 * used to describe the characteristics of a graphics
309 * destination.
310 * This value can be <code>null</code>.
311 *
312 * @since 1.3
313 * @serial
314 * @see GraphicsConfiguration
315 * @see #getGraphicsConfiguration
316 */
317 private transient GraphicsConfiguration graphicsConfig = null;
318
319 /**
320 * A reference to a <code>BufferStrategy</code> object
321 * used to manipulate the buffers on this component.
322 *
323 * @since 1.4
324 * @see java.awt.image.BufferStrategy
325 * @see #getBufferStrategy()
326 */
327 transient BufferStrategy bufferStrategy = null;
328
329 /**
330 * True when the object should ignore all repaint events.
331 *
332 * @since 1.4
333 * @serial
334 * @see #setIgnoreRepaint
335 * @see #getIgnoreRepaint
336 */
337 boolean ignoreRepaint = false;
338
339 /**
340 * True when the object is visible. An object that is not
341 * visible is not drawn on the screen.
342 *
343 * @serial
344 * @see #isVisible
345 * @see #setVisible
346 */
347 boolean visible = true;
348
349 /**
350 * True when the object is enabled. An object that is not
351 * enabled does not interact with the user.
352 *
353 * @serial
354 * @see #isEnabled
355 * @see #setEnabled
356 */
357 boolean enabled = true;
358
359 /**
360 * True when the object is valid. An invalid object needs to
361 * be layed out. This flag is set to false when the object
362 * size is changed.
363 *
364 * @serial
365 * @see #isValid
366 * @see #validate
367 * @see #invalidate
368 */
369 private volatile boolean valid = false;
370
371 /**
372 * The <code>DropTarget</code> associated with this component.
373 *
374 * @since 1.2
375 * @serial
376 * @see #setDropTarget
377 * @see #getDropTarget
378 */
379 DropTarget dropTarget;
380
381 /**
382 * @serial
383 * @see #add
384 */
385 Vector popups;
386
387 /**
388 * A component's name.
389 * This field can be <code>null</code>.
390 *
391 * @serial
392 * @see #getName
393 * @see #setName(String)
394 */
395 private String name;
396
397 /**
398 * A bool to determine whether the name has
399 * been set explicitly. <code>nameExplicitlySet</code> will
400 * be false if the name has not been set and
401 * true if it has.
402 *
403 * @serial
404 * @see #getName
405 * @see #setName(String)
406 */
407 private boolean nameExplicitlySet = false;
408
409 /**
410 * Indicates whether this Component can be focused.
411 *
412 * @serial
413 * @see #setFocusable
414 * @see #isFocusable
415 * @since 1.4
416 */
417 private boolean focusable = true;
418
419 private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0;
420 private static final int FOCUS_TRAVERSABLE_DEFAULT = 1;
421 private static final int FOCUS_TRAVERSABLE_SET = 2;
422
423 /**
424 * Tracks whether this Component is relying on default focus travesability.
425 *
426 * @serial
427 * @since 1.4
428 */
429 private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN;
430
431 /**
432 * The focus traversal keys. These keys will generate focus traversal
433 * behavior for Components for which focus traversal keys are enabled. If a
434 * value of null is specified for a traversal key, this Component inherits
435 * that traversal key from its parent. If all ancestors of this Component
436 * have null specified for that traversal key, then the current
437 * KeyboardFocusManager's default traversal key is used.
438 *
439 * @serial
440 * @see #setFocusTraversalKeys
441 * @see #getFocusTraversalKeys
442 * @since 1.4
443 */
444 Set[] focusTraversalKeys;
445
446 private static final String[] focusTraversalKeyPropertyNames = {
447 "forwardFocusTraversalKeys",
448 "backwardFocusTraversalKeys",
449 "upCycleFocusTraversalKeys",
450 "downCycleFocusTraversalKeys"
451 };
452
453 /**
454 * Indicates whether focus traversal keys are enabled for this Component.
455 * Components for which focus traversal keys are disabled receive key
456 * events for focus traversal keys. Components for which focus traversal
457 * keys are enabled do not see these events; instead, the events are
458 * automatically converted to traversal operations.
459 *
460 * @serial
461 * @see #setFocusTraversalKeysEnabled
462 * @see #getFocusTraversalKeysEnabled
463 * @since 1.4
464 */
465 private boolean focusTraversalKeysEnabled = true;
466
467 /**
468 * The locking object for AWT component-tree and layout operations.
469 *
470 * @see #getTreeLock
471 */
472 static final Object LOCK = new AWTTreeLock();
473 static class AWTTreeLock {}
474
475 /*
476 * The component's AccessControlContext.
477 */
478 private transient volatile AccessControlContext acc =
479 AccessController.getContext();
480
481 /**
482 * Minimum size.
483 * (This field perhaps should have been transient).
484 *
485 * @serial
486 */
487 Dimension minSize;
488
489 /**
490 * Whether or not setMinimumSize has been invoked with a non-null value.
491 */
492 boolean minSizeSet;
493
494 /**
495 * Preferred size.
496 * (This field perhaps should have been transient).
497 *
498 * @serial
499 */
500 Dimension prefSize;
501
502 /**
503 * Whether or not setPreferredSize has been invoked with a non-null value.
504 */
505 boolean prefSizeSet;
506
507 /**
508 * Maximum size
509 *
510 * @serial
511 */
512 Dimension maxSize;
513
514 /**
515 * Whether or not setMaximumSize has been invoked with a non-null value.
516 */
517 boolean maxSizeSet;
518
519 /**
520 * The orientation for this component.
521 * @see #getComponentOrientation
522 * @see #setComponentOrientation
523 */
524 transient ComponentOrientation componentOrientation
525 = ComponentOrientation.UNKNOWN;
526
527 /**
528 * <code>newEventsOnly</code> will be true if the event is
529 * one of the event types enabled for the component.
530 * It will then allow for normal processing to
531 * continue. If it is false the event is passed
532 * to the component's parent and up the ancestor
533 * tree until the event has been consumed.
534 *
535 * @serial
536 * @see #dispatchEvent
537 */
538 boolean newEventsOnly = false;
539 transient ComponentListener componentListener;
540 transient FocusListener focusListener;
541 transient HierarchyListener hierarchyListener;
542 transient HierarchyBoundsListener hierarchyBoundsListener;
543 transient KeyListener keyListener;
544 transient MouseListener mouseListener;
545 transient MouseMotionListener mouseMotionListener;
546 transient MouseWheelListener mouseWheelListener;
547 transient InputMethodListener inputMethodListener;
548
549 transient RuntimeException windowClosingException = null;
550
551 /** Internal, constants for serialization */
552 final static String actionListenerK = "actionL";
553 final static String adjustmentListenerK = "adjustmentL";
554 final static String componentListenerK = "componentL";
555 final static String containerListenerK = "containerL";
556 final static String focusListenerK = "focusL";
557 final static String itemListenerK = "itemL";
558 final static String keyListenerK = "keyL";
559 final static String mouseListenerK = "mouseL";
560 final static String mouseMotionListenerK = "mouseMotionL";
561 final static String mouseWheelListenerK = "mouseWheelL";
562 final static String textListenerK = "textL";
563 final static String ownedWindowK = "ownedL";
564 final static String windowListenerK = "windowL";
565 final static String inputMethodListenerK = "inputMethodL";
566 final static String hierarchyListenerK = "hierarchyL";
567 final static String hierarchyBoundsListenerK = "hierarchyBoundsL";
568 final static String windowStateListenerK = "windowStateL";
569 final static String windowFocusListenerK = "windowFocusL";
570
571 /**
572 * The <code>eventMask</code> is ONLY set by subclasses via
573 * <code>enableEvents</code>.
574 * The mask should NOT be set when listeners are registered
575 * so that we can distinguish the difference between when
576 * listeners request events and subclasses request them.
577 * One bit is used to indicate whether input methods are
578 * enabled; this bit is set by <code>enableInputMethods</code> and is
579 * on by default.
580 *
581 * @serial
582 * @see #enableInputMethods
583 * @see AWTEvent
584 */
585 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK;
586
587 /**
588 * Static properties for incremental drawing.
589 * @see #imageUpdate
590 */
591 static boolean isInc;
592 static int incRate;
593 static {
594 /* ensure that the necessary native libraries are loaded */
595 Toolkit.loadLibraries();
596 /* initialize JNI field and method ids */
597 if (!GraphicsEnvironment.isHeadless()) {
598 initIDs();
599 }
600
601 String s = (String) java.security.AccessController.doPrivileged(
602 new GetPropertyAction("awt.image.incrementaldraw"));
603 isInc = (s == null || s.equals("true"));
604
605 s = (String) java.security.AccessController.doPrivileged(
606 new GetPropertyAction("awt.image.redrawrate"));
607 incRate = (s != null) ? Integer.parseInt(s) : 100;
608 }
609
610 /**
611 * Ease-of-use constant for <code>getAlignmentY()</code>.
612 * Specifies an alignment to the top of the component.
613 * @see #getAlignmentY
614 */
615 public static final float TOP_ALIGNMENT = 0.0f;
616
617 /**
618 * Ease-of-use constant for <code>getAlignmentY</code> and
619 * <code>getAlignmentX</code>. Specifies an alignment to
620 * the center of the component
621 * @see #getAlignmentX
622 * @see #getAlignmentY
623 */
624 public static final float CENTER_ALIGNMENT = 0.5f;
625
626 /**
627 * Ease-of-use constant for <code>getAlignmentY</code>.
628 * Specifies an alignment to the bottom of the component.
629 * @see #getAlignmentY
630 */
631 public static final float BOTTOM_ALIGNMENT = 1.0f;
632
633 /**
634 * Ease-of-use constant for <code>getAlignmentX</code>.
635 * Specifies an alignment to the left side of the component.
636 * @see #getAlignmentX
637 */
638 public static final float LEFT_ALIGNMENT = 0.0f;
639
640 /**
641 * Ease-of-use constant for <code>getAlignmentX</code>.
642 * Specifies an alignment to the right side of the component.
643 * @see #getAlignmentX
644 */
645 public static final float RIGHT_ALIGNMENT = 1.0f;
646
647 /*
648 * JDK 1.1 serialVersionUID
649 */
650 private static final long serialVersionUID = -7644114512714619750L;
651
652 /**
653 * If any <code>PropertyChangeListeners</code> have been registered,
654 * the <code>changeSupport</code> field describes them.
655 *
656 * @serial
657 * @since 1.2
658 * @see #addPropertyChangeListener
659 * @see #removePropertyChangeListener
660 * @see #firePropertyChange
661 */
662 private PropertyChangeSupport changeSupport;
663
664 /*
665 * In some cases using "this" as an object to synchronize by
666 * can lead to a deadlock if client code also uses synchronization
667 * by a component object. For every such situation revealed we should
668 * consider possibility of replacing "this" with the package private
669 * objectLock object introduced below. So far there're 2 issues known:
670 * - CR 6708322 (the getName/setName methods);
671 * - CR 6608764 (the PropertyChangeListener machinery).
672 *
673 * Note: this field is considered final, though readObject() prohibits
674 * initializing final fields.
675 */
676 private transient Object objectLock = new Object();
677 Object getObjectLock() {
678 return objectLock;
679 }
680
681 /*
682 * Returns the acc this component was constructed with.
683 */
684 final AccessControlContext getAccessControlContext() {
685 if (acc == null) {
686 throw new SecurityException("Component is missing AccessControlContext");
687 }
688 return acc;
689 }
690
691 boolean isPacked = false;
692
693 /**
694 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize
695 * to signal setBounds what's changing. Should be used under TreeLock.
696 * This is only needed due to the inability to change the cross-calling
697 * order of public and deprecated methods.
698 */
699 private int boundsOp = ComponentPeer.DEFAULT_OPERATION;
700
701 /**
702 * Enumeration of the common ways the baseline of a component can
703 * change as the size changes. The baseline resize behavior is
704 * primarily for layout managers that need to know how the
705 * position of the baseline changes as the component size changes.
706 * In general the baseline resize behavior will be valid for sizes
707 * greater than or equal to the minimum size (the actual minimum
708 * size; not a developer specified minimum size). For sizes
709 * smaller than the minimum size the baseline may change in a way
710 * other than the baseline resize behavior indicates. Similarly,
711 * as the size approaches <code>Integer.MAX_VALUE</code> and/or
712 * <code>Short.MAX_VALUE</code> the baseline may change in a way
713 * other than the baseline resize behavior indicates.
714 *
715 * @see #getBaselineResizeBehavior
716 * @see #getBaseline(int,int)
717 * @since 1.6
718 */
719 public enum BaselineResizeBehavior {
720 /**
721 * Indicates the baseline remains fixed relative to the
722 * y-origin. That is, <code>getBaseline</code> returns
723 * the same value regardless of the height or width. For example, a
724 * <code>JLabel</code> containing non-empty text with a
725 * vertical alignment of <code>TOP</code> should have a
726 * baseline type of <code>CONSTANT_ASCENT</code>.
727 */
728 CONSTANT_ASCENT,
729
730 /**
731 * Indicates the baseline remains fixed relative to the height
732 * and does not change as the width is varied. That is, for
733 * any height H the difference between H and
734 * <code>getBaseline(w, H)</code> is the same. For example, a
735 * <code>JLabel</code> containing non-empty text with a
736 * vertical alignment of <code>BOTTOM</code> should have a
737 * baseline type of <code>CONSTANT_DESCENT</code>.
738 */
739 CONSTANT_DESCENT,
740
741 /**
742 * Indicates the baseline remains a fixed distance from
743 * the center of the component. That is, for any height H the
744 * difference between <code>getBaseline(w, H)</code> and
745 * <code>H / 2</code> is the same (plus or minus one depending upon
746 * rounding error).
747 * <p>
748 * Because of possible rounding errors it is recommended
749 * you ask for the baseline with two consecutive heights and use
750 * the return value to determine if you need to pad calculations
751 * by 1. The following shows how to calculate the baseline for
752 * any height:
753 * <pre>
754 * Dimension preferredSize = component.getPreferredSize();
755 * int baseline = getBaseline(preferredSize.width,
756 * preferredSize.height);
757 * int nextBaseline = getBaseline(preferredSize.width,
758 * preferredSize.height + 1);
759 * // Amount to add to height when calculating where baseline
760 * // lands for a particular height:
761 * int padding = 0;
762 * // Where the baseline is relative to the mid point
763 * int baselineOffset = baseline - height / 2;
764 * if (preferredSize.height % 2 == 0 &amp;&amp;
765 * baseline != nextBaseline) {
766 * padding = 1;
767 * }
768 * else if (preferredSize.height % 2 == 1 &amp;&amp;
769 * baseline == nextBaseline) {
770 * baselineOffset--;
771 * padding = 1;
772 * }
773 * // The following calculates where the baseline lands for
774 * // the height z:
775 * int calculatedBaseline = (z + padding) / 2 + baselineOffset;
776 * </pre>
777 */
778 CENTER_OFFSET,
779
780 /**
781 * Indicates the baseline resize behavior can not be expressed using
782 * any of the other constants. This may also indicate the baseline
783 * varies with the width of the component. This is also returned
784 * by components that do not have a baseline.
785 */
786 OTHER
787 }
788
789 /*
790 * The shape set with the applyCompoundShape() method. It uncludes the result
791 * of the HW/LW mixing related shape computation. It may also include
792 * the user-specified shape of the component.
793 * The 'null' value means the component has normal shape (or has no shape at all)
794 * and applyCompoundShape() will skip the following shape identical to normal.
795 */
796 private transient Region compoundShape = null;
797
798 /*
799 * Represents the shape of this lightweight component to be cut out from
800 * heavyweight components should they intersect. Possible values:
801 * 1. null - consider the shape rectangular
802 * 2. EMPTY_REGION - nothing gets cut out (children still get cut out)
803 * 3. non-empty - this shape gets cut out.
804 */
805 private transient Region mixingCutoutRegion = null;
806
807 /*
808 * Indicates whether addNotify() is complete
809 * (i.e. the peer is created).
810 */
811 private transient boolean isAddNotifyComplete = false;
812
813 /**
814 * Should only be used in subclass getBounds to check that part of bounds
815 * is actualy changing
816 */
817 int getBoundsOp() {
818 assert Thread.holdsLock(getTreeLock());
819 return boundsOp;
820 }
821
822 void setBoundsOp(int op) {
823 assert Thread.holdsLock(getTreeLock());
824 if (op == ComponentPeer.RESET_OPERATION) {
825 boundsOp = ComponentPeer.DEFAULT_OPERATION;
826 } else
827 if (boundsOp == ComponentPeer.DEFAULT_OPERATION) {
828 boundsOp = op;
829 }
830 }
831
832 // Whether this Component has had the background erase flag
833 // specified via SunToolkit.disableBackgroundErase(). This is
834 // needed in order to make this function work on X11 platforms,
835 // where currently there is no chance to interpose on the creation
836 // of the peer and therefore the call to XSetBackground.
837 transient boolean backgroundEraseDisabled;
838
839 static {
840 AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() {
841 public void setBackgroundEraseDisabled(Component comp, boolean disabled) {
842 comp.backgroundEraseDisabled = disabled;
843 }
844 public boolean getBackgroundEraseDisabled(Component comp) {
845 return comp.backgroundEraseDisabled;
846 }
847 public Rectangle getBounds(Component comp) {
848 return new Rectangle(comp.x, comp.y, comp.width, comp.height);
849 }
850 public void setMixingCutoutShape(Component comp, Shape shape) {
851 Region region = shape == null ? null :
852 Region.getInstance(shape, null);
853
854 synchronized (comp.getTreeLock()) {
855 boolean needShowing = false;
856 boolean needHiding = false;
857
858 if (!comp.isNonOpaqueForMixing()) {
859 needHiding = true;
860 }
861
862 comp.mixingCutoutRegion = region;
863
864 if (!comp.isNonOpaqueForMixing()) {
865 needShowing = true;
866 }
867
868 if (comp.isMixingNeeded()) {
869 if (needHiding) {
870 comp.mixOnHiding(comp.isLightweight());
871 }
872 if (needShowing) {
873 comp.mixOnShowing();
874 }
875 }
876 }
877 }
878
879 public void setGraphicsConfiguration(Component comp,
880 GraphicsConfiguration gc)
881 {
882 comp.setGraphicsConfiguration(gc);
883 }
884 public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) {
885 return comp.requestFocus(cause);
886 }
887 public boolean canBeFocusOwner(Component comp) {
888 return comp.canBeFocusOwner();
889 }
890
891 public boolean isVisible(Component comp) {
892 return comp.isVisible_NoClientCode();
893 }
894 public void setRequestFocusController
895 (RequestFocusController requestController)
896 {
897 Component.setRequestFocusController(requestController);
898 }
899 public AppContext getAppContext(Component comp) {
900 return comp.appContext;
901 }
902 public void setAppContext(Component comp, AppContext appContext) {
903 comp.appContext = appContext;
904 }
905 public Container getParent(Component comp) {
906 return comp.getParent_NoClientCode();
907 }
908 public void setParent(Component comp, Container parent) {
909 comp.parent = parent;
910 }
911 public void setSize(Component comp, int width, int height) {
912 comp.width = width;
913 comp.height = height;
914 }
915 public Point getLocation(Component comp) {
916 return comp.location_NoClientCode();
917 }
918 public void setLocation(Component comp, int x, int y) {
919 comp.x = x;
920 comp.y = y;
921 }
922 public boolean isEnabled(Component comp) {
923 return comp.isEnabledImpl();
924 }
925 public boolean isDisplayable(Component comp) {
926 return comp.peer != null;
927 }
928 public Cursor getCursor(Component comp) {
929 return comp.getCursor_NoClientCode();
930 }
931 public ComponentPeer getPeer(Component comp) {
932 return comp.peer;
933 }
934 public void setPeer(Component comp, ComponentPeer peer) {
935 comp.peer = peer;
936 }
937 public boolean isLightweight(Component comp) {
938 return (comp.peer instanceof LightweightPeer);
939 }
940 public boolean getIgnoreRepaint(Component comp) {
941 return comp.ignoreRepaint;
942 }
943 public int getWidth(Component comp) {
944 return comp.width;
945 }
946 public int getHeight(Component comp) {
947 return comp.height;
948 }
949 public int getX(Component comp) {
950 return comp.x;
951 }
952 public int getY(Component comp) {
953 return comp.y;
954 }
955 public Color getForeground(Component comp) {
956 return comp.foreground;
957 }
958 public Color getBackground(Component comp) {
959 return comp.background;
960 }
961 public void setBackground(Component comp, Color background) {
962 comp.background = background;
963 }
964 public Font getFont(Component comp) {
965 return comp.getFont_NoClientCode();
966 }
967 public void processEvent(Component comp, AWTEvent e) {
968 comp.processEvent(e);
969 }
970
971 public AccessControlContext getAccessControlContext(Component comp) {
972 return comp.getAccessControlContext();
973 }
974 });
975 }
976
977 /**
978 * Constructs a new component. Class <code>Component</code> can be
979 * extended directly to create a lightweight component that does not
980 * utilize an opaque native window. A lightweight component must be
981 * hosted by a native container somewhere higher up in the component
982 * tree (for example, by a <code>Frame</code> object).
983 */
984 protected Component() {
985 appContext = AppContext.getAppContext();
986 }
987
988 void initializeFocusTraversalKeys() {
989 focusTraversalKeys = new Set[3];
990 }
991
992 /**
993 * Constructs a name for this component. Called by <code>getName</code>
994 * when the name is <code>null</code>.
995 */
996 String constructComponentName() {
997 return null; // For strict compliance with prior platform versions, a Component
998 // that doesn't set its name should return null from
999 // getName()
1000 }
1001
1002 /**
1003 * Gets the name of the component.
1004 * @return this component's name
1005 * @see #setName
1006 * @since JDK1.1
1007 */
1008 public String getName() {
1009 if (name == null && !nameExplicitlySet) {
1010 synchronized(getObjectLock()) {
1011 if (name == null && !nameExplicitlySet)
1012 name = constructComponentName();
1013 }
1014 }
1015 return name;
1016 }
1017
1018 /**
1019 * Sets the name of the component to the specified string.
1020 * @param name the string that is to be this
1021 * component's name
1022 * @see #getName
1023 * @since JDK1.1
1024 */
1025 public void setName(String name) {
1026 String oldName;
1027 synchronized(getObjectLock()) {
1028 oldName = this.name;
1029 this.name = name;
1030 nameExplicitlySet = true;
1031 }
1032 firePropertyChange("name", oldName, name);
1033 }
1034
1035 /**
1036 * Gets the parent of this component.
1037 * @return the parent container of this component
1038 * @since JDK1.0
1039 */
1040 public Container getParent() {
1041 return getParent_NoClientCode();
1042 }
1043
1044 // NOTE: This method may be called by privileged threads.
1045 // This functionality is implemented in a package-private method
1046 // to insure that it cannot be overridden by client subclasses.
1047 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1048 final Container getParent_NoClientCode() {
1049 return parent;
1050 }
1051
1052 // This method is overriden in the Window class to return null,
1053 // because the parent field of the Window object contains
1054 // the owner of the window, not its parent.
1055 Container getContainer() {
1056 return getParent();
1057 }
1058
1059 /**
1060 * @deprecated As of JDK version 1.1,
1061 * programs should not directly manipulate peers;
1062 * replaced by <code>boolean isDisplayable()</code>.
1063 */
1064 @Deprecated
1065 public ComponentPeer getPeer() {
1066 return peer;
1067 }
1068
1069 /**
1070 * Associate a <code>DropTarget</code> with this component.
1071 * The <code>Component</code> will receive drops only if it
1072 * is enabled.
1073 *
1074 * @see #isEnabled
1075 * @param dt The DropTarget
1076 */
1077
1078 public synchronized void setDropTarget(DropTarget dt) {
1079 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt)))
1080 return;
1081
1082 DropTarget old;
1083
1084 if ((old = dropTarget) != null) {
1085 if (peer != null) dropTarget.removeNotify(peer);
1086
1087 DropTarget t = dropTarget;
1088
1089 dropTarget = null;
1090
1091 try {
1092 t.setComponent(null);
1093 } catch (IllegalArgumentException iae) {
1094 // ignore it.
1095 }
1096 }
1097
1098 // if we have a new one, and we have a peer, add it!
1099
1100 if ((dropTarget = dt) != null) {
1101 try {
1102 dropTarget.setComponent(this);
1103 if (peer != null) dropTarget.addNotify(peer);
1104 } catch (IllegalArgumentException iae) {
1105 if (old != null) {
1106 try {
1107 old.setComponent(this);
1108 if (peer != null) dropTarget.addNotify(peer);
1109 } catch (IllegalArgumentException iae1) {
1110 // ignore it!
1111 }
1112 }
1113 }
1114 }
1115 }
1116
1117 /**
1118 * Gets the <code>DropTarget</code> associated with this
1119 * <code>Component</code>.
1120 */
1121
1122 public synchronized DropTarget getDropTarget() { return dropTarget; }
1123
1124 /**
1125 * Gets the <code>GraphicsConfiguration</code> associated with this
1126 * <code>Component</code>.
1127 * If the <code>Component</code> has not been assigned a specific
1128 * <code>GraphicsConfiguration</code>,
1129 * the <code>GraphicsConfiguration</code> of the
1130 * <code>Component</code> object's top-level container is
1131 * returned.
1132 * If the <code>Component</code> has been created, but not yet added
1133 * to a <code>Container</code>, this method returns <code>null</code>.
1134 *
1135 * @return the <code>GraphicsConfiguration</code> used by this
1136 * <code>Component</code> or <code>null</code>
1137 * @since 1.3
1138 */
1139 public GraphicsConfiguration getGraphicsConfiguration() {
1140 synchronized(getTreeLock()) {
1141 return getGraphicsConfiguration_NoClientCode();
1142 }
1143 }
1144
1145 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() {
1146 return graphicsConfig;
1147 }
1148
1149 void setGraphicsConfiguration(GraphicsConfiguration gc) {
1150 synchronized(getTreeLock()) {
1151 if (updateGraphicsData(gc)) {
1152 removeNotify();
1153 addNotify();
1154 }
1155 }
1156 }
1157
1158 boolean updateGraphicsData(GraphicsConfiguration gc) {
1159 checkTreeLock();
1160
1161 graphicsConfig = gc;
1162
1163 ComponentPeer peer = getPeer();
1164 if (peer != null) {
1165 return peer.updateGraphicsData(gc);
1166 }
1167 return false;
1168 }
1169
1170 /**
1171 * Checks that this component's <code>GraphicsDevice</code>
1172 * <code>idString</code> matches the string argument.
1173 */
1174 void checkGD(String stringID) {
1175 if (graphicsConfig != null) {
1176 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) {
1177 throw new IllegalArgumentException(
1178 "adding a container to a container on a different GraphicsDevice");
1179 }
1180 }
1181 }
1182
1183 /**
1184 * Gets this component's locking object (the object that owns the thread
1185 * synchronization monitor) for AWT component-tree and layout
1186 * operations.
1187 * @return this component's locking object
1188 */
1189 public final Object getTreeLock() {
1190 return LOCK;
1191 }
1192
1193 final void checkTreeLock() {
1194 if (!Thread.holdsLock(getTreeLock())) {
1195 throw new IllegalStateException("This function should be called while holding treeLock");
1196 }
1197 }
1198
1199 /**
1200 * Gets the toolkit of this component. Note that
1201 * the frame that contains a component controls which
1202 * toolkit is used by that component. Therefore if the component
1203 * is moved from one frame to another, the toolkit it uses may change.
1204 * @return the toolkit of this component
1205 * @since JDK1.0
1206 */
1207 public Toolkit getToolkit() {
1208 return getToolkitImpl();
1209 }
1210
1211 /*
1212 * This is called by the native code, so client code can't
1213 * be called on the toolkit thread.
1214 */
1215 final Toolkit getToolkitImpl() {
1216 ComponentPeer peer = this.peer;
1217 if ((peer != null) && ! (peer instanceof LightweightPeer)){
1218 return peer.getToolkit();
1219 }
1220 Container parent = this.parent;
1221 if (parent != null) {
1222 return parent.getToolkitImpl();
1223 }
1224 return Toolkit.getDefaultToolkit();
1225 }
1226
1227 /**
1228 * Determines whether this component is valid. A component is valid
1229 * when it is correctly sized and positioned within its parent
1230 * container and all its children are also valid.
1231 * In order to account for peers' size requirements, components are invalidated
1232 * before they are first shown on the screen. By the time the parent container
1233 * is fully realized, all its components will be valid.
1234 * @return <code>true</code> if the component is valid, <code>false</code>
1235 * otherwise
1236 * @see #validate
1237 * @see #invalidate
1238 * @since JDK1.0
1239 */
1240 public boolean isValid() {
1241 return (peer != null) && valid;
1242 }
1243
1244 /**
1245 * Determines whether this component is displayable. A component is
1246 * displayable when it is connected to a native screen resource.
1247 * <p>
1248 * A component is made displayable either when it is added to
1249 * a displayable containment hierarchy or when its containment
1250 * hierarchy is made displayable.
1251 * A containment hierarchy is made displayable when its ancestor
1252 * window is either packed or made visible.
1253 * <p>
1254 * A component is made undisplayable either when it is removed from
1255 * a displayable containment hierarchy or when its containment hierarchy
1256 * is made undisplayable. A containment hierarchy is made
1257 * undisplayable when its ancestor window is disposed.
1258 *
1259 * @return <code>true</code> if the component is displayable,
1260 * <code>false</code> otherwise
1261 * @see Container#add(Component)
1262 * @see Window#pack
1263 * @see Window#show
1264 * @see Container#remove(Component)
1265 * @see Window#dispose
1266 * @since 1.2
1267 */
1268 public boolean isDisplayable() {
1269 return getPeer() != null;
1270 }
1271
1272 /**
1273 * Determines whether this component should be visible when its
1274 * parent is visible. Components are
1275 * initially visible, with the exception of top level components such
1276 * as <code>Frame</code> objects.
1277 * @return <code>true</code> if the component is visible,
1278 * <code>false</code> otherwise
1279 * @see #setVisible
1280 * @since JDK1.0
1281 */
1282 @Transient
1283 public boolean isVisible() {
1284 return isVisible_NoClientCode();
1285 }
1286 final boolean isVisible_NoClientCode() {
1287 return visible;
1288 }
1289
1290 /**
1291 * Determines whether this component will be displayed on the screen.
1292 * @return <code>true</code> if the component and all of its ancestors
1293 * until a toplevel window or null parent are visible,
1294 * <code>false</code> otherwise
1295 */
1296 boolean isRecursivelyVisible() {
1297 return visible && (parent == null || parent.isRecursivelyVisible());
1298 }
1299
1300 /**
1301 * Translates absolute coordinates into coordinates in the coordinate
1302 * space of this component.
1303 */
1304 Point pointRelativeToComponent(Point absolute) {
1305 Point compCoords = getLocationOnScreen();
1306 return new Point(absolute.x - compCoords.x,
1307 absolute.y - compCoords.y);
1308 }
1309
1310 /**
1311 * Assuming that mouse location is stored in PointerInfo passed
1312 * to this method, it finds a Component that is in the same
1313 * Window as this Component and is located under the mouse pointer.
1314 * If no such Component exists, null is returned.
1315 * NOTE: this method should be called under the protection of
1316 * tree lock, as it is done in Component.getMousePosition() and
1317 * Container.getMousePosition(boolean).
1318 */
1319 Component findUnderMouseInWindow(PointerInfo pi) {
1320 if (!isShowing()) {
1321 return null;
1322 }
1323 Window win = getContainingWindow();
1324 if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) {
1325 return null;
1326 }
1327 final boolean INCLUDE_DISABLED = true;
1328 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation());
1329 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x,
1330 relativeToWindow.y,
1331 INCLUDE_DISABLED);
1332 return inTheSameWindow;
1333 }
1334
1335 /**
1336 * Returns the position of the mouse pointer in this <code>Component</code>'s
1337 * coordinate space if the <code>Component</code> is directly under the mouse
1338 * pointer, otherwise returns <code>null</code>.
1339 * If the <code>Component</code> is not showing on the screen, this method
1340 * returns <code>null</code> even if the mouse pointer is above the area
1341 * where the <code>Component</code> would be displayed.
1342 * If the <code>Component</code> is partially or fully obscured by other
1343 * <code>Component</code>s or native windows, this method returns a non-null
1344 * value only if the mouse pointer is located above the unobscured part of the
1345 * <code>Component</code>.
1346 * <p>
1347 * For <code>Container</code>s it returns a non-null value if the mouse is
1348 * above the <code>Container</code> itself or above any of its descendants.
1349 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children.
1350 * <p>
1351 * Sometimes the exact mouse coordinates are not important, and the only thing
1352 * that matters is whether a specific <code>Component</code> is under the mouse
1353 * pointer. If the return value of this method is <code>null</code>, mouse
1354 * pointer is not directly above the <code>Component</code>.
1355 *
1356 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true
1357 * @see #isShowing
1358 * @see Container#getMousePosition
1359 * @return mouse coordinates relative to this <code>Component</code>, or null
1360 * @since 1.5
1361 */
1362 public Point getMousePosition() throws HeadlessException {
1363 if (GraphicsEnvironment.isHeadless()) {
1364 throw new HeadlessException();
1365 }
1366
1367 PointerInfo pi = (PointerInfo)java.security.AccessController.doPrivileged(
1368 new java.security.PrivilegedAction() {
1369 public Object run() {
1370 return MouseInfo.getPointerInfo();
1371 }
1372 }
1373 );
1374
1375 synchronized (getTreeLock()) {
1376 Component inTheSameWindow = findUnderMouseInWindow(pi);
1377 if (!isSameOrAncestorOf(inTheSameWindow, true)) {
1378 return null;
1379 }
1380 return pointRelativeToComponent(pi.getLocation());
1381 }
1382 }
1383
1384 /**
1385 * Overridden in Container. Must be called under TreeLock.
1386 */
1387 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) {
1388 return comp == this;
1389 }
1390
1391 /**
1392 * Determines whether this component is showing on screen. This means
1393 * that the component must be visible, and it must be in a container
1394 * that is visible and showing.
1395 * <p>
1396 * <strong>Note:</strong> sometimes there is no way to detect whether the
1397 * {@code Component} is actually visible to the user. This can happen when:
1398 * <ul>
1399 * <li>the component has been added to a visible {@code ScrollPane} but
1400 * the {@code Component} is not currently in the scroll pane's view port.
1401 * <li>the {@code Component} is obscured by another {@code Component} or
1402 * {@code Container}.
1403 * </ul>
1404 * @return <code>true</code> if the component is showing,
1405 * <code>false</code> otherwise
1406 * @see #setVisible
1407 * @since JDK1.0
1408 */
1409 public boolean isShowing() {
1410 if (visible && (peer != null)) {
1411 Container parent = this.parent;
1412 return (parent == null) || parent.isShowing();
1413 }
1414 return false;
1415 }
1416
1417 /**
1418 * Determines whether this component is enabled. An enabled component
1419 * can respond to user input and generate events. Components are
1420 * enabled initially by default. A component may be enabled or disabled by
1421 * calling its <code>setEnabled</code> method.
1422 * @return <code>true</code> if the component is enabled,
1423 * <code>false</code> otherwise
1424 * @see #setEnabled
1425 * @since JDK1.0
1426 */
1427 public boolean isEnabled() {
1428 return isEnabledImpl();
1429 }
1430
1431 /*
1432 * This is called by the native code, so client code can't
1433 * be called on the toolkit thread.
1434 */
1435 final boolean isEnabledImpl() {
1436 return enabled;
1437 }
1438
1439 /**
1440 * Enables or disables this component, depending on the value of the
1441 * parameter <code>b</code>. An enabled component can respond to user
1442 * input and generate events. Components are enabled initially by default.
1443 *
1444 * <p>Note: Disabling a lightweight component does not prevent it from
1445 * receiving MouseEvents.
1446 * <p>Note: Disabling a heavyweight container prevents all components
1447 * in this container from receiving any input events. But disabling a
1448 * lightweight container affects only this container.
1449 *
1450 * @param b If <code>true</code>, this component is
1451 * enabled; otherwise this component is disabled
1452 * @see #isEnabled
1453 * @see #isLightweight
1454 * @since JDK1.1
1455 */
1456 public void setEnabled(boolean b) {
1457 enable(b);
1458 }
1459
1460 /**
1461 * @deprecated As of JDK version 1.1,
1462 * replaced by <code>setEnabled(boolean)</code>.
1463 */
1464 @Deprecated
1465 public void enable() {
1466 if (!enabled) {
1467 synchronized (getTreeLock()) {
1468 enabled = true;
1469 ComponentPeer peer = this.peer;
1470 if (peer != null) {
1471 peer.setEnabled(true);
1472 if (visible) {
1473 updateCursorImmediately();
1474 }
1475 }
1476 }
1477 if (accessibleContext != null) {
1478 accessibleContext.firePropertyChange(
1479 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1480 null, AccessibleState.ENABLED);
1481 }
1482 }
1483 }
1484
1485 /**
1486 * @deprecated As of JDK version 1.1,
1487 * replaced by <code>setEnabled(boolean)</code>.
1488 */
1489 @Deprecated
1490 public void enable(boolean b) {
1491 if (b) {
1492 enable();
1493 } else {
1494 disable();
1495 }
1496 }
1497
1498 /**
1499 * @deprecated As of JDK version 1.1,
1500 * replaced by <code>setEnabled(boolean)</code>.
1501 */
1502 @Deprecated
1503 public void disable() {
1504 if (enabled) {
1505 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1506 synchronized (getTreeLock()) {
1507 enabled = false;
1508 // A disabled lw container is allowed to contain a focus owner.
1509 if ((isFocusOwner() || (containsFocus() && !isLightweight())) &&
1510 KeyboardFocusManager.isAutoFocusTransferEnabled())
1511 {
1512 // Don't clear the global focus owner. If transferFocus
1513 // fails, we want the focus to stay on the disabled
1514 // Component so that keyboard traversal, et. al. still
1515 // makes sense to the user.
1516 transferFocus(false);
1517 }
1518 ComponentPeer peer = this.peer;
1519 if (peer != null) {
1520 peer.setEnabled(false);
1521 if (visible) {
1522 updateCursorImmediately();
1523 }
1524 }
1525 }
1526 if (accessibleContext != null) {
1527 accessibleContext.firePropertyChange(
1528 AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
1529 null, AccessibleState.ENABLED);
1530 }
1531 }
1532 }
1533
1534 /**
1535 * Returns true if this component is painted to an offscreen image
1536 * ("buffer") that's copied to the screen later. Component
1537 * subclasses that support double buffering should override this
1538 * method to return true if double buffering is enabled.
1539 *
1540 * @return false by default
1541 */
1542 public boolean isDoubleBuffered() {
1543 return false;
1544 }
1545
1546 /**
1547 * Enables or disables input method support for this component. If input
1548 * method support is enabled and the component also processes key events,
1549 * incoming events are offered to
1550 * the current input method and will only be processed by the component or
1551 * dispatched to its listeners if the input method does not consume them.
1552 * By default, input method support is enabled.
1553 *
1554 * @param enable true to enable, false to disable
1555 * @see #processKeyEvent
1556 * @since 1.2
1557 */
1558 public void enableInputMethods(boolean enable) {
1559 if (enable) {
1560 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0)
1561 return;
1562
1563 // If this component already has focus, then activate the
1564 // input method by dispatching a synthesized focus gained
1565 // event.
1566 if (isFocusOwner()) {
1567 InputContext inputContext = getInputContext();
1568 if (inputContext != null) {
1569 FocusEvent focusGainedEvent =
1570 new FocusEvent(this, FocusEvent.FOCUS_GAINED);
1571 inputContext.dispatchEvent(focusGainedEvent);
1572 }
1573 }
1574
1575 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK;
1576 } else {
1577 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) {
1578 InputContext inputContext = getInputContext();
1579 if (inputContext != null) {
1580 inputContext.endComposition();
1581 inputContext.removeNotify(this);
1582 }
1583 }
1584 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK;
1585 }
1586 }
1587
1588 /**
1589 * Shows or hides this component depending on the value of parameter
1590 * <code>b</code>.
1591 * <p>
1592 * This method changes layout-related information, and therefore,
1593 * invalidates the component hierarchy.
1594 *
1595 * @param b if <code>true</code>, shows this component;
1596 * otherwise, hides this component
1597 * @see #isVisible
1598 * @see #invalidate
1599 * @since JDK1.1
1600 */
1601 public void setVisible(boolean b) {
1602 show(b);
1603 }
1604
1605 /**
1606 * @deprecated As of JDK version 1.1,
1607 * replaced by <code>setVisible(boolean)</code>.
1608 */
1609 @Deprecated
1610 public void show() {
1611 if (!visible) {
1612 synchronized (getTreeLock()) {
1613 visible = true;
1614 mixOnShowing();
1615 ComponentPeer peer = this.peer;
1616 if (peer != null) {
1617 peer.setVisible(true);
1618 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1619 this, parent,
1620 HierarchyEvent.SHOWING_CHANGED,
1621 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1622 if (peer instanceof LightweightPeer) {
1623 repaint();
1624 }
1625 updateCursorImmediately();
1626 }
1627
1628 if (componentListener != null ||
1629 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1630 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1631 ComponentEvent e = new ComponentEvent(this,
1632 ComponentEvent.COMPONENT_SHOWN);
1633 Toolkit.getEventQueue().postEvent(e);
1634 }
1635 }
1636 Container parent = this.parent;
1637 if (parent != null) {
1638 parent.invalidate();
1639 }
1640 }
1641 }
1642
1643 /**
1644 * @deprecated As of JDK version 1.1,
1645 * replaced by <code>setVisible(boolean)</code>.
1646 */
1647 @Deprecated
1648 public void show(boolean b) {
1649 if (b) {
1650 show();
1651 } else {
1652 hide();
1653 }
1654 }
1655
1656 boolean containsFocus() {
1657 return isFocusOwner();
1658 }
1659
1660 void clearMostRecentFocusOwnerOnHide() {
1661 KeyboardFocusManager.clearMostRecentFocusOwner(this);
1662 }
1663
1664 void clearCurrentFocusCycleRootOnHide() {
1665 /* do nothing */
1666 }
1667
1668 /**
1669 * @deprecated As of JDK version 1.1,
1670 * replaced by <code>setVisible(boolean)</code>.
1671 */
1672 @Deprecated
1673 public void hide() {
1674 isPacked = false;
1675
1676 if (visible) {
1677 clearCurrentFocusCycleRootOnHide();
1678 clearMostRecentFocusOwnerOnHide();
1679 synchronized (getTreeLock()) {
1680 visible = false;
1681 mixOnHiding(isLightweight());
1682 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) {
1683 transferFocus(true);
1684 }
1685 ComponentPeer peer = this.peer;
1686 if (peer != null) {
1687 peer.setVisible(false);
1688 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED,
1689 this, parent,
1690 HierarchyEvent.SHOWING_CHANGED,
1691 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK));
1692 if (peer instanceof LightweightPeer) {
1693 repaint();
1694 }
1695 updateCursorImmediately();
1696 }
1697 if (componentListener != null ||
1698 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 ||
1699 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) {
1700 ComponentEvent e = new ComponentEvent(this,
1701 ComponentEvent.COMPONENT_HIDDEN);
1702 Toolkit.getEventQueue().postEvent(e);
1703 }
1704 }
1705 Container parent = this.parent;
1706 if (parent != null) {
1707 parent.invalidate();
1708 }
1709 }
1710 }
1711
1712 /**
1713 * Gets the foreground color of this component.
1714 * @return this component's foreground color; if this component does
1715 * not have a foreground color, the foreground color of its parent
1716 * is returned
1717 * @see #setForeground
1718 * @since JDK1.0
1719 * @beaninfo
1720 * bound: true
1721 */
1722 @Transient
1723 public Color getForeground() {
1724 Color foreground = this.foreground;
1725 if (foreground != null) {
1726 return foreground;
1727 }
1728 Container parent = this.parent;
1729 return (parent != null) ? parent.getForeground() : null;
1730 }
1731
1732 /**
1733 * Sets the foreground color of this component.
1734 * @param c the color to become this component's
1735 * foreground color; if this parameter is <code>null</code>
1736 * then this component will inherit
1737 * the foreground color of its parent
1738 * @see #getForeground
1739 * @since JDK1.0
1740 */
1741 public void setForeground(Color c) {
1742 Color oldColor = foreground;
1743 ComponentPeer peer = this.peer;
1744 foreground = c;
1745 if (peer != null) {
1746 c = getForeground();
1747 if (c != null) {
1748 peer.setForeground(c);
1749 }
1750 }
1751 // This is a bound property, so report the change to
1752 // any registered listeners. (Cheap if there are none.)
1753 firePropertyChange("foreground", oldColor, c);
1754 }
1755
1756 /**
1757 * Returns whether the foreground color has been explicitly set for this
1758 * Component. If this method returns <code>false</code>, this Component is
1759 * inheriting its foreground color from an ancestor.
1760 *
1761 * @return <code>true</code> if the foreground color has been explicitly
1762 * set for this Component; <code>false</code> otherwise.
1763 * @since 1.4
1764 */
1765 public boolean isForegroundSet() {
1766 return (foreground != null);
1767 }
1768
1769 /**
1770 * Gets the background color of this component.
1771 * @return this component's background color; if this component does
1772 * not have a background color,
1773 * the background color of its parent is returned
1774 * @see #setBackground
1775 * @since JDK1.0
1776 */
1777 @Transient
1778 public Color getBackground() {
1779 Color background = this.background;
1780 if (background != null) {
1781 return background;
1782 }
1783 Container parent = this.parent;
1784 return (parent != null) ? parent.getBackground() : null;
1785 }
1786
1787 /**
1788 * Sets the background color of this component.
1789 * <p>
1790 * The background color affects each component differently and the
1791 * parts of the component that are affected by the background color
1792 * may differ between operating systems.
1793 *
1794 * @param c the color to become this component's color;
1795 * if this parameter is <code>null</code>, then this
1796 * component will inherit the background color of its parent
1797 * @see #getBackground
1798 * @since JDK1.0
1799 * @beaninfo
1800 * bound: true
1801 */
1802 public void setBackground(Color c) {
1803 Color oldColor = background;
1804 ComponentPeer peer = this.peer;
1805 background = c;
1806 if (peer != null) {
1807 c = getBackground();
1808 if (c != null) {
1809 peer.setBackground(c);
1810 }
1811 }
1812 // This is a bound property, so report the change to
1813 // any registered listeners. (Cheap if there are none.)
1814 firePropertyChange("background", oldColor, c);
1815 }
1816
1817 /**
1818 * Returns whether the background color has been explicitly set for this
1819 * Component. If this method returns <code>false</code>, this Component is
1820 * inheriting its background color from an ancestor.
1821 *
1822 * @return <code>true</code> if the background color has been explicitly
1823 * set for this Component; <code>false</code> otherwise.
1824 * @since 1.4
1825 */
1826 public boolean isBackgroundSet() {
1827 return (background != null);
1828 }
1829
1830 /**
1831 * Gets the font of this component.
1832 * @return this component's font; if a font has not been set
1833 * for this component, the font of its parent is returned
1834 * @see #setFont
1835 * @since JDK1.0
1836 */
1837 @Transient
1838 public Font getFont() {
1839 return getFont_NoClientCode();
1840 }
1841
1842 // NOTE: This method may be called by privileged threads.
1843 // This functionality is implemented in a package-private method
1844 // to insure that it cannot be overridden by client subclasses.
1845 // DO NOT INVOKE CLIENT CODE ON THIS THREAD!
1846 final Font getFont_NoClientCode() {
1847 Font font = this.font;
1848 if (font != null) {
1849 return font;
1850 }
1851 Container parent = this.parent;
1852 return (parent != null) ? parent.getFont_NoClientCode() : null;
1853 }
1854
1855 /**
1856 * Sets the font of this component.
1857 * <p>
1858 * This method changes layout-related information, and therefore,
1859 * invalidates the component hierarchy.
1860 *
1861 * @param f the font to become this component's font;
1862 * if this parameter is <code>null</code> then this
1863 * component will inherit the font of its parent
1864 * @see #getFont
1865 * @see #invalidate
1866 * @since JDK1.0
1867 * @beaninfo
1868 * bound: true
1869 */
1870 public void setFont(Font f) {
1871 Font oldFont, newFont;
1872 synchronized(getTreeLock()) {
1873 synchronized (this) {
1874 oldFont = font;
1875 newFont = font = f;
1876 }
1877 ComponentPeer peer = this.peer;
1878 if (peer != null) {
1879 f = getFont();
1880 if (f != null) {
1881 peer.setFont(f);
1882 peerFont = f;
1883 }
1884 }
1885 }
1886 // This is a bound property, so report the change to
1887 // any registered listeners. (Cheap if there are none.)
1888 firePropertyChange("font", oldFont, newFont);
1889
1890 // This could change the preferred size of the Component.
1891 // Fix for 6213660. Should compare old and new fonts and do not
1892 // call invalidate() if they are equal.
1893 if (f != oldFont && (oldFont == null ||
1894 !oldFont.equals(f))) {
1895 invalidateIfValid();
1896 }
1897 }
1898
1899 /**
1900 * Returns whether the font has been explicitly set for this Component. If
1901 * this method returns <code>false</code>, this Component is inheriting its
1902 * font from an ancestor.
1903 *
1904 * @return <code>true</code> if the font has been explicitly set for this
1905 * Component; <code>false</code> otherwise.
1906 * @since 1.4
1907 */
1908 public boolean isFontSet() {
1909 return (font != null);
1910 }
1911
1912 /**
1913 * Gets the locale of this component.
1914 * @return this component's locale; if this component does not
1915 * have a locale, the locale of its parent is returned
1916 * @see #setLocale
1917 * @exception IllegalComponentStateException if the <code>Component</code>
1918 * does not have its own locale and has not yet been added to
1919 * a containment hierarchy such that the locale can be determined
1920 * from the containing parent
1921 * @since JDK1.1
1922 */
1923 public Locale getLocale() {
1924 Locale locale = this.locale;
1925 if (locale != null) {
1926 return locale;
1927 }
1928 Container parent = this.parent;
1929
1930 if (parent == null) {
1931 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale");
1932 } else {
1933 return parent.getLocale();
1934 }
1935 }
1936
1937 /**
1938 * Sets the locale of this component. This is a bound property.
1939 * <p>
1940 * This method changes layout-related information, and therefore,
1941 * invalidates the component hierarchy.
1942 *
1943 * @param l the locale to become this component's locale
1944 * @see #getLocale
1945 * @see #invalidate
1946 * @since JDK1.1
1947 */
1948 public void setLocale(Locale l) {
1949 Locale oldValue = locale;
1950 locale = l;
1951
1952 // This is a bound property, so report the change to
1953 // any registered listeners. (Cheap if there are none.)
1954 firePropertyChange("locale", oldValue, l);
1955
1956 // This could change the preferred size of the Component.
1957 invalidateIfValid();
1958 }
1959
1960 /**
1961 * Gets the instance of <code>ColorModel</code> used to display
1962 * the component on the output device.
1963 * @return the color model used by this component
1964 * @see java.awt.image.ColorModel
1965 * @see java.awt.peer.ComponentPeer#getColorModel()
1966 * @see Toolkit#getColorModel()
1967 * @since JDK1.0
1968 */
1969 public ColorModel getColorModel() {
1970 ComponentPeer peer = this.peer;
1971 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
1972 return peer.getColorModel();
1973 } else if (GraphicsEnvironment.isHeadless()) {
1974 return ColorModel.getRGBdefault();
1975 } // else
1976 return getToolkit().getColorModel();
1977 }
1978
1979 /**
1980 * Gets the location of this component in the form of a
1981 * point specifying the component's top-left corner.
1982 * The location will be relative to the parent's coordinate space.
1983 * <p>
1984 * Due to the asynchronous nature of native event handling, this
1985 * method can return outdated values (for instance, after several calls
1986 * of <code>setLocation()</code> in rapid succession). For this
1987 * reason, the recommended method of obtaining a component's position is
1988 * within <code>java.awt.event.ComponentListener.componentMoved()</code>,
1989 * which is called after the operating system has finished moving the
1990 * component.
1991 * </p>
1992 * @return an instance of <code>Point</code> representing
1993 * the top-left corner of the component's bounds in
1994 * the coordinate space of the component's parent
1995 * @see #setLocation
1996 * @see #getLocationOnScreen
1997 * @since JDK1.1
1998 */
1999 public Point getLocation() {
2000 return location();
2001 }
2002
2003 /**
2004 * Gets the location of this component in the form of a point
2005 * specifying the component's top-left corner in the screen's
2006 * coordinate space.
2007 * @return an instance of <code>Point</code> representing
2008 * the top-left corner of the component's bounds in the
2009 * coordinate space of the screen
2010 * @throws <code>IllegalComponentStateException</code> if the
2011 * component is not showing on the screen
2012 * @see #setLocation
2013 * @see #getLocation
2014 */
2015 public Point getLocationOnScreen() {
2016 synchronized (getTreeLock()) {
2017 return getLocationOnScreen_NoTreeLock();
2018 }
2019 }
2020
2021 /*
2022 * a package private version of getLocationOnScreen
2023 * used by GlobalCursormanager to update cursor
2024 */
2025 final Point getLocationOnScreen_NoTreeLock() {
2026
2027 if (peer != null && isShowing()) {
2028 if (peer instanceof LightweightPeer) {
2029 // lightweight component location needs to be translated
2030 // relative to a native component.
2031 Container host = getNativeContainer();
2032 Point pt = host.peer.getLocationOnScreen();
2033 for(Component c = this; c != host; c = c.getParent()) {
2034 pt.x += c.x;
2035 pt.y += c.y;
2036 }
2037 return pt;
2038 } else {
2039 Point pt = peer.getLocationOnScreen();
2040 return pt;
2041 }
2042 } else {
2043 throw new IllegalComponentStateException("component must be showing on the screen to determine its location");
2044 }
2045 }
2046
2047
2048 /**
2049 * @deprecated As of JDK version 1.1,
2050 * replaced by <code>getLocation()</code>.
2051 */
2052 @Deprecated
2053 public Point location() {
2054 return location_NoClientCode();
2055 }
2056
2057 private Point location_NoClientCode() {
2058 return new Point(x, y);
2059 }
2060
2061 /**
2062 * Moves this component to a new location. The top-left corner of
2063 * the new location is specified by the <code>x</code> and <code>y</code>
2064 * parameters in the coordinate space of this component's parent.
2065 * <p>
2066 * This method changes layout-related information, and therefore,
2067 * invalidates the component hierarchy.
2068 *
2069 * @param x the <i>x</i>-coordinate of the new location's
2070 * top-left corner in the parent's coordinate space
2071 * @param y the <i>y</i>-coordinate of the new location's
2072 * top-left corner in the parent's coordinate space
2073 * @see #getLocation
2074 * @see #setBounds
2075 * @see #invalidate
2076 * @since JDK1.1
2077 */
2078 public void setLocation(int x, int y) {
2079 move(x, y);
2080 }
2081
2082 /**
2083 * @deprecated As of JDK version 1.1,
2084 * replaced by <code>setLocation(int, int)</code>.
2085 */
2086 @Deprecated
2087 public void move(int x, int y) {
2088 synchronized(getTreeLock()) {
2089 setBoundsOp(ComponentPeer.SET_LOCATION);
2090 setBounds(x, y, width, height);
2091 }
2092 }
2093
2094 /**
2095 * Moves this component to a new location. The top-left corner of
2096 * the new location is specified by point <code>p</code>. Point
2097 * <code>p</code> is given in the parent's coordinate space.
2098 * <p>
2099 * This method changes layout-related information, and therefore,
2100 * invalidates the component hierarchy.
2101 *
2102 * @param p the point defining the top-left corner
2103 * of the new location, given in the coordinate space of this
2104 * component's parent
2105 * @see #getLocation
2106 * @see #setBounds
2107 * @see #invalidate
2108 * @since JDK1.1
2109 */
2110 public void setLocation(Point p) {
2111 setLocation(p.x, p.y);
2112 }
2113
2114 /**
2115 * Returns the size of this component in the form of a
2116 * <code>Dimension</code> object. The <code>height</code>
2117 * field of the <code>Dimension</code> object contains
2118 * this component's height, and the <code>width</code>
2119 * field of the <code>Dimension</code> object contains
2120 * this component's width.
2121 * @return a <code>Dimension</code> object that indicates the
2122 * size of this component
2123 * @see #setSize
2124 * @since JDK1.1
2125 */
2126 public Dimension getSize() {
2127 return size();
2128 }
2129
2130 /**
2131 * @deprecated As of JDK version 1.1,
2132 * replaced by <code>getSize()</code>.
2133 */
2134 @Deprecated
2135 public Dimension size() {
2136 return new Dimension(width, height);
2137 }
2138
2139 /**
2140 * Resizes this component so that it has width <code>width</code>
2141 * and height <code>height</code>.
2142 * <p>
2143 * This method changes layout-related information, and therefore,
2144 * invalidates the component hierarchy.
2145 *
2146 * @param width the new width of this component in pixels
2147 * @param height the new height of this component in pixels
2148 * @see #getSize
2149 * @see #setBounds
2150 * @see #invalidate
2151 * @since JDK1.1
2152 */
2153 public void setSize(int width, int height) {
2154 resize(width, height);
2155 }
2156
2157 /**
2158 * @deprecated As of JDK version 1.1,
2159 * replaced by <code>setSize(int, int)</code>.
2160 */
2161 @Deprecated
2162 public void resize(int width, int height) {
2163 synchronized(getTreeLock()) {
2164 setBoundsOp(ComponentPeer.SET_SIZE);
2165 setBounds(x, y, width, height);
2166 }
2167 }
2168
2169 /**
2170 * Resizes this component so that it has width <code>d.width</code>
2171 * and height <code>d.height</code>.
2172 * <p>
2173 * This method changes layout-related information, and therefore,
2174 * invalidates the component hierarchy.
2175 *
2176 * @param d the dimension specifying the new size
2177 * of this component
2178 * @throws NullPointerException if {@code d} is {@code null}
2179 * @see #setSize
2180 * @see #setBounds
2181 * @see #invalidate
2182 * @since JDK1.1
2183 */
2184 public void setSize(Dimension d) {
2185 resize(d);
2186 }
2187
2188 /**
2189 * @deprecated As of JDK version 1.1,
2190 * replaced by <code>setSize(Dimension)</code>.
2191 */
2192 @Deprecated
2193 public void resize(Dimension d) {
2194 setSize(d.width, d.height);
2195 }
2196
2197 /**
2198 * Gets the bounds of this component in the form of a
2199 * <code>Rectangle</code> object. The bounds specify this
2200 * component's width, height, and location relative to
2201 * its parent.
2202 * @return a rectangle indicating this component's bounds
2203 * @see #setBounds
2204 * @see #getLocation
2205 * @see #getSize
2206 */
2207 public Rectangle getBounds() {
2208 return bounds();
2209 }
2210
2211 /**
2212 * @deprecated As of JDK version 1.1,
2213 * replaced by <code>getBounds()</code>.
2214 */
2215 @Deprecated
2216 public Rectangle bounds() {
2217 return new Rectangle(x, y, width, height);
2218 }
2219
2220 /**
2221 * Moves and resizes this component. The new location of the top-left
2222 * corner is specified by <code>x</code> and <code>y</code>, and the
2223 * new size is specified by <code>width</code> and <code>height</code>.
2224 * <p>
2225 * This method changes layout-related information, and therefore,
2226 * invalidates the component hierarchy.
2227 *
2228 * @param x the new <i>x</i>-coordinate of this component
2229 * @param y the new <i>y</i>-coordinate of this component
2230 * @param width the new <code>width</code> of this component
2231 * @param height the new <code>height</code> of this
2232 * component
2233 * @see #getBounds
2234 * @see #setLocation(int, int)
2235 * @see #setLocation(Point)
2236 * @see #setSize(int, int)
2237 * @see #setSize(Dimension)
2238 * @see #invalidate
2239 * @since JDK1.1
2240 */
2241 public void setBounds(int x, int y, int width, int height) {
2242 reshape(x, y, width, height);
2243 }
2244
2245 /**
2246 * @deprecated As of JDK version 1.1,
2247 * replaced by <code>setBounds(int, int, int, int)</code>.
2248 */
2249 @Deprecated
2250 public void reshape(int x, int y, int width, int height) {
2251 synchronized (getTreeLock()) {
2252 try {
2253 setBoundsOp(ComponentPeer.SET_BOUNDS);
2254 boolean resized = (this.width != width) || (this.height != height);
2255 boolean moved = (this.x != x) || (this.y != y);
2256 if (!resized && !moved) {
2257 return;
2258 }
2259 int oldX = this.x;
2260 int oldY = this.y;
2261 int oldWidth = this.width;
2262 int oldHeight = this.height;
2263 this.x = x;
2264 this.y = y;
2265 this.width = width;
2266 this.height = height;
2267
2268 if (resized) {
2269 isPacked = false;
2270 }
2271
2272 boolean needNotify = true;
2273 mixOnReshaping();
2274 if (peer != null) {
2275 // LightwightPeer is an empty stub so can skip peer.reshape
2276 if (!(peer instanceof LightweightPeer)) {
2277 reshapeNativePeer(x, y, width, height, getBoundsOp());
2278 // Check peer actualy changed coordinates
2279 resized = (oldWidth != this.width) || (oldHeight != this.height);
2280 moved = (oldX != this.x) || (oldY != this.y);
2281 // fix for 5025858: do not send ComponentEvents for toplevel
2282 // windows here as it is done from peer or native code when
2283 // the window is really resized or moved, otherwise some
2284 // events may be sent twice
2285 if (this instanceof Window) {
2286 needNotify = false;
2287 }
2288 }
2289 if (resized) {
2290 invalidate();
2291 }
2292 if (parent != null) {
2293 parent.invalidateIfValid();
2294 }
2295 }
2296 if (needNotify) {
2297 notifyNewBounds(resized, moved);
2298 }
2299 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight);
2300 } finally {
2301 setBoundsOp(ComponentPeer.RESET_OPERATION);
2302 }
2303 }
2304 }
2305
2306 private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth,
2307 int oldHeight)
2308 {
2309 if (parent != null && peer instanceof LightweightPeer && isShowing()) {
2310 // Have the parent redraw the area this component occupied.
2311 parent.repaint(oldX, oldY, oldWidth, oldHeight);
2312 // Have the parent redraw the area this component *now* occupies.
2313 repaint();
2314 }
2315 }
2316
2317 private void reshapeNativePeer(int x, int y, int width, int height, int op) {
2318 // native peer might be offset by more than direct
2319 // parent since parent might be lightweight.
2320 int nativeX = x;
2321 int nativeY = y;
2322 for (Component c = parent;
2323 (c != null) && (c.peer instanceof LightweightPeer);
2324 c = c.parent)
2325 {
2326 nativeX += c.x;
2327 nativeY += c.y;
2328 }
2329 peer.setBounds(nativeX, nativeY, width, height, op);
2330 }
2331
2332
2333 private void notifyNewBounds(boolean resized, boolean moved) {
2334 if (componentListener != null
2335 || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0
2336 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK))
2337 {
2338 if (resized) {
2339 ComponentEvent e = new ComponentEvent(this,
2340 ComponentEvent.COMPONENT_RESIZED);
2341 Toolkit.getEventQueue().postEvent(e);
2342 }
2343 if (moved) {
2344 ComponentEvent e = new ComponentEvent(this,
2345 ComponentEvent.COMPONENT_MOVED);
2346 Toolkit.getEventQueue().postEvent(e);
2347 }
2348 } else {
2349 if (this instanceof Container && ((Container)this).countComponents() > 0) {
2350 boolean enabledOnToolkit =
2351 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK);
2352 if (resized) {
2353
2354 ((Container)this).createChildHierarchyEvents(
2355 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit);
2356 }
2357 if (moved) {
2358 ((Container)this).createChildHierarchyEvents(
2359 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit);
2360 }
2361 }
2362 }
2363 }
2364
2365 /**
2366 * Moves and resizes this component to conform to the new
2367 * bounding rectangle <code>r</code>. This component's new
2368 * position is specified by <code>r.x</code> and <code>r.y</code>,
2369 * and its new size is specified by <code>r.width</code> and
2370 * <code>r.height</code>
2371 * <p>
2372 * This method changes layout-related information, and therefore,
2373 * invalidates the component hierarchy.
2374 *
2375 * @param r the new bounding rectangle for this component
2376 * @throws NullPointerException if {@code r} is {@code null}
2377 * @see #getBounds
2378 * @see #setLocation(int, int)
2379 * @see #setLocation(Point)
2380 * @see #setSize(int, int)
2381 * @see #setSize(Dimension)
2382 * @see #invalidate
2383 * @since JDK1.1
2384 */
2385 public void setBounds(Rectangle r) {
2386 setBounds(r.x, r.y, r.width, r.height);
2387 }
2388
2389
2390 /**
2391 * Returns the current x coordinate of the components origin.
2392 * This method is preferable to writing
2393 * <code>component.getBounds().x</code>,
2394 * or <code>component.getLocation().x</code> because it doesn't
2395 * cause any heap allocations.
2396 *
2397 * @return the current x coordinate of the components origin
2398 * @since 1.2
2399 */
2400 public int getX() {
2401 return x;
2402 }
2403
2404
2405 /**
2406 * Returns the current y coordinate of the components origin.
2407 * This method is preferable to writing
2408 * <code>component.getBounds().y</code>,
2409 * or <code>component.getLocation().y</code> because it
2410 * doesn't cause any heap allocations.
2411 *
2412 * @return the current y coordinate of the components origin
2413 * @since 1.2
2414 */
2415 public int getY() {
2416 return y;
2417 }
2418
2419
2420 /**
2421 * Returns the current width of this component.
2422 * This method is preferable to writing
2423 * <code>component.getBounds().width</code>,
2424 * or <code>component.getSize().width</code> because it
2425 * doesn't cause any heap allocations.
2426 *
2427 * @return the current width of this component
2428 * @since 1.2
2429 */
2430 public int getWidth() {
2431 return width;
2432 }
2433
2434
2435 /**
2436 * Returns the current height of this component.
2437 * This method is preferable to writing
2438 * <code>component.getBounds().height</code>,
2439 * or <code>component.getSize().height</code> because it
2440 * doesn't cause any heap allocations.
2441 *
2442 * @return the current height of this component
2443 * @since 1.2
2444 */
2445 public int getHeight() {
2446 return height;
2447 }
2448
2449 /**
2450 * Stores the bounds of this component into "return value" <b>rv</b> and
2451 * return <b>rv</b>. If rv is <code>null</code> a new
2452 * <code>Rectangle</code> is allocated.
2453 * This version of <code>getBounds</code> is useful if the caller
2454 * wants to avoid allocating a new <code>Rectangle</code> object
2455 * on the heap.
2456 *
2457 * @param rv the return value, modified to the components bounds
2458 * @return rv
2459 */
2460 public Rectangle getBounds(Rectangle rv) {
2461 if (rv == null) {
2462 return new Rectangle(getX(), getY(), getWidth(), getHeight());
2463 }
2464 else {
2465 rv.setBounds(getX(), getY(), getWidth(), getHeight());
2466 return rv;
2467 }
2468 }
2469
2470 /**
2471 * Stores the width/height of this component into "return value" <b>rv</b>
2472 * and return <b>rv</b>. If rv is <code>null</code> a new
2473 * <code>Dimension</code> object is allocated. This version of
2474 * <code>getSize</code> is useful if the caller wants to avoid
2475 * allocating a new <code>Dimension</code> object on the heap.
2476 *
2477 * @param rv the return value, modified to the components size
2478 * @return rv
2479 */
2480 public Dimension getSize(Dimension rv) {
2481 if (rv == null) {
2482 return new Dimension(getWidth(), getHeight());
2483 }
2484 else {
2485 rv.setSize(getWidth(), getHeight());
2486 return rv;
2487 }
2488 }
2489
2490 /**
2491 * Stores the x,y origin of this component into "return value" <b>rv</b>
2492 * and return <b>rv</b>. If rv is <code>null</code> a new
2493 * <code>Point</code> is allocated.
2494 * This version of <code>getLocation</code> is useful if the
2495 * caller wants to avoid allocating a new <code>Point</code>
2496 * object on the heap.
2497 *
2498 * @param rv the return value, modified to the components location
2499 * @return rv
2500 */
2501 public Point getLocation(Point rv) {
2502 if (rv == null) {
2503 return new Point(getX(), getY());
2504 }
2505 else {
2506 rv.setLocation(getX(), getY());
2507 return rv;
2508 }
2509 }
2510
2511 /**
2512 * Returns true if this component is completely opaque, returns
2513 * false by default.
2514 * <p>
2515 * An opaque component paints every pixel within its
2516 * rectangular region. A non-opaque component paints only some of
2517 * its pixels, allowing the pixels underneath it to "show through".
2518 * A component that does not fully paint its pixels therefore
2519 * provides a degree of transparency.
2520 * <p>
2521 * Subclasses that guarantee to always completely paint their
2522 * contents should override this method and return true.
2523 *
2524 * @return true if this component is completely opaque
2525 * @see #isLightweight
2526 * @since 1.2
2527 */
2528 public boolean isOpaque() {
2529 if (getPeer() == null) {
2530 return false;
2531 }
2532 else {
2533 return !isLightweight();
2534 }
2535 }
2536
2537
2538 /**
2539 * A lightweight component doesn't have a native toolkit peer.
2540 * Subclasses of <code>Component</code> and <code>Container</code>,
2541 * other than the ones defined in this package like <code>Button</code>
2542 * or <code>Scrollbar</code>, are lightweight.
2543 * All of the Swing components are lightweights.
2544 * <p>
2545 * This method will always return <code>false</code> if this component
2546 * is not displayable because it is impossible to determine the
2547 * weight of an undisplayable component.
2548 *
2549 * @return true if this component has a lightweight peer; false if
2550 * it has a native peer or no peer
2551 * @see #isDisplayable
2552 * @since 1.2
2553 */
2554 public boolean isLightweight() {
2555 return getPeer() instanceof LightweightPeer;
2556 }
2557
2558
2559 /**
2560 * Sets the preferred size of this component to a constant
2561 * value. Subsequent calls to <code>getPreferredSize</code> will always
2562 * return this value. Setting the preferred size to <code>null</code>
2563 * restores the default behavior.
2564 *
2565 * @param preferredSize The new preferred size, or null
2566 * @see #getPreferredSize
2567 * @see #isPreferredSizeSet
2568 * @since 1.5
2569 */
2570 public void setPreferredSize(Dimension preferredSize) {
2571 Dimension old;
2572 // If the preferred size was set, use it as the old value, otherwise
2573 // use null to indicate we didn't previously have a set preferred
2574 // size.
2575 if (prefSizeSet) {
2576 old = this.prefSize;
2577 }
2578 else {
2579 old = null;
2580 }
2581 this.prefSize = preferredSize;
2582 prefSizeSet = (preferredSize != null);
2583 firePropertyChange("preferredSize", old, preferredSize);
2584 }
2585
2586
2587 /**
2588 * Returns true if the preferred size has been set to a
2589 * non-<code>null</code> value otherwise returns false.
2590 *
2591 * @return true if <code>setPreferredSize</code> has been invoked
2592 * with a non-null value.
2593 * @since 1.5
2594 */
2595 public boolean isPreferredSizeSet() {
2596 return prefSizeSet;
2597 }
2598
2599
2600 /**
2601 * Gets the preferred size of this component.
2602 * @return a dimension object indicating this component's preferred size
2603 * @see #getMinimumSize
2604 * @see LayoutManager
2605 */
2606 public Dimension getPreferredSize() {
2607 return preferredSize();
2608 }
2609
2610
2611 /**
2612 * @deprecated As of JDK version 1.1,
2613 * replaced by <code>getPreferredSize()</code>.
2614 */
2615 @Deprecated
2616 public Dimension preferredSize() {
2617 /* Avoid grabbing the lock if a reasonable cached size value
2618 * is available.
2619 */
2620 Dimension dim = prefSize;
2621 if (dim == null || !(isPreferredSizeSet() || isValid())) {
2622 synchronized (getTreeLock()) {
2623 prefSize = (peer != null) ?
2624 peer.getPreferredSize() :
2625 getMinimumSize();
2626 dim = prefSize;
2627 }
2628 }
2629 return new Dimension(dim);
2630 }
2631
2632 /**
2633 * Sets the minimum size of this component to a constant
2634 * value. Subsequent calls to <code>getMinimumSize</code> will always
2635 * return this value. Setting the minimum size to <code>null</code>
2636 * restores the default behavior.
2637 *
2638 * @param minimumSize the new minimum size of this component
2639 * @see #getMinimumSize
2640 * @see #isMinimumSizeSet
2641 * @since 1.5
2642 */
2643 public void setMinimumSize(Dimension minimumSize) {
2644 Dimension old;
2645 // If the minimum size was set, use it as the old value, otherwise
2646 // use null to indicate we didn't previously have a set minimum
2647 // size.
2648 if (minSizeSet) {
2649 old = this.minSize;
2650 }
2651 else {
2652 old = null;
2653 }
2654 this.minSize = minimumSize;
2655 minSizeSet = (minimumSize != null);
2656 firePropertyChange("minimumSize", old, minimumSize);
2657 }
2658
2659 /**
2660 * Returns whether or not <code>setMinimumSize</code> has been
2661 * invoked with a non-null value.
2662 *
2663 * @return true if <code>setMinimumSize</code> has been invoked with a
2664 * non-null value.
2665 * @since 1.5
2666 */
2667 public boolean isMinimumSizeSet() {
2668 return minSizeSet;
2669 }
2670
2671 /**
2672 * Gets the mininimum size of this component.
2673 * @return a dimension object indicating this component's minimum size
2674 * @see #getPreferredSize
2675 * @see LayoutManager
2676 */
2677 public Dimension getMinimumSize() {
2678 return minimumSize();
2679 }
2680
2681 /**
2682 * @deprecated As of JDK version 1.1,
2683 * replaced by <code>getMinimumSize()</code>.
2684 */
2685 @Deprecated
2686 public Dimension minimumSize() {
2687 /* Avoid grabbing the lock if a reasonable cached size value
2688 * is available.
2689 */
2690 Dimension dim = minSize;
2691 if (dim == null || !(isMinimumSizeSet() || isValid())) {
2692 synchronized (getTreeLock()) {
2693 minSize = (peer != null) ?
2694 peer.getMinimumSize() :
2695 size();
2696 dim = minSize;
2697 }
2698 }
2699 return new Dimension(dim);
2700 }
2701
2702 /**
2703 * Sets the maximum size of this component to a constant
2704 * value. Subsequent calls to <code>getMaximumSize</code> will always
2705 * return this value. Setting the maximum size to <code>null</code>
2706 * restores the default behavior.
2707 *
2708 * @param maximumSize a <code>Dimension</code> containing the
2709 * desired maximum allowable size
2710 * @see #getMaximumSize
2711 * @see #isMaximumSizeSet
2712 * @since 1.5
2713 */
2714 public void setMaximumSize(Dimension maximumSize) {
2715 // If the maximum size was set, use it as the old value, otherwise
2716 // use null to indicate we didn't previously have a set maximum
2717 // size.
2718 Dimension old;
2719 if (maxSizeSet) {
2720 old = this.maxSize;
2721 }
2722 else {
2723 old = null;
2724 }
2725 this.maxSize = maximumSize;
2726 maxSizeSet = (maximumSize != null);
2727 firePropertyChange("maximumSize", old, maximumSize);
2728 }
2729
2730 /**
2731 * Returns true if the maximum size has been set to a non-<code>null</code>
2732 * value otherwise returns false.
2733 *
2734 * @return true if <code>maximumSize</code> is non-<code>null</code>,
2735 * false otherwise
2736 * @since 1.5
2737 */
2738 public boolean isMaximumSizeSet() {
2739 return maxSizeSet;
2740 }
2741
2742 /**
2743 * Gets the maximum size of this component.
2744 * @return a dimension object indicating this component's maximum size
2745 * @see #getMinimumSize
2746 * @see #getPreferredSize
2747 * @see LayoutManager
2748 */
2749 public Dimension getMaximumSize() {
2750 if (isMaximumSizeSet()) {
2751 return new Dimension(maxSize);
2752 }
2753 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE);
2754 }
2755
2756 /**
2757 * Returns the alignment along the x axis. This specifies how
2758 * the component would like to be aligned relative to other
2759 * components. The value should be a number between 0 and 1
2760 * where 0 represents alignment along the origin, 1 is aligned
2761 * the furthest away from the origin, 0.5 is centered, etc.
2762 */
2763 public float getAlignmentX() {
2764 return CENTER_ALIGNMENT;
2765 }
2766
2767 /**
2768 * Returns the alignment along the y axis. This specifies how
2769 * the component would like to be aligned relative to other
2770 * components. The value should be a number between 0 and 1
2771 * where 0 represents alignment along the origin, 1 is aligned
2772 * the furthest away from the origin, 0.5 is centered, etc.
2773 */
2774 public float getAlignmentY() {
2775 return CENTER_ALIGNMENT;
2776 }
2777
2778 /**
2779 * Returns the baseline. The baseline is measured from the top of
2780 * the component. This method is primarily meant for
2781 * <code>LayoutManager</code>s to align components along their
2782 * baseline. A return value less than 0 indicates this component
2783 * does not have a reasonable baseline and that
2784 * <code>LayoutManager</code>s should not align this component on
2785 * its baseline.
2786 * <p>
2787 * The default implementation returns -1. Subclasses that support
2788 * baseline should override appropriately. If a value &gt;= 0 is
2789 * returned, then the component has a valid baseline for any
2790 * size &gt;= the minimum size and <code>getBaselineResizeBehavior</code>
2791 * can be used to determine how the baseline changes with size.
2792 *
2793 * @param width the width to get the baseline for
2794 * @param height the height to get the baseline for
2795 * @return the baseline or &lt; 0 indicating there is no reasonable
2796 * baseline
2797 * @throws IllegalArgumentException if width or height is &lt; 0
2798 * @see #getBaselineResizeBehavior
2799 * @see java.awt.FontMetrics
2800 * @since 1.6
2801 */
2802 public int getBaseline(int width, int height) {
2803 if (width < 0 || height < 0) {
2804 throw new IllegalArgumentException(
2805 "Width and height must be >= 0");
2806 }
2807 return -1;
2808 }
2809
2810 /**
2811 * Returns an enum indicating how the baseline of the component
2812 * changes as the size changes. This method is primarily meant for
2813 * layout managers and GUI builders.
2814 * <p>
2815 * The default implementation returns
2816 * <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a
2817 * baseline should override appropriately. Subclasses should
2818 * never return <code>null</code>; if the baseline can not be
2819 * calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers
2820 * should first ask for the baseline using
2821 * <code>getBaseline</code> and if a value &gt;= 0 is returned use
2822 * this method. It is acceptable for this method to return a
2823 * value other than <code>BaselineResizeBehavior.OTHER</code> even if
2824 * <code>getBaseline</code> returns a value less than 0.
2825 *
2826 * @return an enum indicating how the baseline changes as the component
2827 * size changes
2828 * @see #getBaseline(int, int)
2829 * @since 1.6
2830 */
2831 public BaselineResizeBehavior getBaselineResizeBehavior() {
2832 return BaselineResizeBehavior.OTHER;
2833 }
2834
2835 /**
2836 * Prompts the layout manager to lay out this component. This is
2837 * usually called when the component (more specifically, container)
2838 * is validated.
2839 * @see #validate
2840 * @see LayoutManager
2841 */
2842 public void doLayout() {
2843 layout();
2844 }
2845
2846 /**
2847 * @deprecated As of JDK version 1.1,
2848 * replaced by <code>doLayout()</code>.
2849 */
2850 @Deprecated
2851 public void layout() {
2852 }
2853
2854 /**
2855 * Validates this component.
2856 * <p>
2857 * The meaning of the term <i>validating</i> is defined by the ancestors of
2858 * this class. See {@link Container#validate} for more details.
2859 *
2860 * @see #invalidate
2861 * @see #doLayout()
2862 * @see LayoutManager
2863 * @see Container#validate
2864 * @since JDK1.0
2865 */
2866 public void validate() {
2867 synchronized (getTreeLock()) {
2868 ComponentPeer peer = this.peer;
2869 boolean wasValid = isValid();
2870 if (!wasValid && peer != null) {
2871 Font newfont = getFont();
2872 Font oldfont = peerFont;
2873 if (newfont != oldfont && (oldfont == null
2874 || !oldfont.equals(newfont))) {
2875 peer.setFont(newfont);
2876 peerFont = newfont;
2877 }
2878 peer.layout();
2879 }
2880 valid = true;
2881 if (!wasValid) {
2882 mixOnValidating();
2883 }
2884 }
2885 }
2886
2887 /**
2888 * Invalidates this component and its ancestors.
2889 * <p>
2890 * By default, all the ancestors of the component up to the top-most
2891 * container of the hierarchy are marked invalid. If the {@code
2892 * java.awt.smartInvalidate} system property is set to {@code true},
2893 * invalidation stops on the nearest validate root of this component.
2894 * Marking a container <i>invalid</i> indicates that the container needs to
2895 * be laid out.
2896 * <p>
2897 * This method is called automatically when any layout-related information
2898 * changes (e.g. setting the bounds of the component, or adding the
2899 * component to a container).
2900 * <p>
2901 * This method might be called often, so it should work fast.
2902 *
2903 * @see #validate
2904 * @see #doLayout
2905 * @see LayoutManager
2906 * @see java.awt.Container#isValidateRoot
2907 * @since JDK1.0
2908 */
2909 public void invalidate() {
2910 synchronized (getTreeLock()) {
2911 /* Nullify cached layout and size information.
2912 * For efficiency, propagate invalidate() upwards only if
2913 * some other component hasn't already done so first.
2914 */
2915 valid = false;
2916 if (!isPreferredSizeSet()) {
2917 prefSize = null;
2918 }
2919 if (!isMinimumSizeSet()) {
2920 minSize = null;
2921 }
2922 if (!isMaximumSizeSet()) {
2923 maxSize = null;
2924 }
2925 invalidateParent();
2926 }
2927 }
2928
2929 /**
2930 * Invalidates the parent of this component if any.
2931 *
2932 * This method MUST BE invoked under the TreeLock.
2933 */
2934 void invalidateParent() {
2935 if (parent != null) {
2936 parent.invalidateIfValid();
2937 }
2938 }
2939
2940 /** Invalidates the component unless it is already invalid.
2941 */
2942 final void invalidateIfValid() {
2943 if (isValid()) {
2944 invalidate();
2945 }
2946 }
2947
2948 /**
2949 * Revalidates the component hierarchy up to the nearest validate root.
2950 * <p>
2951 * This method first invalidates the component hierarchy starting from this
2952 * component up to the nearest validate root. Afterwards, the component
2953 * hierarchy is validated starting from the nearest validate root.
2954 * <p>
2955 * This is a convenience method supposed to help application developers
2956 * avoid looking for validate roots manually. Basically, it's equivalent to
2957 * first calling the {@link #invalidate()} method on this component, and
2958 * then calling the {@link #validate()} method on the nearest validate
2959 * root.
2960 *
2961 * @see Container#isValidateRoot
2962 * @since 1.7
2963 */
2964 public void revalidate() {
2965 synchronized (getTreeLock()) {
2966 invalidate();
2967
2968 Container root = getContainer();
2969 if (root == null) {
2970 // There's no parents. Just validate itself.
2971 validate();
2972 } else {
2973 while (!root.isValidateRoot()) {
2974 if (root.getContainer() == null) {
2975 // If there's no validate roots, we'll validate the
2976 // topmost container
2977 break;
2978 }
2979
2980 root = root.getContainer();
2981 }
2982
2983 root.validate();
2984 }
2985 }
2986 }
2987
2988 /**
2989 * Creates a graphics context for this component. This method will
2990 * return <code>null</code> if this component is currently not
2991 * displayable.
2992 * @return a graphics context for this component, or <code>null</code>
2993 * if it has none
2994 * @see #paint
2995 * @since JDK1.0
2996 */
2997 public Graphics getGraphics() {
2998 if (peer instanceof LightweightPeer) {
2999 // This is for a lightweight component, need to
3000 // translate coordinate spaces and clip relative
3001 // to the parent.
3002 if (parent == null) return null;
3003 Graphics g = parent.getGraphics();
3004 if (g == null) return null;
3005 if (g instanceof ConstrainableGraphics) {
3006 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3007 } else {
3008 g.translate(x,y);
3009 g.setClip(0, 0, width, height);
3010 }
3011 g.setFont(getFont());
3012 return g;
3013 } else {
3014 ComponentPeer peer = this.peer;
3015 return (peer != null) ? peer.getGraphics() : null;
3016 }
3017 }
3018
3019 final Graphics getGraphics_NoClientCode() {
3020 ComponentPeer peer = this.peer;
3021 if (peer instanceof LightweightPeer) {
3022 // This is for a lightweight component, need to
3023 // translate coordinate spaces and clip relative
3024 // to the parent.
3025 Container parent = this.parent;
3026 if (parent == null) return null;
3027 Graphics g = parent.getGraphics_NoClientCode();
3028 if (g == null) return null;
3029 if (g instanceof ConstrainableGraphics) {
3030 ((ConstrainableGraphics) g).constrain(x, y, width, height);
3031 } else {
3032 g.translate(x,y);
3033 g.setClip(0, 0, width, height);
3034 }
3035 g.setFont(getFont_NoClientCode());
3036 return g;
3037 } else {
3038 return (peer != null) ? peer.getGraphics() : null;
3039 }
3040 }
3041
3042 /**
3043 * Gets the font metrics for the specified font.
3044 * Warning: Since Font metrics are affected by the
3045 * {@link java.awt.font.FontRenderContext FontRenderContext} and
3046 * this method does not provide one, it can return only metrics for
3047 * the default render context which may not match that used when
3048 * rendering on the Component if {@link Graphics2D} functionality is being
3049 * used. Instead metrics can be obtained at rendering time by calling
3050 * {@link Graphics#getFontMetrics()} or text measurement APIs on the
3051 * {@link Font Font} class.
3052 * @param font the font for which font metrics is to be
3053 * obtained
3054 * @return the font metrics for <code>font</code>
3055 * @see #getFont
3056 * @see #getPeer
3057 * @see java.awt.peer.ComponentPeer#getFontMetrics(Font)
3058 * @see Toolkit#getFontMetrics(Font)
3059 * @since JDK1.0
3060 */
3061 public FontMetrics getFontMetrics(Font font) {
3062 // This is an unsupported hack, but left in for a customer.
3063 // Do not remove.
3064 FontManager fm = FontManagerFactory.getInstance();
3065 if (fm instanceof SunFontManager
3066 && ((SunFontManager) fm).usePlatformFontMetrics()) {
3067
3068 if (peer != null &&
3069 !(peer instanceof LightweightPeer)) {
3070 return peer.getFontMetrics(font);
3071 }
3072 }
3073 return sun.font.FontDesignMetrics.getMetrics(font);
3074 }
3075
3076 /**
3077 * Sets the cursor image to the specified cursor. This cursor
3078 * image is displayed when the <code>contains</code> method for
3079 * this component returns true for the current cursor location, and
3080 * this Component is visible, displayable, and enabled. Setting the
3081 * cursor of a <code>Container</code> causes that cursor to be displayed
3082 * within all of the container's subcomponents, except for those
3083 * that have a non-<code>null</code> cursor.
3084 * <p>
3085 * The method may have no visual effect if the Java platform
3086 * implementation and/or the native system do not support
3087 * changing the mouse cursor shape.
3088 * @param cursor One of the constants defined
3089 * by the <code>Cursor</code> class;
3090 * if this parameter is <code>null</code>
3091 * then this component will inherit
3092 * the cursor of its parent
3093 * @see #isEnabled
3094 * @see #isShowing
3095 * @see #getCursor
3096 * @see #contains
3097 * @see Toolkit#createCustomCursor
3098 * @see Cursor
3099 * @since JDK1.1
3100 */
3101 public void setCursor(Cursor cursor) {
3102 this.cursor = cursor;
3103 updateCursorImmediately();
3104 }
3105
3106 /**
3107 * Updates the cursor. May not be invoked from the native
3108 * message pump.
3109 */
3110 final void updateCursorImmediately() {
3111 if (peer instanceof LightweightPeer) {
3112 Container nativeContainer = getNativeContainer();
3113
3114 if (nativeContainer == null) return;
3115
3116 ComponentPeer cPeer = nativeContainer.getPeer();
3117
3118 if (cPeer != null) {
3119 cPeer.updateCursorImmediately();
3120 }
3121 } else if (peer != null) {
3122 peer.updateCursorImmediately();
3123 }
3124 }
3125
3126 /**
3127 * Gets the cursor set in the component. If the component does
3128 * not have a cursor set, the cursor of its parent is returned.
3129 * If no cursor is set in the entire hierarchy,
3130 * <code>Cursor.DEFAULT_CURSOR</code> is returned.
3131 * @see #setCursor
3132 * @since JDK1.1
3133 */
3134 public Cursor getCursor() {
3135 return getCursor_NoClientCode();
3136 }
3137
3138 final Cursor getCursor_NoClientCode() {
3139 Cursor cursor = this.cursor;
3140 if (cursor != null) {
3141 return cursor;
3142 }
3143 Container parent = this.parent;
3144 if (parent != null) {
3145 return parent.getCursor_NoClientCode();
3146 } else {
3147 return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
3148 }
3149 }
3150
3151 /**
3152 * Returns whether the cursor has been explicitly set for this Component.
3153 * If this method returns <code>false</code>, this Component is inheriting
3154 * its cursor from an ancestor.
3155 *
3156 * @return <code>true</code> if the cursor has been explicitly set for this
3157 * Component; <code>false</code> otherwise.
3158 * @since 1.4
3159 */
3160 public boolean isCursorSet() {
3161 return (cursor != null);
3162 }
3163
3164 /**
3165 * Paints this component.
3166 * <p>
3167 * This method is called when the contents of the component should
3168 * be painted; such as when the component is first being shown or
3169 * is damaged and in need of repair. The clip rectangle in the
3170 * <code>Graphics</code> parameter is set to the area
3171 * which needs to be painted.
3172 * Subclasses of <code>Component</code> that override this
3173 * method need not call <code>super.paint(g)</code>.
3174 * <p>
3175 * For performance reasons, <code>Component</code>s with zero width
3176 * or height aren't considered to need painting when they are first shown,
3177 * and also aren't considered to need repair.
3178 * <p>
3179 * <b>Note</b>: For more information on the paint mechanisms utilitized
3180 * by AWT and Swing, including information on how to write the most
3181 * efficient painting code, see
3182 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3183 *
3184 * @param g the graphics context to use for painting
3185 * @see #update
3186 * @since JDK1.0
3187 */
3188 public void paint(Graphics g) {
3189 }
3190
3191 /**
3192 * Updates this component.
3193 * <p>
3194 * If this component is not a lightweight component, the
3195 * AWT calls the <code>update</code> method in response to
3196 * a call to <code>repaint</code>. You can assume that
3197 * the background is not cleared.
3198 * <p>
3199 * The <code>update</code> method of <code>Component</code>
3200 * calls this component's <code>paint</code> method to redraw
3201 * this component. This method is commonly overridden by subclasses
3202 * which need to do additional work in response to a call to
3203 * <code>repaint</code>.
3204 * Subclasses of Component that override this method should either
3205 * call <code>super.update(g)</code>, or call <code>paint(g)</code>
3206 * directly from their <code>update</code> method.
3207 * <p>
3208 * The origin of the graphics context, its
3209 * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3210 * top-left corner of this component. The clipping region of the
3211 * graphics context is the bounding rectangle of this component.
3212 *
3213 * <p>
3214 * <b>Note</b>: For more information on the paint mechanisms utilitized
3215 * by AWT and Swing, including information on how to write the most
3216 * efficient painting code, see
3217 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3218 *
3219 * @param g the specified context to use for updating
3220 * @see #paint
3221 * @see #repaint()
3222 * @since JDK1.0
3223 */
3224 public void update(Graphics g) {
3225 paint(g);
3226 }
3227
3228 /**
3229 * Paints this component and all of its subcomponents.
3230 * <p>
3231 * The origin of the graphics context, its
3232 * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3233 * top-left corner of this component. The clipping region of the
3234 * graphics context is the bounding rectangle of this component.
3235 *
3236 * @param g the graphics context to use for painting
3237 * @see #paint
3238 * @since JDK1.0
3239 */
3240 public void paintAll(Graphics g) {
3241 if (isShowing()) {
3242 GraphicsCallback.PeerPaintCallback.getInstance().
3243 runOneComponent(this, new Rectangle(0, 0, width, height),
3244 g, g.getClip(),
3245 GraphicsCallback.LIGHTWEIGHTS |
3246 GraphicsCallback.HEAVYWEIGHTS);
3247 }
3248 }
3249
3250 /**
3251 * Simulates the peer callbacks into java.awt for painting of
3252 * lightweight Components.
3253 * @param g the graphics context to use for painting
3254 * @see #paintAll
3255 */
3256 void lightweightPaint(Graphics g) {
3257 paint(g);
3258 }
3259
3260 /**
3261 * Paints all the heavyweight subcomponents.
3262 */
3263 void paintHeavyweightComponents(Graphics g) {
3264 }
3265
3266 /**
3267 * Repaints this component.
3268 * <p>
3269 * If this component is a lightweight component, this method
3270 * causes a call to this component's <code>paint</code>
3271 * method as soon as possible. Otherwise, this method causes
3272 * a call to this component's <code>update</code> method as soon
3273 * as possible.
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://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3279
3280 *
3281 * @see #update(Graphics)
3282 * @since JDK1.0
3283 */
3284 public void repaint() {
3285 repaint(0, 0, 0, width, height);
3286 }
3287
3288 /**
3289 * Repaints the component. If this component is a lightweight
3290 * component, this results in a call to <code>paint</code>
3291 * within <code>tm</code> milliseconds.
3292 * <p>
3293 * <b>Note</b>: For more information on the paint mechanisms utilitized
3294 * by AWT and Swing, including information on how to write the most
3295 * efficient painting code, see
3296 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3297 *
3298 * @param tm maximum time in milliseconds before update
3299 * @see #paint
3300 * @see #update(Graphics)
3301 * @since JDK1.0
3302 */
3303 public void repaint(long tm) {
3304 repaint(tm, 0, 0, width, height);
3305 }
3306
3307 /**
3308 * Repaints the specified rectangle of this component.
3309 * <p>
3310 * If this component is a lightweight component, this method
3311 * causes a call to this component's <code>paint</code> method
3312 * as soon as possible. Otherwise, this method causes a call to
3313 * this component's <code>update</code> method as soon as possible.
3314 * <p>
3315 * <b>Note</b>: For more information on the paint mechanisms utilitized
3316 * by AWT and Swing, including information on how to write the most
3317 * efficient painting code, see
3318 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3319 *
3320 * @param x the <i>x</i> coordinate
3321 * @param y the <i>y</i> coordinate
3322 * @param width the width
3323 * @param height the height
3324 * @see #update(Graphics)
3325 * @since JDK1.0
3326 */
3327 public void repaint(int x, int y, int width, int height) {
3328 repaint(0, x, y, width, height);
3329 }
3330
3331 /**
3332 * Repaints the specified rectangle of this component within
3333 * <code>tm</code> milliseconds.
3334 * <p>
3335 * If this component is a lightweight component, this method causes
3336 * a call to this component's <code>paint</code> method.
3337 * Otherwise, this method causes a call to this component's
3338 * <code>update</code> method.
3339 * <p>
3340 * <b>Note</b>: For more information on the paint mechanisms utilitized
3341 * by AWT and Swing, including information on how to write the most
3342 * efficient painting code, see
3343 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>.
3344 *
3345 * @param tm maximum time in milliseconds before update
3346 * @param x the <i>x</i> coordinate
3347 * @param y the <i>y</i> coordinate
3348 * @param width the width
3349 * @param height the height
3350 * @see #update(Graphics)
3351 * @since JDK1.0
3352 */
3353 public void repaint(long tm, int x, int y, int width, int height) {
3354 if (this.peer instanceof LightweightPeer) {
3355 // Needs to be translated to parent coordinates since
3356 // a parent native container provides the actual repaint
3357 // services. Additionally, the request is restricted to
3358 // the bounds of the component.
3359 if (parent != null) {
3360 if (x < 0) {
3361 width += x;
3362 x = 0;
3363 }
3364 if (y < 0) {
3365 height += y;
3366 y = 0;
3367 }
3368
3369 int pwidth = (width > this.width) ? this.width : width;
3370 int pheight = (height > this.height) ? this.height : height;
3371
3372 if (pwidth <= 0 || pheight <= 0) {
3373 return;
3374 }
3375
3376 int px = this.x + x;
3377 int py = this.y + y;
3378 parent.repaint(tm, px, py, pwidth, pheight);
3379 }
3380 } else {
3381 if (isVisible() && (this.peer != null) &&
3382 (width > 0) && (height > 0)) {
3383 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE,
3384 new Rectangle(x, y, width, height));
3385 Toolkit.getEventQueue().postEvent(e);
3386 }
3387 }
3388 }
3389
3390 /**
3391 * Prints this component. Applications should override this method
3392 * for components that must do special processing before being
3393 * printed or should be printed differently than they are painted.
3394 * <p>
3395 * The default implementation of this method calls the
3396 * <code>paint</code> method.
3397 * <p>
3398 * The origin of the graphics context, its
3399 * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3400 * top-left corner of this component. The clipping region of the
3401 * graphics context is the bounding rectangle of this component.
3402 * @param g the graphics context to use for printing
3403 * @see #paint(Graphics)
3404 * @since JDK1.0
3405 */
3406 public void print(Graphics g) {
3407 paint(g);
3408 }
3409
3410 /**
3411 * Prints this component and all of its subcomponents.
3412 * <p>
3413 * The origin of the graphics context, its
3414 * (<code>0</code>,&nbsp;<code>0</code>) coordinate point, is the
3415 * top-left corner of this component. The clipping region of the
3416 * graphics context is the bounding rectangle of this component.
3417 * @param g the graphics context to use for printing
3418 * @see #print(Graphics)
3419 * @since JDK1.0
3420 */
3421 public void printAll(Graphics g) {
3422 if (isShowing()) {
3423 GraphicsCallback.PeerPrintCallback.getInstance().
3424 runOneComponent(this, new Rectangle(0, 0, width, height),
3425 g, g.getClip(),
3426 GraphicsCallback.LIGHTWEIGHTS |
3427 GraphicsCallback.HEAVYWEIGHTS);
3428 }
3429 }
3430
3431 /**
3432 * Simulates the peer callbacks into java.awt for printing of
3433 * lightweight Components.
3434 * @param g the graphics context to use for printing
3435 * @see #printAll
3436 */
3437 void lightweightPrint(Graphics g) {
3438 print(g);
3439 }
3440
3441 /**
3442 * Prints all the heavyweight subcomponents.
3443 */
3444 void printHeavyweightComponents(Graphics g) {
3445 }
3446
3447 private Insets getInsets_NoClientCode() {
3448 ComponentPeer peer = this.peer;
3449 if (peer instanceof ContainerPeer) {
3450 return (Insets)((ContainerPeer)peer).getInsets().clone();
3451 }
3452 return new Insets(0, 0, 0, 0);
3453 }
3454
3455 /**
3456 * Repaints the component when the image has changed.
3457 * This <code>imageUpdate</code> method of an <code>ImageObserver</code>
3458 * is called when more information about an
3459 * image which had been previously requested using an asynchronous
3460 * routine such as the <code>drawImage</code> method of
3461 * <code>Graphics</code> becomes available.
3462 * See the definition of <code>imageUpdate</code> for
3463 * more information on this method and its arguments.
3464 * <p>
3465 * The <code>imageUpdate</code> method of <code>Component</code>
3466 * incrementally draws an image on the component as more of the bits
3467 * of the image are available.
3468 * <p>
3469 * If the system property <code>awt.image.incrementaldraw</code>
3470 * is missing or has the value <code>true</code>, the image is
3471 * incrementally drawn. If the system property has any other value,
3472 * then the image is not drawn until it has been completely loaded.
3473 * <p>
3474 * Also, if incremental drawing is in effect, the value of the
3475 * system property <code>awt.image.redrawrate</code> is interpreted
3476 * as an integer to give the maximum redraw rate, in milliseconds. If
3477 * the system property is missing or cannot be interpreted as an
3478 * integer, the redraw rate is once every 100ms.
3479 * <p>
3480 * The interpretation of the <code>x</code>, <code>y</code>,
3481 * <code>width</code>, and <code>height</code> arguments depends on
3482 * the value of the <code>infoflags</code> argument.
3483 *
3484 * @param img the image being observed
3485 * @param infoflags see <code>imageUpdate</code> for more information
3486 * @param x the <i>x</i> coordinate
3487 * @param y the <i>y</i> coordinate
3488 * @param w the width
3489 * @param h the height
3490 * @return <code>false</code> if the infoflags indicate that the
3491 * image is completely loaded; <code>true</code> otherwise.
3492 *
3493 * @see java.awt.image.ImageObserver
3494 * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver)
3495 * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver)
3496 * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver)
3497 * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver)
3498 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int)
3499 * @since JDK1.0
3500 */
3501 public boolean imageUpdate(Image img, int infoflags,
3502 int x, int y, int w, int h) {
3503 int rate = -1;
3504 if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) {
3505 rate = 0;
3506 } else if ((infoflags & SOMEBITS) != 0) {
3507 if (isInc) {
3508 rate = incRate;
3509 if (rate < 0) {
3510 rate = 0;
3511 }
3512 }
3513 }
3514 if (rate >= 0) {
3515 repaint(rate, 0, 0, width, height);
3516 }
3517 return (infoflags & (ALLBITS|ABORT)) == 0;
3518 }
3519
3520 /**
3521 * Creates an image from the specified image producer.
3522 * @param producer the image producer
3523 * @return the image produced
3524 * @since JDK1.0
3525 */
3526 public Image createImage(ImageProducer producer) {
3527 ComponentPeer peer = this.peer;
3528 if ((peer != null) && ! (peer instanceof LightweightPeer)) {
3529 return peer.createImage(producer);
3530 }
3531 return getToolkit().createImage(producer);
3532 }
3533
3534 /**
3535 * Creates an off-screen drawable image
3536 * to be used for double buffering.
3537 * @param width the specified width
3538 * @param height the specified height
3539 * @return an off-screen drawable image, which can be used for double
3540 * buffering. The return value may be <code>null</code> if the
3541 * component is not displayable. This will always happen if
3542 * <code>GraphicsEnvironment.isHeadless()</code> returns
3543 * <code>true</code>.
3544 * @see #isDisplayable
3545 * @see GraphicsEnvironment#isHeadless
3546 * @since JDK1.0
3547 */
3548 public Image createImage(int width, int height) {
3549 ComponentPeer peer = this.peer;
3550 if (peer instanceof LightweightPeer) {
3551 if (parent != null) { return parent.createImage(width, height); }
3552 else { return null;}
3553 } else {
3554 return (peer != null) ? peer.createImage(width, height) : null;
3555 }
3556 }
3557
3558 /**
3559 * Creates a volatile off-screen drawable image
3560 * to be used for double buffering.
3561 * @param width the specified width.
3562 * @param height the specified height.
3563 * @return an off-screen drawable image, which can be used for double
3564 * buffering. The return value may be <code>null</code> if the
3565 * component is not displayable. This will always happen if
3566 * <code>GraphicsEnvironment.isHeadless()</code> returns
3567 * <code>true</code>.
3568 * @see java.awt.image.VolatileImage
3569 * @see #isDisplayable
3570 * @see GraphicsEnvironment#isHeadless
3571 * @since 1.4
3572 */
3573 public VolatileImage createVolatileImage(int width, int height) {
3574 ComponentPeer peer = this.peer;
3575 if (peer instanceof LightweightPeer) {
3576 if (parent != null) {
3577 return parent.createVolatileImage(width, height);
3578 }
3579 else { return null;}
3580 } else {
3581 return (peer != null) ?
3582 peer.createVolatileImage(width, height) : null;
3583 }
3584 }
3585
3586 /**
3587 * Creates a volatile off-screen drawable image, with the given capabilities.
3588 * The contents of this image may be lost at any time due
3589 * to operating system issues, so the image must be managed
3590 * via the <code>VolatileImage</code> interface.
3591 * @param width the specified width.
3592 * @param height the specified height.
3593 * @param caps the image capabilities
3594 * @exception AWTException if an image with the specified capabilities cannot
3595 * be created
3596 * @return a VolatileImage object, which can be used
3597 * to manage surface contents loss and capabilities.
3598 * @see java.awt.image.VolatileImage
3599 * @since 1.4
3600 */
3601 public VolatileImage createVolatileImage(int width, int height,
3602 ImageCapabilities caps) throws AWTException {
3603 // REMIND : check caps
3604 return createVolatileImage(width, height);
3605 }
3606
3607 /**
3608 * Prepares an image for rendering on this component. The image
3609 * data is downloaded asynchronously in another thread and the
3610 * appropriate screen representation of the image is generated.
3611 * @param image the <code>Image</code> for which to
3612 * prepare a screen representation
3613 * @param observer the <code>ImageObserver</code> object
3614 * to be notified as the image is being prepared
3615 * @return <code>true</code> if the image has already been fully
3616 * prepared; <code>false</code> otherwise
3617 * @since JDK1.0
3618 */
3619 public boolean prepareImage(Image image, ImageObserver observer) {
3620 return prepareImage(image, -1, -1, observer);
3621 }
3622
3623 /**
3624 * Prepares an image for rendering on this component at the
3625 * specified width and height.
3626 * <p>
3627 * The image data is downloaded asynchronously in another thread,
3628 * and an appropriately scaled screen representation of the image is
3629 * generated.
3630 * @param image the instance of <code>Image</code>
3631 * for which to prepare a screen representation
3632 * @param width the width of the desired screen representation
3633 * @param height the height of the desired screen representation
3634 * @param observer the <code>ImageObserver</code> object
3635 * to be notified as the image is being prepared
3636 * @return <code>true</code> if the image has already been fully
3637 * prepared; <code>false</code> otherwise
3638 * @see java.awt.image.ImageObserver
3639 * @since JDK1.0
3640 */
3641 public boolean prepareImage(Image image, int width, int height,
3642 ImageObserver observer) {
3643 ComponentPeer peer = this.peer;
3644 if (peer instanceof LightweightPeer) {
3645 return (parent != null)
3646 ? parent.prepareImage(image, width, height, observer)
3647 : getToolkit().prepareImage(image, width, height, observer);
3648 } else {
3649 return (peer != null)
3650 ? peer.prepareImage(image, width, height, observer)
3651 : getToolkit().prepareImage(image, width, height, observer);
3652 }
3653 }
3654
3655 /**
3656 * Returns the status of the construction of a screen representation
3657 * of the specified image.
3658 * <p>
3659 * This method does not cause the image to begin loading. An
3660 * application must use the <code>prepareImage</code> method
3661 * to force the loading of an image.
3662 * <p>
3663 * Information on the flags returned by this method can be found
3664 * with the discussion of the <code>ImageObserver</code> interface.
3665 * @param image the <code>Image</code> object whose status
3666 * is being checked
3667 * @param observer the <code>ImageObserver</code>
3668 * object to be notified as the image is being prepared
3669 * @return the bitwise inclusive <b>OR</b> of
3670 * <code>ImageObserver</code> flags indicating what
3671 * information about the image is currently available
3672 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3673 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3674 * @see java.awt.image.ImageObserver
3675 * @since JDK1.0
3676 */
3677 public int checkImage(Image image, ImageObserver observer) {
3678 return checkImage(image, -1, -1, observer);
3679 }
3680
3681 /**
3682 * Returns the status of the construction of a screen representation
3683 * of the specified image.
3684 * <p>
3685 * This method does not cause the image to begin loading. An
3686 * application must use the <code>prepareImage</code> method
3687 * to force the loading of an image.
3688 * <p>
3689 * The <code>checkImage</code> method of <code>Component</code>
3690 * calls its peer's <code>checkImage</code> method to calculate
3691 * the flags. If this component does not yet have a peer, the
3692 * component's toolkit's <code>checkImage</code> method is called
3693 * instead.
3694 * <p>
3695 * Information on the flags returned by this method can be found
3696 * with the discussion of the <code>ImageObserver</code> interface.
3697 * @param image the <code>Image</code> object whose status
3698 * is being checked
3699 * @param width the width of the scaled version
3700 * whose status is to be checked
3701 * @param height the height of the scaled version
3702 * whose status is to be checked
3703 * @param observer the <code>ImageObserver</code> object
3704 * to be notified as the image is being prepared
3705 * @return the bitwise inclusive <b>OR</b> of
3706 * <code>ImageObserver</code> flags indicating what
3707 * information about the image is currently available
3708 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver)
3709 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver)
3710 * @see java.awt.image.ImageObserver
3711 * @since JDK1.0
3712 */
3713 public int checkImage(Image image, int width, int height,
3714 ImageObserver observer) {
3715 ComponentPeer peer = this.peer;
3716 if (peer instanceof LightweightPeer) {
3717 return (parent != null)
3718 ? parent.checkImage(image, width, height, observer)
3719 : getToolkit().checkImage(image, width, height, observer);
3720 } else {
3721 return (peer != null)
3722 ? peer.checkImage(image, width, height, observer)
3723 : getToolkit().checkImage(image, width, height, observer);
3724 }
3725 }
3726
3727 /**
3728 * Creates a new strategy for multi-buffering on this component.
3729 * Multi-buffering is useful for rendering performance. This method
3730 * attempts to create the best strategy available with the number of
3731 * buffers supplied. It will always create a <code>BufferStrategy</code>
3732 * with that number of buffers.
3733 * A page-flipping strategy is attempted first, then a blitting strategy
3734 * using accelerated buffers. Finally, an unaccelerated blitting
3735 * strategy is used.
3736 * <p>
3737 * Each time this method is called,
3738 * the existing buffer strategy for this component is discarded.
3739 * @param numBuffers number of buffers to create, including the front buffer
3740 * @exception IllegalArgumentException if numBuffers is less than 1.
3741 * @exception IllegalStateException if the component is not displayable
3742 * @see #isDisplayable
3743 * @see Window#getBufferStrategy()
3744 * @see Canvas#getBufferStrategy()
3745 * @since 1.4
3746 */
3747 void createBufferStrategy(int numBuffers) {
3748 BufferCapabilities bufferCaps;
3749 if (numBuffers > 1) {
3750 // Try to create a page-flipping strategy
3751 bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3752 new ImageCapabilities(true),
3753 BufferCapabilities.FlipContents.UNDEFINED);
3754 try {
3755 createBufferStrategy(numBuffers, bufferCaps);
3756 return; // Success
3757 } catch (AWTException e) {
3758 // Failed
3759 }
3760 }
3761 // Try a blitting (but still accelerated) strategy
3762 bufferCaps = new BufferCapabilities(new ImageCapabilities(true),
3763 new ImageCapabilities(true),
3764 null);
3765 try {
3766 createBufferStrategy(numBuffers, bufferCaps);
3767 return; // Success
3768 } catch (AWTException e) {
3769 // Failed
3770 }
3771 // Try an unaccelerated blitting strategy
3772 bufferCaps = new BufferCapabilities(new ImageCapabilities(false),
3773 new ImageCapabilities(false),
3774 null);
3775 try {
3776 createBufferStrategy(numBuffers, bufferCaps);
3777 return; // Success
3778 } catch (AWTException e) {
3779 // Failed
3780 }
3781 // Code should never reach here (an unaccelerated blitting
3782 // strategy should always work)
3783 throw new InternalError("Could not create a buffer strategy");
3784 }
3785
3786 /**
3787 * Creates a new strategy for multi-buffering on this component with the
3788 * required buffer capabilities. This is useful, for example, if only
3789 * accelerated memory or page flipping is desired (as specified by the
3790 * buffer capabilities).
3791 * <p>
3792 * Each time this method
3793 * is called, <code>dispose</code> will be invoked on the existing
3794 * <code>BufferStrategy</code>.
3795 * @param numBuffers number of buffers to create
3796 * @param caps the required capabilities for creating the buffer strategy;
3797 * cannot be <code>null</code>
3798 * @exception AWTException if the capabilities supplied could not be
3799 * supported or met; this may happen, for example, if there is not enough
3800 * accelerated memory currently available, or if page flipping is specified
3801 * but not possible.
3802 * @exception IllegalArgumentException if numBuffers is less than 1, or if
3803 * caps is <code>null</code>
3804 * @see Window#getBufferStrategy()
3805 * @see Canvas#getBufferStrategy()
3806 * @since 1.4
3807 */
3808 void createBufferStrategy(int numBuffers,
3809 BufferCapabilities caps) throws AWTException {
3810 // Check arguments
3811 if (numBuffers < 1) {
3812 throw new IllegalArgumentException(
3813 "Number of buffers must be at least 1");
3814 }
3815 if (caps == null) {
3816 throw new IllegalArgumentException("No capabilities specified");
3817 }
3818 // Destroy old buffers
3819 if (bufferStrategy != null) {
3820 bufferStrategy.dispose();
3821 }
3822 if (numBuffers == 1) {
3823 bufferStrategy = new SingleBufferStrategy(caps);
3824 } else {
3825 SunGraphicsEnvironment sge = (SunGraphicsEnvironment)
3826 GraphicsEnvironment.getLocalGraphicsEnvironment();
3827 if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) {
3828 caps = new ProxyCapabilities(caps);
3829 }
3830 // assert numBuffers > 1;
3831 if (caps.isPageFlipping()) {
3832 bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps);
3833 } else {
3834 bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps);
3835 }
3836 }
3837 }
3838
3839 /**
3840 * This is a proxy capabilities class used when a FlipBufferStrategy
3841 * is created instead of the requested Blit strategy.
3842 *
3843 * @see sun.awt.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer)
3844 */
3845 private class ProxyCapabilities extends ExtendedBufferCapabilities {
3846 private BufferCapabilities orig;
3847 private ProxyCapabilities(BufferCapabilities orig) {
3848 super(orig.getFrontBufferCapabilities(),
3849 orig.getBackBufferCapabilities(),
3850 orig.getFlipContents() ==
3851 BufferCapabilities.FlipContents.BACKGROUND ?
3852 BufferCapabilities.FlipContents.BACKGROUND :
3853 BufferCapabilities.FlipContents.COPIED);
3854 this.orig = orig;
3855 }
3856 }
3857
3858 /**
3859 * @return the buffer strategy used by this component
3860 * @see Window#createBufferStrategy
3861 * @see Canvas#createBufferStrategy
3862 * @since 1.4
3863 */
3864 BufferStrategy getBufferStrategy() {
3865 return bufferStrategy;
3866 }
3867
3868 /**
3869 * @return the back buffer currently used by this component's
3870 * BufferStrategy. If there is no BufferStrategy or no
3871 * back buffer, this method returns null.
3872 */
3873 Image getBackBuffer() {
3874 if (bufferStrategy != null) {
3875 if (bufferStrategy instanceof BltBufferStrategy) {
3876 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy;
3877 return bltBS.getBackBuffer();
3878 } else if (bufferStrategy instanceof FlipBufferStrategy) {
3879 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy;
3880 return flipBS.getBackBuffer();
3881 }
3882 }
3883 return null;
3884 }
3885
3886 /**
3887 * Inner class for flipping buffers on a component. That component must
3888 * be a <code>Canvas</code> or <code>Window</code>.
3889 * @see Canvas
3890 * @see Window
3891 * @see java.awt.image.BufferStrategy
3892 * @author Michael Martak
3893 * @since 1.4
3894 */
3895 protected class FlipBufferStrategy extends BufferStrategy {
3896 /**
3897 * The number of buffers
3898 */
3899 protected int numBuffers; // = 0
3900 /**
3901 * The buffering capabilities
3902 */
3903 protected BufferCapabilities caps; // = null
3904 /**
3905 * The drawing buffer
3906 */
3907 protected Image drawBuffer; // = null
3908 /**
3909 * The drawing buffer as a volatile image
3910 */
3911 protected VolatileImage drawVBuffer; // = null
3912 /**
3913 * Whether or not the drawing buffer has been recently restored from
3914 * a lost state.
3915 */
3916 protected boolean validatedContents; // = false
3917 /**
3918 * Size of the back buffers. (Note: these fields were added in 6.0
3919 * but kept package-private to avoid exposing them in the spec.
3920 * None of these fields/methods really should have been marked
3921 * protected when they were introduced in 1.4, but now we just have
3922 * to live with that decision.)
3923 */
3924 int width;
3925 int height;
3926
3927 /**
3928 * Creates a new flipping buffer strategy for this component.
3929 * The component must be a <code>Canvas</code> or <code>Window</code>.
3930 * @see Canvas
3931 * @see Window
3932 * @param numBuffers the number of buffers
3933 * @param caps the capabilities of the buffers
3934 * @exception AWTException if the capabilities supplied could not be
3935 * supported or met
3936 * @exception ClassCastException if the component is not a canvas or
3937 * window.
3938 * @exception IllegalStateException if the component has no peer
3939 * @exception IllegalArgumentException if {@code numBuffers} is less than two,
3940 * or if {@code BufferCapabilities.isPageFlipping} is not
3941 * {@code true}.
3942 * @see #createBuffers(int, BufferCapabilities)
3943 */
3944 protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps)
3945 throws AWTException
3946 {
3947 if (!(Component.this instanceof Window) &&
3948 !(Component.this instanceof Canvas))
3949 {
3950 throw new ClassCastException(
3951 "Component must be a Canvas or Window");
3952 }
3953 this.numBuffers = numBuffers;
3954 this.caps = caps;
3955 createBuffers(numBuffers, caps);
3956 }
3957
3958 /**
3959 * Creates one or more complex, flipping buffers with the given
3960 * capabilities.
3961 * @param numBuffers number of buffers to create; must be greater than
3962 * one
3963 * @param caps the capabilities of the buffers.
3964 * <code>BufferCapabilities.isPageFlipping</code> must be
3965 * <code>true</code>.
3966 * @exception AWTException if the capabilities supplied could not be
3967 * supported or met
3968 * @exception IllegalStateException if the component has no peer
3969 * @exception IllegalArgumentException if numBuffers is less than two,
3970 * or if <code>BufferCapabilities.isPageFlipping</code> is not
3971 * <code>true</code>.
3972 * @see java.awt.BufferCapabilities#isPageFlipping()
3973 */
3974 protected void createBuffers(int numBuffers, BufferCapabilities caps)
3975 throws AWTException
3976 {
3977 if (numBuffers < 2) {
3978 throw new IllegalArgumentException(
3979 "Number of buffers cannot be less than two");
3980 } else if (peer == null) {
3981 throw new IllegalStateException(
3982 "Component must have a valid peer");
3983 } else if (caps == null || !caps.isPageFlipping()) {
3984 throw new IllegalArgumentException(
3985 "Page flipping capabilities must be specified");
3986 }
3987
3988 // save the current bounds
3989 width = getWidth();
3990 height = getHeight();
3991
3992 if (drawBuffer != null) {
3993 // dispose the existing backbuffers
3994 drawBuffer = null;
3995 drawVBuffer = null;
3996 destroyBuffers();
3997 // ... then recreate the backbuffers
3998 }
3999
4000 if (caps instanceof ExtendedBufferCapabilities) {
4001 ExtendedBufferCapabilities ebc =
4002 (ExtendedBufferCapabilities)caps;
4003 if (ebc.getVSync() == VSYNC_ON) {
4004 // if this buffer strategy is not allowed to be v-synced,
4005 // change the caps that we pass to the peer but keep on
4006 // trying to create v-synced buffers;
4007 // do not throw IAE here in case it is disallowed, see
4008 // ExtendedBufferCapabilities for more info
4009 if (!VSyncedBSManager.vsyncAllowed(this)) {
4010 caps = ebc.derive(VSYNC_DEFAULT);
4011 }
4012 }
4013 }
4014
4015 peer.createBuffers(numBuffers, caps);
4016 updateInternalBuffers();
4017 }
4018
4019 /**
4020 * Updates internal buffers (both volatile and non-volatile)
4021 * by requesting the back-buffer from the peer.
4022 */
4023 private void updateInternalBuffers() {
4024 // get the images associated with the draw buffer
4025 drawBuffer = getBackBuffer();
4026 if (drawBuffer instanceof VolatileImage) {
4027 drawVBuffer = (VolatileImage)drawBuffer;
4028 } else {
4029 drawVBuffer = null;
4030 }
4031 }
4032
4033 /**
4034 * @return direct access to the back buffer, as an image.
4035 * @exception IllegalStateException if the buffers have not yet
4036 * been created
4037 */
4038 protected Image getBackBuffer() {
4039 if (peer != null) {
4040 return peer.getBackBuffer();
4041 } else {
4042 throw new IllegalStateException(
4043 "Component must have a valid peer");
4044 }
4045 }
4046
4047 /**
4048 * Flipping moves the contents of the back buffer to the front buffer,
4049 * either by copying or by moving the video pointer.
4050 * @param flipAction an integer value describing the flipping action
4051 * for the contents of the back buffer. This should be one of the
4052 * values of the <code>BufferCapabilities.FlipContents</code>
4053 * property.
4054 * @exception IllegalStateException if the buffers have not yet
4055 * been created
4056 * @see java.awt.BufferCapabilities#getFlipContents()
4057 */
4058 protected void flip(BufferCapabilities.FlipContents flipAction) {
4059 if (peer != null) {
4060 Image backBuffer = getBackBuffer();
4061 if (backBuffer != null) {
4062 peer.flip(0, 0,
4063 backBuffer.getWidth(null),
4064 backBuffer.getHeight(null), flipAction);
4065 }
4066 } else {
4067 throw new IllegalStateException(
4068 "Component must have a valid peer");
4069 }
4070 }
4071
4072 void flipSubRegion(int x1, int y1, int x2, int y2,
4073 BufferCapabilities.FlipContents flipAction)
4074 {
4075 if (peer != null) {
4076 peer.flip(x1, y1, x2, y2, flipAction);
4077 } else {
4078 throw new IllegalStateException(
4079 "Component must have a valid peer");
4080 }
4081 }
4082
4083 /**
4084 * Destroys the buffers created through this object
4085 */
4086 protected void destroyBuffers() {
4087 VSyncedBSManager.releaseVsync(this);
4088 if (peer != null) {
4089 peer.destroyBuffers();
4090 } else {
4091 throw new IllegalStateException(
4092 "Component must have a valid peer");
4093 }
4094 }
4095
4096 /**
4097 * @return the buffering capabilities of this strategy
4098 */
4099 public BufferCapabilities getCapabilities() {
4100 if (caps instanceof ProxyCapabilities) {
4101 return ((ProxyCapabilities)caps).orig;
4102 } else {
4103 return caps;
4104 }
4105 }
4106
4107 /**
4108 * @return the graphics on the drawing buffer. This method may not
4109 * be synchronized for performance reasons; use of this method by multiple
4110 * threads should be handled at the application level. Disposal of the
4111 * graphics object must be handled by the application.
4112 */
4113 public Graphics getDrawGraphics() {
4114 revalidate();
4115 return drawBuffer.getGraphics();
4116 }
4117
4118 /**
4119 * Restore the drawing buffer if it has been lost
4120 */
4121 protected void revalidate() {
4122 revalidate(true);
4123 }
4124
4125 void revalidate(boolean checkSize) {
4126 validatedContents = false;
4127
4128 if (checkSize && (getWidth() != width || getHeight() != height)) {
4129 // component has been resized; recreate the backbuffers
4130 try {
4131 createBuffers(numBuffers, caps);
4132 } catch (AWTException e) {
4133 // shouldn't be possible
4134 }
4135 validatedContents = true;
4136 }
4137
4138 // get the buffers from the peer every time since they
4139 // might have been replaced in response to a display change event
4140 updateInternalBuffers();
4141
4142 // now validate the backbuffer
4143 if (drawVBuffer != null) {
4144 GraphicsConfiguration gc =
4145 getGraphicsConfiguration_NoClientCode();
4146 int returnCode = drawVBuffer.validate(gc);
4147 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4148 try {
4149 createBuffers(numBuffers, caps);
4150 } catch (AWTException e) {
4151 // shouldn't be possible
4152 }
4153 if (drawVBuffer != null) {
4154 // backbuffers were recreated, so validate again
4155 drawVBuffer.validate(gc);
4156 }
4157 validatedContents = true;
4158 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4159 validatedContents = true;
4160 }
4161 }
4162 }
4163
4164 /**
4165 * @return whether the drawing buffer was lost since the last call to
4166 * <code>getDrawGraphics</code>
4167 */
4168 public boolean contentsLost() {
4169 if (drawVBuffer == null) {
4170 return false;
4171 }
4172 return drawVBuffer.contentsLost();
4173 }
4174
4175 /**
4176 * @return whether the drawing buffer was recently restored from a lost
4177 * state and reinitialized to the default background color (white)
4178 */
4179 public boolean contentsRestored() {
4180 return validatedContents;
4181 }
4182
4183 /**
4184 * Makes the next available buffer visible by either blitting or
4185 * flipping.
4186 */
4187 public void show() {
4188 flip(caps.getFlipContents());
4189 }
4190
4191 /**
4192 * Makes specified region of the the next available buffer visible
4193 * by either blitting or flipping.
4194 */
4195 void showSubRegion(int x1, int y1, int x2, int y2) {
4196 flipSubRegion(x1, y1, x2, y2, caps.getFlipContents());
4197 }
4198
4199 /**
4200 * {@inheritDoc}
4201 * @since 1.6
4202 */
4203 public void dispose() {
4204 if (Component.this.bufferStrategy == this) {
4205 Component.this.bufferStrategy = null;
4206 if (peer != null) {
4207 destroyBuffers();
4208 }
4209 }
4210 }
4211
4212 } // Inner class FlipBufferStrategy
4213
4214 /**
4215 * Inner class for blitting offscreen surfaces to a component.
4216 *
4217 * @author Michael Martak
4218 * @since 1.4
4219 */
4220 protected class BltBufferStrategy extends BufferStrategy {
4221
4222 /**
4223 * The buffering capabilities
4224 */
4225 protected BufferCapabilities caps; // = null
4226 /**
4227 * The back buffers
4228 */
4229 protected VolatileImage[] backBuffers; // = null
4230 /**
4231 * Whether or not the drawing buffer has been recently restored from
4232 * a lost state.
4233 */
4234 protected boolean validatedContents; // = false
4235 /**
4236 * Size of the back buffers
4237 */
4238 protected int width;
4239 protected int height;
4240
4241 /**
4242 * Insets for the hosting Component. The size of the back buffer
4243 * is constrained by these.
4244 */
4245 private Insets insets;
4246
4247 /**
4248 * Creates a new blt buffer strategy around a component
4249 * @param numBuffers number of buffers to create, including the
4250 * front buffer
4251 * @param caps the capabilities of the buffers
4252 */
4253 protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) {
4254 this.caps = caps;
4255 createBackBuffers(numBuffers - 1);
4256 }
4257
4258 /**
4259 * {@inheritDoc}
4260 * @since 1.6
4261 */
4262 public void dispose() {
4263 if (backBuffers != null) {
4264 for (int counter = backBuffers.length - 1; counter >= 0;
4265 counter--) {
4266 if (backBuffers[counter] != null) {
4267 backBuffers[counter].flush();
4268 backBuffers[counter] = null;
4269 }
4270 }
4271 }
4272 if (Component.this.bufferStrategy == this) {
4273 Component.this.bufferStrategy = null;
4274 }
4275 }
4276
4277 /**
4278 * Creates the back buffers
4279 */
4280 protected void createBackBuffers(int numBuffers) {
4281 if (numBuffers == 0) {
4282 backBuffers = null;
4283 } else {
4284 // save the current bounds
4285 width = getWidth();
4286 height = getHeight();
4287 insets = getInsets_NoClientCode();
4288 int iWidth = width - insets.left - insets.right;
4289 int iHeight = height - insets.top - insets.bottom;
4290
4291 // It is possible for the component's width and/or height
4292 // to be 0 here. Force the size of the backbuffers to
4293 // be > 0 so that creating the image won't fail.
4294 iWidth = Math.max(1, iWidth);
4295 iHeight = Math.max(1, iHeight);
4296 if (backBuffers == null) {
4297 backBuffers = new VolatileImage[numBuffers];
4298 } else {
4299 // flush any existing backbuffers
4300 for (int i = 0; i < numBuffers; i++) {
4301 if (backBuffers[i] != null) {
4302 backBuffers[i].flush();
4303 backBuffers[i] = null;
4304 }
4305 }
4306 }
4307
4308 // create the backbuffers
4309 for (int i = 0; i < numBuffers; i++) {
4310 backBuffers[i] = createVolatileImage(iWidth, iHeight);
4311 }
4312 }
4313 }
4314
4315 /**
4316 * @return the buffering capabilities of this strategy
4317 */
4318 public BufferCapabilities getCapabilities() {
4319 return caps;
4320 }
4321
4322 /**
4323 * @return the draw graphics
4324 */
4325 public Graphics getDrawGraphics() {
4326 revalidate();
4327 Image backBuffer = getBackBuffer();
4328 if (backBuffer == null) {
4329 return getGraphics();
4330 }
4331 SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics();
4332 g.constrain(-insets.left, -insets.top,
4333 backBuffer.getWidth(null) + insets.left,
4334 backBuffer.getHeight(null) + insets.top);
4335 return g;
4336 }
4337
4338 /**
4339 * @return direct access to the back buffer, as an image.
4340 * If there is no back buffer, returns null.
4341 */
4342 Image getBackBuffer() {
4343 if (backBuffers != null) {
4344 return backBuffers[backBuffers.length - 1];
4345 } else {
4346 return null;
4347 }
4348 }
4349
4350 /**
4351 * Makes the next available buffer visible.
4352 */
4353 public void show() {
4354 showSubRegion(insets.left, insets.top,
4355 width - insets.right,
4356 height - insets.bottom);
4357 }
4358
4359 /**
4360 * Package-private method to present a specific rectangular area
4361 * of this buffer. This class currently shows only the entire
4362 * buffer, by calling showSubRegion() with the full dimensions of
4363 * the buffer. Subclasses (e.g., BltSubRegionBufferStrategy
4364 * and FlipSubRegionBufferStrategy) may have region-specific show
4365 * methods that call this method with actual sub regions of the
4366 * buffer.
4367 */
4368 void showSubRegion(int x1, int y1, int x2, int y2) {
4369 if (backBuffers == null) {
4370 return;
4371 }
4372 // Adjust location to be relative to client area.
4373 x1 -= insets.left;
4374 x2 -= insets.left;
4375 y1 -= insets.top;
4376 y2 -= insets.top;
4377 Graphics g = getGraphics_NoClientCode();
4378 if (g == null) {
4379 // Not showing, bail
4380 return;
4381 }
4382 try {
4383 // First image copy is in terms of Frame's coordinates, need
4384 // to translate to client area.
4385 g.translate(insets.left, insets.top);
4386 for (int i = 0; i < backBuffers.length; i++) {
4387 g.drawImage(backBuffers[i],
4388 x1, y1, x2, y2,
4389 x1, y1, x2, y2,
4390 null);
4391 g.dispose();
4392 g = null;
4393 g = backBuffers[i].getGraphics();
4394 }
4395 } finally {
4396 if (g != null) {
4397 g.dispose();
4398 }
4399 }
4400 }
4401
4402 /**
4403 * Restore the drawing buffer if it has been lost
4404 */
4405 protected void revalidate() {
4406 revalidate(true);
4407 }
4408
4409 void revalidate(boolean checkSize) {
4410 validatedContents = false;
4411
4412 if (backBuffers == null) {
4413 return;
4414 }
4415
4416 if (checkSize) {
4417 Insets insets = getInsets_NoClientCode();
4418 if (getWidth() != width || getHeight() != height ||
4419 !insets.equals(this.insets)) {
4420 // component has been resized; recreate the backbuffers
4421 createBackBuffers(backBuffers.length);
4422 validatedContents = true;
4423 }
4424 }
4425
4426 // now validate the backbuffer
4427 GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
4428 int returnCode =
4429 backBuffers[backBuffers.length - 1].validate(gc);
4430 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) {
4431 if (checkSize) {
4432 createBackBuffers(backBuffers.length);
4433 // backbuffers were recreated, so validate again
4434 backBuffers[backBuffers.length - 1].validate(gc);
4435 }
4436 // else case means we're called from Swing on the toolkit
4437 // thread, don't recreate buffers as that'll deadlock
4438 // (creating VolatileImages invokes getting GraphicsConfig
4439 // which grabs treelock).
4440 validatedContents = true;
4441 } else if (returnCode == VolatileImage.IMAGE_RESTORED) {
4442 validatedContents = true;
4443 }
4444 }
4445
4446 /**
4447 * @return whether the drawing buffer was lost since the last call to
4448 * <code>getDrawGraphics</code>
4449 */
4450 public boolean contentsLost() {
4451 if (backBuffers == null) {
4452 return false;
4453 } else {
4454 return backBuffers[backBuffers.length - 1].contentsLost();
4455 }
4456 }
4457
4458 /**
4459 * @return whether the drawing buffer was recently restored from a lost
4460 * state and reinitialized to the default background color (white)
4461 */
4462 public boolean contentsRestored() {
4463 return validatedContents;
4464 }
4465 } // Inner class BltBufferStrategy
4466
4467 /**
4468 * Private class to perform sub-region flipping.
4469 */
4470 private class FlipSubRegionBufferStrategy extends FlipBufferStrategy
4471 implements SubRegionShowable
4472 {
4473
4474 protected FlipSubRegionBufferStrategy(int numBuffers,
4475 BufferCapabilities caps)
4476 throws AWTException
4477 {
4478 super(numBuffers, caps);
4479 }
4480
4481 public void show(int x1, int y1, int x2, int y2) {
4482 showSubRegion(x1, y1, x2, y2);
4483 }
4484
4485 // This is invoked by Swing on the toolkit thread.
4486 public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4487 if (!contentsLost()) {
4488 showSubRegion(x1, y1, x2, y2);
4489 return !contentsLost();
4490 }
4491 return false;
4492 }
4493 }
4494
4495 /**
4496 * Private class to perform sub-region blitting. Swing will use
4497 * this subclass via the SubRegionShowable interface in order to
4498 * copy only the area changed during a repaint.
4499 * @see javax.swing.BufferStrategyPaintManager
4500 */
4501 private class BltSubRegionBufferStrategy extends BltBufferStrategy
4502 implements SubRegionShowable
4503 {
4504
4505 protected BltSubRegionBufferStrategy(int numBuffers,
4506 BufferCapabilities caps)
4507 {
4508 super(numBuffers, caps);
4509 }
4510
4511 public void show(int x1, int y1, int x2, int y2) {
4512 showSubRegion(x1, y1, x2, y2);
4513 }
4514
4515 // This method is called by Swing on the toolkit thread.
4516 public boolean showIfNotLost(int x1, int y1, int x2, int y2) {
4517 if (!contentsLost()) {
4518 showSubRegion(x1, y1, x2, y2);
4519 return !contentsLost();
4520 }
4521 return false;
4522 }
4523 }
4524
4525 /**
4526 * Inner class for flipping buffers on a component. That component must
4527 * be a <code>Canvas</code> or <code>Window</code>.
4528 * @see Canvas
4529 * @see Window
4530 * @see java.awt.image.BufferStrategy
4531 * @author Michael Martak
4532 * @since 1.4
4533 */
4534 private class SingleBufferStrategy extends BufferStrategy {
4535
4536 private BufferCapabilities caps;
4537
4538 public SingleBufferStrategy(BufferCapabilities caps) {
4539 this.caps = caps;
4540 }
4541 public BufferCapabilities getCapabilities() {
4542 return caps;
4543 }
4544 public Graphics getDrawGraphics() {
4545 return getGraphics();
4546 }
4547 public boolean contentsLost() {
4548 return false;
4549 }
4550 public boolean contentsRestored() {
4551 return false;
4552 }
4553 public void show() {
4554 // Do nothing
4555 }
4556 } // Inner class SingleBufferStrategy
4557
4558 /**
4559 * Sets whether or not paint messages received from the operating system
4560 * should be ignored. This does not affect paint events generated in
4561 * software by the AWT, unless they are an immediate response to an
4562 * OS-level paint message.
4563 * <p>
4564 * This is useful, for example, if running under full-screen mode and
4565 * better performance is desired, or if page-flipping is used as the
4566 * buffer strategy.
4567 *
4568 * @since 1.4
4569 * @see #getIgnoreRepaint
4570 * @see Canvas#createBufferStrategy
4571 * @see Window#createBufferStrategy
4572 * @see java.awt.image.BufferStrategy
4573 * @see GraphicsDevice#setFullScreenWindow
4574 */
4575 public void setIgnoreRepaint(boolean ignoreRepaint) {
4576 this.ignoreRepaint = ignoreRepaint;
4577 }
4578
4579 /**
4580 * @return whether or not paint messages received from the operating system
4581 * should be ignored.
4582 *
4583 * @since 1.4
4584 * @see #setIgnoreRepaint
4585 */
4586 public boolean getIgnoreRepaint() {
4587 return ignoreRepaint;
4588 }
4589
4590 /**
4591 * Checks whether this component "contains" the specified point,
4592 * where <code>x</code> and <code>y</code> are defined to be
4593 * relative to the coordinate system of this component.
4594 * @param x the <i>x</i> coordinate of the point
4595 * @param y the <i>y</i> coordinate of the point
4596 * @see #getComponentAt(int, int)
4597 * @since JDK1.1
4598 */
4599 public boolean contains(int x, int y) {
4600 return inside(x, y);
4601 }
4602
4603 /**
4604 * @deprecated As of JDK version 1.1,
4605 * replaced by contains(int, int).
4606 */
4607 @Deprecated
4608 public boolean inside(int x, int y) {
4609 return (x >= 0) && (x < width) && (y >= 0) && (y < height);
4610 }
4611
4612 /**
4613 * Checks whether this component "contains" the specified point,
4614 * where the point's <i>x</i> and <i>y</i> coordinates are defined
4615 * to be relative to the coordinate system of this component.
4616 * @param p the point
4617 * @throws NullPointerException if {@code p} is {@code null}
4618 * @see #getComponentAt(Point)
4619 * @since JDK1.1
4620 */
4621 public boolean contains(Point p) {
4622 return contains(p.x, p.y);
4623 }
4624
4625 /**
4626 * Determines if this component or one of its immediate
4627 * subcomponents contains the (<i>x</i>,&nbsp;<i>y</i>) location,
4628 * and if so, returns the containing component. This method only
4629 * looks one level deep. If the point (<i>x</i>,&nbsp;<i>y</i>) is
4630 * inside a subcomponent that itself has subcomponents, it does not
4631 * go looking down the subcomponent tree.
4632 * <p>
4633 * The <code>locate</code> method of <code>Component</code> simply
4634 * returns the component itself if the (<i>x</i>,&nbsp;<i>y</i>)
4635 * coordinate location is inside its bounding box, and <code>null</code>
4636 * otherwise.
4637 * @param x the <i>x</i> coordinate
4638 * @param y the <i>y</i> coordinate
4639 * @return the component or subcomponent that contains the
4640 * (<i>x</i>,&nbsp;<i>y</i>) location;
4641 * <code>null</code> if the location
4642 * is outside this component
4643 * @see #contains(int, int)
4644 * @since JDK1.0
4645 */
4646 public Component getComponentAt(int x, int y) {
4647 return locate(x, y);
4648 }
4649
4650 /**
4651 * @deprecated As of JDK version 1.1,
4652 * replaced by getComponentAt(int, int).
4653 */
4654 @Deprecated
4655 public Component locate(int x, int y) {
4656 return contains(x, y) ? this : null;
4657 }
4658
4659 /**
4660 * Returns the component or subcomponent that contains the
4661 * specified point.
4662 * @param p the point
4663 * @see java.awt.Component#contains
4664 * @since JDK1.1
4665 */
4666 public Component getComponentAt(Point p) {
4667 return getComponentAt(p.x, p.y);
4668 }
4669
4670 /**
4671 * @deprecated As of JDK version 1.1,
4672 * replaced by <code>dispatchEvent(AWTEvent e)</code>.
4673 */
4674 @Deprecated
4675 public void deliverEvent(Event e) {
4676 postEvent(e);
4677 }
4678
4679 /**
4680 * Dispatches an event to this component or one of its sub components.
4681 * Calls <code>processEvent</code> before returning for 1.1-style
4682 * events which have been enabled for the <code>Component</code>.
4683 * @param e the event
4684 */
4685 public final void dispatchEvent(AWTEvent e) {
4686 dispatchEventImpl(e);
4687 }
4688
4689 void dispatchEventImpl(AWTEvent e) {
4690 int id = e.getID();
4691
4692 // Check that this component belongs to this app-context
4693 AppContext compContext = appContext;
4694 if (compContext != null && !compContext.equals(AppContext.getAppContext())) {
4695 if (eventLog.isLoggable(PlatformLogger.FINE)) {
4696 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext");
4697 }
4698 }
4699
4700 if (eventLog.isLoggable(PlatformLogger.FINEST)) {
4701 eventLog.finest("{0}", e);
4702 }
4703
4704 /*
4705 * 0. Set timestamp and modifiers of current event.
4706 */
4707 EventQueue.setCurrentEventAndMostRecentTime(e);
4708
4709 /*
4710 * 1. Pre-dispatchers. Do any necessary retargeting/reordering here
4711 * before we notify AWTEventListeners.
4712 */
4713
4714 if (e instanceof SunDropTargetEvent) {
4715 ((SunDropTargetEvent)e).dispatch();
4716 return;
4717 }
4718
4719 if (!e.focusManagerIsDispatching) {
4720 // Invoke the private focus retargeting method which provides
4721 // lightweight Component support
4722 if (e.isPosted) {
4723 e = KeyboardFocusManager.retargetFocusEvent(e);
4724 e.isPosted = true;
4725 }
4726
4727 // Now, with the event properly targeted to a lightweight
4728 // descendant if necessary, invoke the public focus retargeting
4729 // and dispatching function
4730 if (KeyboardFocusManager.getCurrentKeyboardFocusManager().
4731 dispatchEvent(e))
4732 {
4733 return;
4734 }
4735 }
4736 if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.FINEST)) {
4737 focusLog.finest("" + e);
4738 }
4739 // MouseWheel may need to be retargeted here so that
4740 // AWTEventListener sees the event go to the correct
4741 // Component. If the MouseWheelEvent needs to go to an ancestor,
4742 // the event is dispatched to the ancestor, and dispatching here
4743 // stops.
4744 if (id == MouseEvent.MOUSE_WHEEL &&
4745 (!eventTypeEnabled(id)) &&
4746 (peer != null && !peer.handlesWheelScrolling()) &&
4747 (dispatchMouseWheelToAncestor((MouseWheelEvent)e)))
4748 {
4749 return;
4750 }
4751
4752 /*
4753 * 2. Allow the Toolkit to pass this to AWTEventListeners.
4754 */
4755 Toolkit toolkit = Toolkit.getDefaultToolkit();
4756 toolkit.notifyAWTEventListeners(e);
4757
4758
4759 /*
4760 * 3. If no one has consumed a key event, allow the
4761 * KeyboardFocusManager to process it.
4762 */
4763 if (!e.isConsumed()) {
4764 if (e instanceof java.awt.event.KeyEvent) {
4765 KeyboardFocusManager.getCurrentKeyboardFocusManager().
4766 processKeyEvent(this, (KeyEvent)e);
4767 if (e.isConsumed()) {
4768 return;
4769 }
4770 }
4771 }
4772
4773 /*
4774 * 4. Allow input methods to process the event
4775 */
4776 if (areInputMethodsEnabled()) {
4777 // We need to pass on InputMethodEvents since some host
4778 // input method adapters send them through the Java
4779 // event queue instead of directly to the component,
4780 // and the input context also handles the Java composition window
4781 if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea))
4782 ||
4783 // Otherwise, we only pass on input and focus events, because
4784 // a) input methods shouldn't know about semantic or component-level events
4785 // b) passing on the events takes time
4786 // c) isConsumed() is always true for semantic events.
4787 (e instanceof InputEvent) || (e instanceof FocusEvent)) {
4788 InputContext inputContext = getInputContext();
4789
4790
4791 if (inputContext != null) {
4792 inputContext.dispatchEvent(e);
4793 if (e.isConsumed()) {
4794 if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.FINEST)) {
4795 focusLog.finest("3579: Skipping " + e);
4796 }
4797 return;
4798 }
4799 }
4800 }
4801 } else {
4802 // When non-clients get focus, we need to explicitly disable the native
4803 // input method. The native input method is actually not disabled when
4804 // the active/passive/peered clients loose focus.
4805 if (id == FocusEvent.FOCUS_GAINED) {
4806 InputContext inputContext = getInputContext();
4807 if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) {
4808 ((sun.awt.im.InputContext)inputContext).disableNativeIM();
4809 }
4810 }
4811 }
4812
4813
4814 /*
4815 * 5. Pre-process any special events before delivery
4816 */
4817 switch(id) {
4818 // Handling of the PAINT and UPDATE events is now done in the
4819 // peer's handleEvent() method so the background can be cleared
4820 // selectively for non-native components on Windows only.
4821 // - Fred.Ecks@Eng.sun.com, 5-8-98
4822
4823 case KeyEvent.KEY_PRESSED:
4824 case KeyEvent.KEY_RELEASED:
4825 Container p = (Container)((this instanceof Container) ? this : parent);
4826 if (p != null) {
4827 p.preProcessKeyEvent((KeyEvent)e);
4828 if (e.isConsumed()) {
4829 if (focusLog.isLoggable(PlatformLogger.FINEST)) {
4830 focusLog.finest("Pre-process consumed event");
4831 }
4832 return;
4833 }
4834 }
4835 break;
4836
4837 case WindowEvent.WINDOW_CLOSING:
4838 if (toolkit instanceof WindowClosingListener) {
4839 windowClosingException = ((WindowClosingListener)
4840 toolkit).windowClosingNotify((WindowEvent)e);
4841 if (checkWindowClosingException()) {
4842 return;
4843 }
4844 }
4845 break;
4846
4847 default:
4848 break;
4849 }
4850
4851 /*
4852 * 6. Deliver event for normal processing
4853 */
4854 if (newEventsOnly) {
4855 // Filtering needs to really be moved to happen at a lower
4856 // level in order to get maximum performance gain; it is
4857 // here temporarily to ensure the API spec is honored.
4858 //
4859 if (eventEnabled(e)) {
4860 processEvent(e);
4861 }
4862 } else if (id == MouseEvent.MOUSE_WHEEL) {
4863 // newEventsOnly will be false for a listenerless ScrollPane, but
4864 // MouseWheelEvents still need to be dispatched to it so scrolling
4865 // can be done.
4866 autoProcessMouseWheel((MouseWheelEvent)e);
4867 } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) {
4868 //
4869 // backward compatibility
4870 //
4871 Event olde = e.convertToOld();
4872 if (olde != null) {
4873 int key = olde.key;
4874 int modifiers = olde.modifiers;
4875
4876 postEvent(olde);
4877 if (olde.isConsumed()) {
4878 e.consume();
4879 }
4880 // if target changed key or modifier values, copy them
4881 // back to original event
4882 //
4883 switch(olde.id) {
4884 case Event.KEY_PRESS:
4885 case Event.KEY_RELEASE:
4886 case Event.KEY_ACTION:
4887 case Event.KEY_ACTION_RELEASE:
4888 if (olde.key != key) {
4889 ((KeyEvent)e).setKeyChar(olde.getKeyEventChar());
4890 }
4891 if (olde.modifiers != modifiers) {
4892 ((KeyEvent)e).setModifiers(olde.modifiers);
4893 }
4894 break;
4895 default:
4896 break;
4897 }
4898 }
4899 }
4900
4901 /*
4902 * 8. Special handling for 4061116 : Hook for browser to close modal
4903 * dialogs.
4904 */
4905 if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) {
4906 if (toolkit instanceof WindowClosingListener) {
4907 windowClosingException =
4908 ((WindowClosingListener)toolkit).
4909 windowClosingDelivered((WindowEvent)e);
4910 if (checkWindowClosingException()) {
4911 return;
4912 }
4913 }
4914 }
4915
4916 /*
4917 * 9. Allow the peer to process the event.
4918 * Except KeyEvents, they will be processed by peer after
4919 * all KeyEventPostProcessors
4920 * (see DefaultKeyboardFocusManager.dispatchKeyEvent())
4921 */
4922 if (!(e instanceof KeyEvent)) {
4923 ComponentPeer tpeer = peer;
4924 if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) {
4925 // if focus owner is lightweight then its native container
4926 // processes event
4927 Component source = (Component)e.getSource();
4928 if (source != null) {
4929 Container target = source.getNativeContainer();
4930 if (target != null) {
4931 tpeer = target.getPeer();
4932 }
4933 }
4934 }
4935 if (tpeer != null) {
4936 tpeer.handleEvent(e);
4937 }
4938 }
4939 } // dispatchEventImpl()
4940
4941 /*
4942 * If newEventsOnly is false, method is called so that ScrollPane can
4943 * override it and handle common-case mouse wheel scrolling. NOP
4944 * for Component.
4945 */
4946 void autoProcessMouseWheel(MouseWheelEvent e) {}
4947
4948 /*
4949 * Dispatch given MouseWheelEvent to the first ancestor for which
4950 * MouseWheelEvents are enabled.
4951 *
4952 * Returns whether or not event was dispatched to an ancestor
4953 */
4954 boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
4955 int newX, newY;
4956 newX = e.getX() + getX(); // Coordinates take into account at least
4957 newY = e.getY() + getY(); // the cursor's position relative to this
4958 // Component (e.getX()), and this Component's
4959 // position relative to its parent.
4960 MouseWheelEvent newMWE;
4961
4962 if (eventLog.isLoggable(PlatformLogger.FINEST)) {
4963 eventLog.finest("dispatchMouseWheelToAncestor");
4964 eventLog.finest("orig event src is of " + e.getSource().getClass());
4965 }
4966
4967 /* parent field for Window refers to the owning Window.
4968 * MouseWheelEvents should NOT be propagated into owning Windows
4969 */
4970 synchronized (getTreeLock()) {
4971 Container anc = getParent();
4972 while (anc != null && !anc.eventEnabled(e)) {
4973 // fix coordinates to be relative to new event source
4974 newX += anc.getX();
4975 newY += anc.getY();
4976
4977 if (!(anc instanceof Window)) {
4978 anc = anc.getParent();
4979 }
4980 else {
4981 break;
4982 }
4983 }
4984
4985 if (eventLog.isLoggable(PlatformLogger.FINEST)) {
4986 eventLog.finest("new event src is " + anc.getClass());
4987 }
4988
4989 if (anc != null && anc.eventEnabled(e)) {
4990 // Change event to be from new source, with new x,y
4991 // For now, just create a new event - yucky
4992
4993 newMWE = new MouseWheelEvent(anc, // new source
4994 e.getID(),
4995 e.getWhen(),
4996 e.getModifiers(),
4997 newX, // x relative to new source
4998 newY, // y relative to new source
4999 e.getXOnScreen(),

5100 more lines aren’t shown here.