1 /* 2 * Copyright 1995-2009 Sun Microsystems, Inc. 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. Sun designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 22 * CA 95054 USA or visit www.sun.com if you need additional information or 23 * have any questions. 24 */ 25 package java.awt; 26 27 import java.io.PrintStream; 28 import java.io.PrintWriter; 29 import java.util.Vector; 30 import java.util.Locale; 31 import java.util.EventListener; 32 import java.util.Iterator; 33 import java.util.HashSet; 34 import java.util.Map; 35 import java.util.Set; 36 import java.util.Collections; 37 import java.awt.peer.ComponentPeer; 38 import java.awt.peer.ContainerPeer; 39 import java.awt.peer.LightweightPeer; 40 import java.awt.image.BufferStrategy; 41 import java.awt.image.ImageObserver; 42 import java.awt.image.ImageProducer; 43 import java.awt.image.ColorModel; 44 import java.awt.image.VolatileImage; 45 import java.awt.event.*; 46 import java.io.Serializable; 47 import java.io.ObjectOutputStream; 48 import java.io.ObjectInputStream; 49 import java.io.IOException; 50 import java.beans.PropertyChangeListener; 51 import java.beans.PropertyChangeSupport; 52 import java.beans.Transient; 53 import java.awt.event.InputMethodListener; 54 import java.awt.event.InputMethodEvent; 55 import java.awt.im.InputContext; 56 import java.awt.im.InputMethodRequests; 57 import java.awt.dnd.DropTarget; 58 import java.lang.reflect.InvocationTargetException; 59 import java.lang.reflect.Method; 60 import java.security.AccessController; 61 import java.security.PrivilegedAction; 62 import javax.accessibility.*; 63 import java.util.logging.*; 64 import java.applet.Applet; 65 66 import sun.security.action.GetPropertyAction; 67 import sun.awt.AppContext; 68 import sun.awt.AWTAccessor; 69 import sun.awt.ConstrainableGraphics; 70 import sun.awt.SubRegionShowable; 71 import sun.awt.SunToolkit; 72 import sun.awt.WindowClosingListener; 73 import sun.awt.CausedFocusEvent; 74 import sun.awt.EmbeddedFrame; 75 import sun.awt.dnd.SunDropTargetEvent; 76 import sun.awt.im.CompositionArea; 77 import sun.java2d.SunGraphics2D; 78 import sun.java2d.pipe.Region; 79 import sun.awt.image.VSyncedBSManager; 80 import sun.java2d.pipe.hw.ExtendedBufferCapabilities; 81 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*; 82 import sun.awt.RequestFocusController; 83 import sun.java2d.SunGraphicsEnvironment; 84 85 /** 86 * A <em>component</em> is an object having a graphical representation 87 * that can be displayed on the screen and that can interact with the 88 * user. Examples of components are the buttons, checkboxes, and scrollbars 89 * of a typical graphical user interface. <p> 90 * The <code>Component</code> class is the abstract superclass of 91 * the nonmenu-related Abstract Window Toolkit components. Class 92 * <code>Component</code> can also be extended directly to create a 93 * lightweight component. A lightweight component is a component that is 94 * not associated with a native opaque window. 95 * <p> 96 * <h3>Serialization</h3> 97 * It is important to note that only AWT listeners which conform 98 * to the <code>Serializable</code> protocol will be saved when 99 * the object is stored. If an AWT object has listeners that 100 * aren't marked serializable, they will be dropped at 101 * <code>writeObject</code> time. Developers will need, as always, 102 * to consider the implications of making an object serializable. 103 * One situation to watch out for is this: 104 * <pre> 105 * import java.awt.*; 106 * import java.awt.event.*; 107 * import java.io.Serializable; 108 * 109 * class MyApp implements ActionListener, Serializable 110 * { 111 * BigObjectThatShouldNotBeSerializedWithAButton bigOne; 112 * Button aButton = new Button(); 113 * 114 * MyApp() 115 * { 116 * // Oops, now aButton has a listener with a reference 117 * // to bigOne! 118 * aButton.addActionListener(this); 119 * } 120 * 121 * public void actionPerformed(ActionEvent e) 122 * { 123 * System.out.println("Hello There"); 124 * } 125 * } 126 * </pre> 127 * In this example, serializing <code>aButton</code> by itself 128 * will cause <code>MyApp</code> and everything it refers to 129 * to be serialized as well. The problem is that the listener 130 * is serializable by coincidence, not by design. To separate 131 * the decisions about <code>MyApp</code> and the 132 * <code>ActionListener</code> being serializable one can use a 133 * nested class, as in the following example: 134 * <pre> 135 * import java.awt.*; 136 * import java.awt.event.*; 137 * import java.io.Serializable; 138 * 139 * class MyApp java.io.Serializable 140 * { 141 * BigObjectThatShouldNotBeSerializedWithAButton bigOne; 142 * Button aButton = new Button(); 143 * 144 * static class MyActionListener implements ActionListener 145 * { 146 * public void actionPerformed(ActionEvent e) 147 * { 148 * System.out.println("Hello There"); 149 * } 150 * } 151 * 152 * MyApp() 153 * { 154 * aButton.addActionListener(new MyActionListener()); 155 * } 156 * } 157 * </pre> 158 * <p> 159 * <b>Note</b>: For more information on the paint mechanisms utilitized 160 * by AWT and Swing, including information on how to write the most 161 * efficient painting code, see 162 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 163 * <p> 164 * For details on the focus subsystem, see 165 * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html"> 166 * How to Use the Focus Subsystem</a>, 167 * a section in <em>The Java Tutorial</em>, and the 168 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 169 * for more information. 170 * 171 * @author Arthur van Hoff 172 * @author Sami Shaio 173 */ 174 public abstract class Component implements ImageObserver, MenuContainer, 175 Serializable 176 { 177 178 private static final Logger log = Logger.getLogger("java.awt.Component"); 179 private static final Logger eventLog = Logger.getLogger("java.awt.event.Component"); 180 private static final Logger focusLog = Logger.getLogger("java.awt.focus.Component"); 181 private static final Logger mixingLog = Logger.getLogger("java.awt.mixing.Component"); 182 183 /** 184 * The peer of the component. The peer implements the component's 185 * behavior. The peer is set when the <code>Component</code> is 186 * added to a container that also is a peer. 187 * @see #addNotify 188 * @see #removeNotify 189 */ 190 transient ComponentPeer peer; 191 192 /** 193 * The parent of the object. It may be <code>null</code> 194 * for top-level components. 195 * @see #getParent 196 */ 197 transient Container parent; 198 199 /** 200 * The <code>AppContext</code> of the component. Applets/Plugin may 201 * change the AppContext. 202 */ 203 transient AppContext appContext; 204 205 /** 206 * The x position of the component in the parent's coordinate system. 207 * 208 * @serial 209 * @see #getLocation 210 */ 211 int x; 212 213 /** 214 * The y position of the component in the parent's coordinate system. 215 * 216 * @serial 217 * @see #getLocation 218 */ 219 int y; 220 221 /** 222 * The width of the component. 223 * 224 * @serial 225 * @see #getSize 226 */ 227 int width; 228 229 /** 230 * The height of the component. 231 * 232 * @serial 233 * @see #getSize 234 */ 235 int height; 236 237 /** 238 * The foreground color for this component. 239 * <code>foreground</code> can be <code>null</code>. 240 * 241 * @serial 242 * @see #getForeground 243 * @see #setForeground 244 */ 245 Color foreground; 246 247 /** 248 * The background color for this component. 249 * <code>background</code> can be <code>null</code>. 250 * 251 * @serial 252 * @see #getBackground 253 * @see #setBackground 254 */ 255 Color background; 256 257 /** 258 * The font used by this component. 259 * The <code>font</code> can be <code>null</code>. 260 * 261 * @serial 262 * @see #getFont 263 * @see #setFont 264 */ 265 Font font; 266 267 /** 268 * The font which the peer is currently using. 269 * (<code>null</code> if no peer exists.) 270 */ 271 Font peerFont; 272 273 /** 274 * The cursor displayed when pointer is over this component. 275 * This value can be <code>null</code>. 276 * 277 * @serial 278 * @see #getCursor 279 * @see #setCursor 280 */ 281 Cursor cursor; 282 283 /** 284 * The locale for the component. 285 * 286 * @serial 287 * @see #getLocale 288 * @see #setLocale 289 */ 290 Locale locale; 291 292 /** 293 * A reference to a <code>GraphicsConfiguration</code> object 294 * used to describe the characteristics of a graphics 295 * destination. 296 * This value can be <code>null</code>. 297 * 298 * @since 1.3 299 * @serial 300 * @see GraphicsConfiguration 301 * @see #getGraphicsConfiguration 302 */ 303 private transient GraphicsConfiguration graphicsConfig = null; 304 305 /** 306 * A reference to a <code>BufferStrategy</code> object 307 * used to manipulate the buffers on this component. 308 * 309 * @since 1.4 310 * @see java.awt.image.BufferStrategy 311 * @see #getBufferStrategy() 312 */ 313 transient BufferStrategy bufferStrategy = null; 314 315 /** 316 * True when the object should ignore all repaint events. 317 * 318 * @since 1.4 319 * @serial 320 * @see #setIgnoreRepaint 321 * @see #getIgnoreRepaint 322 */ 323 boolean ignoreRepaint = false; 324 325 /** 326 * True when the object is visible. An object that is not 327 * visible is not drawn on the screen. 328 * 329 * @serial 330 * @see #isVisible 331 * @see #setVisible 332 */ 333 boolean visible = true; 334 335 /** 336 * True when the object is enabled. An object that is not 337 * enabled does not interact with the user. 338 * 339 * @serial 340 * @see #isEnabled 341 * @see #setEnabled 342 */ 343 boolean enabled = true; 344 345 /** 346 * True when the object is valid. An invalid object needs to 347 * be layed out. This flag is set to false when the object 348 * size is changed. 349 * 350 * @serial 351 * @see #isValid 352 * @see #validate 353 * @see #invalidate 354 */ 355 private volatile boolean valid = false; 356 357 /** 358 * The <code>DropTarget</code> associated with this component. 359 * 360 * @since 1.2 361 * @serial 362 * @see #setDropTarget 363 * @see #getDropTarget 364 */ 365 DropTarget dropTarget; 366 367 /** 368 * @serial 369 * @see #add 370 */ 371 Vector popups; 372 373 /** 374 * A component's name. 375 * This field can be <code>null</code>. 376 * 377 * @serial 378 * @see #getName 379 * @see #setName(String) 380 */ 381 private String name; 382 383 /** 384 * A bool to determine whether the name has 385 * been set explicitly. <code>nameExplicitlySet</code> will 386 * be false if the name has not been set and 387 * true if it has. 388 * 389 * @serial 390 * @see #getName 391 * @see #setName(String) 392 */ 393 private boolean nameExplicitlySet = false; 394 395 /** 396 * Indicates whether this Component can be focused. 397 * 398 * @serial 399 * @see #setFocusable 400 * @see #isFocusable 401 * @since 1.4 402 */ 403 private boolean focusable = true; 404 405 private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0; 406 private static final int FOCUS_TRAVERSABLE_DEFAULT = 1; 407 private static final int FOCUS_TRAVERSABLE_SET = 2; 408 409 /** 410 * Tracks whether this Component is relying on default focus travesability. 411 * 412 * @serial 413 * @since 1.4 414 */ 415 private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; 416 417 /** 418 * The focus traversal keys. These keys will generate focus traversal 419 * behavior for Components for which focus traversal keys are enabled. If a 420 * value of null is specified for a traversal key, this Component inherits 421 * that traversal key from its parent. If all ancestors of this Component 422 * have null specified for that traversal key, then the current 423 * KeyboardFocusManager's default traversal key is used. 424 * 425 * @serial 426 * @see #setFocusTraversalKeys 427 * @see #getFocusTraversalKeys 428 * @since 1.4 429 */ 430 Set[] focusTraversalKeys; 431 432 private static final String[] focusTraversalKeyPropertyNames = { 433 "forwardFocusTraversalKeys", 434 "backwardFocusTraversalKeys", 435 "upCycleFocusTraversalKeys", 436 "downCycleFocusTraversalKeys" 437 }; 438 439 /** 440 * Indicates whether focus traversal keys are enabled for this Component. 441 * Components for which focus traversal keys are disabled receive key 442 * events for focus traversal keys. Components for which focus traversal 443 * keys are enabled do not see these events; instead, the events are 444 * automatically converted to traversal operations. 445 * 446 * @serial 447 * @see #setFocusTraversalKeysEnabled 448 * @see #getFocusTraversalKeysEnabled 449 * @since 1.4 450 */ 451 private boolean focusTraversalKeysEnabled = true; 452 453 /** 454 * The locking object for AWT component-tree and layout operations. 455 * 456 * @see #getTreeLock 457 */ 458 static final Object LOCK = new AWTTreeLock(); 459 static class AWTTreeLock {} 460 461 /** 462 * Minimum size. 463 * (This field perhaps should have been transient). 464 * 465 * @serial 466 */ 467 Dimension minSize; 468 469 /** 470 * Whether or not setMinimumSize has been invoked with a non-null value. 471 */ 472 boolean minSizeSet; 473 474 /** 475 * Preferred size. 476 * (This field perhaps should have been transient). 477 * 478 * @serial 479 */ 480 Dimension prefSize; 481 482 /** 483 * Whether or not setPreferredSize has been invoked with a non-null value. 484 */ 485 boolean prefSizeSet; 486 487 /** 488 * Maximum size 489 * 490 * @serial 491 */ 492 Dimension maxSize; 493 494 /** 495 * Whether or not setMaximumSize has been invoked with a non-null value. 496 */ 497 boolean maxSizeSet; 498 499 /** 500 * The orientation for this component. 501 * @see #getComponentOrientation 502 * @see #setComponentOrientation 503 */ 504 transient ComponentOrientation componentOrientation 505 = ComponentOrientation.UNKNOWN; 506 507 /** 508 * <code>newEventsOnly</code> will be true if the event is 509 * one of the event types enabled for the component. 510 * It will then allow for normal processing to 511 * continue. If it is false the event is passed 512 * to the component's parent and up the ancestor 513 * tree until the event has been consumed. 514 * 515 * @serial 516 * @see #dispatchEvent 517 */ 518 boolean newEventsOnly = false; 519 transient ComponentListener componentListener; 520 transient FocusListener focusListener; 521 transient HierarchyListener hierarchyListener; 522 transient HierarchyBoundsListener hierarchyBoundsListener; 523 transient KeyListener keyListener; 524 transient MouseListener mouseListener; 525 transient MouseMotionListener mouseMotionListener; 526 transient MouseWheelListener mouseWheelListener; 527 transient InputMethodListener inputMethodListener; 528 529 transient RuntimeException windowClosingException = null; 530 531 /** Internal, constants for serialization */ 532 final static String actionListenerK = "actionL"; 533 final static String adjustmentListenerK = "adjustmentL"; 534 final static String componentListenerK = "componentL"; 535 final static String containerListenerK = "containerL"; 536 final static String focusListenerK = "focusL"; 537 final static String itemListenerK = "itemL"; 538 final static String keyListenerK = "keyL"; 539 final static String mouseListenerK = "mouseL"; 540 final static String mouseMotionListenerK = "mouseMotionL"; 541 final static String mouseWheelListenerK = "mouseWheelL"; 542 final static String textListenerK = "textL"; 543 final static String ownedWindowK = "ownedL"; 544 final static String windowListenerK = "windowL"; 545 final static String inputMethodListenerK = "inputMethodL"; 546 final static String hierarchyListenerK = "hierarchyL"; 547 final static String hierarchyBoundsListenerK = "hierarchyBoundsL"; 548 final static String windowStateListenerK = "windowStateL"; 549 final static String windowFocusListenerK = "windowFocusL"; 550 551 /** 552 * The <code>eventMask</code> is ONLY set by subclasses via 553 * <code>enableEvents</code>. 554 * The mask should NOT be set when listeners are registered 555 * so that we can distinguish the difference between when 556 * listeners request events and subclasses request them. 557 * One bit is used to indicate whether input methods are 558 * enabled; this bit is set by <code>enableInputMethods</code> and is 559 * on by default. 560 * 561 * @serial 562 * @see #enableInputMethods 563 * @see AWTEvent 564 */ 565 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK; 566 567 /** 568 * Static properties for incremental drawing. 569 * @see #imageUpdate 570 */ 571 static boolean isInc; 572 static int incRate; 573 static { 574 /* ensure that the necessary native libraries are loaded */ 575 Toolkit.loadLibraries(); 576 /* initialize JNI field and method ids */ 577 if (!GraphicsEnvironment.isHeadless()) { 578 initIDs(); 579 } 580 581 String s = (String) java.security.AccessController.doPrivileged( 582 new GetPropertyAction("awt.image.incrementaldraw")); 583 isInc = (s == null || s.equals("true")); 584 585 s = (String) java.security.AccessController.doPrivileged( 586 new GetPropertyAction("awt.image.redrawrate")); 587 incRate = (s != null) ? Integer.parseInt(s) : 100; 588 } 589 590 /** 591 * Ease-of-use constant for <code>getAlignmentY()</code>. 592 * Specifies an alignment to the top of the component. 593 * @see #getAlignmentY 594 */ 595 public static final float TOP_ALIGNMENT = 0.0f; 596 597 /** 598 * Ease-of-use constant for <code>getAlignmentY</code> and 599 * <code>getAlignmentX</code>. Specifies an alignment to 600 * the center of the component 601 * @see #getAlignmentX 602 * @see #getAlignmentY 603 */ 604 public static final float CENTER_ALIGNMENT = 0.5f; 605 606 /** 607 * Ease-of-use constant for <code>getAlignmentY</code>. 608 * Specifies an alignment to the bottom of the component. 609 * @see #getAlignmentY 610 */ 611 public static final float BOTTOM_ALIGNMENT = 1.0f; 612 613 /** 614 * Ease-of-use constant for <code>getAlignmentX</code>. 615 * Specifies an alignment to the left side of the component. 616 * @see #getAlignmentX 617 */ 618 public static final float LEFT_ALIGNMENT = 0.0f; 619 620 /** 621 * Ease-of-use constant for <code>getAlignmentX</code>. 622 * Specifies an alignment to the right side of the component. 623 * @see #getAlignmentX 624 */ 625 public static final float RIGHT_ALIGNMENT = 1.0f; 626 627 /* 628 * JDK 1.1 serialVersionUID 629 */ 630 private static final long serialVersionUID = -7644114512714619750L; 631 632 /** 633 * If any <code>PropertyChangeListeners</code> have been registered, 634 * the <code>changeSupport</code> field describes them. 635 * 636 * @serial 637 * @since 1.2 638 * @see #addPropertyChangeListener 639 * @see #removePropertyChangeListener 640 * @see #firePropertyChange 641 */ 642 private PropertyChangeSupport changeSupport; 643 644 /* 645 * In some cases using "this" as an object to synchronize by 646 * can lead to a deadlock if client code also uses synchronization 647 * by a component object. For every such situation revealed we should 648 * consider possibility of replacing "this" with the package private 649 * objectLock object introduced below. So far there're 2 issues known: 650 * - CR 6708322 (the getName/setName methods); 651 * - CR 6608764 (the PropertyChangeListener machinery). 652 * 653 * Note: this field is considered final, though readObject() prohibits 654 * initializing final fields. 655 */ 656 private transient Object objectLock = new Object(); 657 Object getObjectLock() { 658 return objectLock; 659 } 660 661 boolean isPacked = false; 662 663 /** 664 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize 665 * to signal setBounds what's changing. Should be used under TreeLock. 666 * This is only needed due to the inability to change the cross-calling 667 * order of public and deprecated methods. 668 */ 669 private int boundsOp = ComponentPeer.DEFAULT_OPERATION; 670 671 /** 672 * Enumeration of the common ways the baseline of a component can 673 * change as the size changes. The baseline resize behavior is 674 * primarily for layout managers that need to know how the 675 * position of the baseline changes as the component size changes. 676 * In general the baseline resize behavior will be valid for sizes 677 * greater than or equal to the minimum size (the actual minimum 678 * size; not a developer specified minimum size). For sizes 679 * smaller than the minimum size the baseline may change in a way 680 * other than the baseline resize behavior indicates. Similarly, 681 * as the size approaches <code>Integer.MAX_VALUE</code> and/or 682 * <code>Short.MAX_VALUE</code> the baseline may change in a way 683 * other than the baseline resize behavior indicates. 684 * 685 * @see #getBaselineResizeBehavior 686 * @see #getBaseline(int,int) 687 * @since 1.6 688 */ 689 public enum BaselineResizeBehavior { 690 /** 691 * Indicates the baseline remains fixed relative to the 692 * y-origin. That is, <code>getBaseline</code> returns 693 * the same value regardless of the height or width. For example, a 694 * <code>JLabel</code> containing non-empty text with a 695 * vertical alignment of <code>TOP</code> should have a 696 * baseline type of <code>CONSTANT_ASCENT</code>. 697 */ 698 CONSTANT_ASCENT, 699 700 /** 701 * Indicates the baseline remains fixed relative to the height 702 * and does not change as the width is varied. That is, for 703 * any height H the difference between H and 704 * <code>getBaseline(w, H)</code> is the same. For example, a 705 * <code>JLabel</code> containing non-empty text with a 706 * vertical alignment of <code>BOTTOM</code> should have a 707 * baseline type of <code>CONSTANT_DESCENT</code>. 708 */ 709 CONSTANT_DESCENT, 710 711 /** 712 * Indicates the baseline remains a fixed distance from 713 * the center of the component. That is, for any height H the 714 * difference between <code>getBaseline(w, H)</code> and 715 * <code>H / 2</code> is the same (plus or minus one depending upon 716 * rounding error). 717 * <p> 718 * Because of possible rounding errors it is recommended 719 * you ask for the baseline with two consecutive heights and use 720 * the return value to determine if you need to pad calculations 721 * by 1. The following shows how to calculate the baseline for 722 * any height: 723 * <pre> 724 * Dimension preferredSize = component.getPreferredSize(); 725 * int baseline = getBaseline(preferredSize.width, 726 * preferredSize.height); 727 * int nextBaseline = getBaseline(preferredSize.width, 728 * preferredSize.height + 1); 729 * // Amount to add to height when calculating where baseline 730 * // lands for a particular height: 731 * int padding = 0; 732 * // Where the baseline is relative to the mid point 733 * int baselineOffset = baseline - height / 2; 734 * if (preferredSize.height % 2 == 0 && 735 * baseline != nextBaseline) { 736 * padding = 1; 737 * } 738 * else if (preferredSize.height % 2 == 1 && 739 * baseline == nextBaseline) { 740 * baselineOffset--; 741 * padding = 1; 742 * } 743 * // The following calculates where the baseline lands for 744 * // the height z: 745 * int calculatedBaseline = (z + padding) / 2 + baselineOffset; 746 * </pre> 747 */ 748 CENTER_OFFSET, 749 750 /** 751 * Indicates the baseline resize behavior can not be expressed using 752 * any of the other constants. This may also indicate the baseline 753 * varies with the width of the component. This is also returned 754 * by components that do not have a baseline. 755 */ 756 OTHER 757 } 758 759 /* 760 * The shape set with the applyCompoundShape() method. It uncludes the result 761 * of the HW/LW mixing related shape computation. It may also include 762 * the user-specified shape of the component. 763 * The 'null' value means the component has normal shape (or has no shape at all) 764 * and applyCompoundShape() will skip the following shape identical to normal. 765 */ 766 private transient Region compoundShape = null; 767 768 /* 769 * Represents the shape of this lightweight component to be cut out from 770 * heavyweight components should they intersect. Possible values: 771 * 1. null - consider the shape rectangular 772 * 2. EMPTY_REGION - nothing gets cut out (children still get cut out) 773 * 3. non-empty - this shape gets cut out. 774 */ 775 private transient Region mixingCutoutRegion = null; 776 777 /* 778 * Indicates whether addNotify() is complete 779 * (i.e. the peer is created). 780 */ 781 private transient boolean isAddNotifyComplete = false; 782 783 /** 784 * Should only be used in subclass getBounds to check that part of bounds 785 * is actualy changing 786 */ 787 int getBoundsOp() { 788 assert Thread.holdsLock(getTreeLock()); 789 return boundsOp; 790 } 791 792 void setBoundsOp(int op) { 793 assert Thread.holdsLock(getTreeLock()); 794 if (op == ComponentPeer.RESET_OPERATION) { 795 boundsOp = ComponentPeer.DEFAULT_OPERATION; 796 } else 797 if (boundsOp == ComponentPeer.DEFAULT_OPERATION) { 798 boundsOp = op; 799 } 800 } 801 802 // Whether this Component has had the background erase flag 803 // specified via SunToolkit.disableBackgroundErase(). This is 804 // needed in order to make this function work on X11 platforms, 805 // where currently there is no chance to interpose on the creation 806 // of the peer and therefore the call to XSetBackground. 807 transient boolean backgroundEraseDisabled; 808 809 static { 810 AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() { 811 public void setBackgroundEraseDisabled(Component comp, boolean disabled) { 812 comp.backgroundEraseDisabled = disabled; 813 } 814 public boolean getBackgroundEraseDisabled(Component comp) { 815 return comp.backgroundEraseDisabled; 816 } 817 public Rectangle getBounds(Component comp) { 818 return new Rectangle(comp.x, comp.y, comp.width, comp.height); 819 } 820 public void setMixingCutoutShape(Component comp, Shape shape) { 821 Region region = shape == null ? null : 822 Region.getInstance(shape, null); 823 824 synchronized (comp.getTreeLock()) { 825 boolean needShowing = false; 826 boolean needHiding = false; 827 828 if (!comp.isNonOpaqueForMixing()) { 829 needHiding = true; 830 } 831 832 comp.mixingCutoutRegion = region; 833 834 if (!comp.isNonOpaqueForMixing()) { 835 needShowing = true; 836 } 837 838 if (comp.isMixingNeeded()) { 839 if (needHiding) { 840 comp.mixOnHiding(comp.isLightweight()); 841 } 842 if (needShowing) { 843 comp.mixOnShowing(); 844 } 845 } 846 } 847 } 848 849 public void setGraphicsConfiguration(Component comp, 850 GraphicsConfiguration gc) 851 { 852 comp.setGraphicsConfiguration(gc); 853 } 854 public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) { 855 return comp.requestFocus(cause); 856 } 857 public boolean canBeFocusOwner(Component comp) { 858 return comp.canBeFocusOwner(); 859 } 860 861 public boolean isVisible_NoClientCode(Component comp) { 862 return comp.isVisible_NoClientCode(); 863 } 864 public void setRequestFocusController 865 (RequestFocusController requestController) 866 { 867 Component.setRequestFocusController(requestController); 868 } 869 public AppContext getAppContext(Component comp) { 870 return comp.appContext; 871 } 872 public void setAppContext(Component comp, AppContext appContext) { 873 comp.appContext = appContext; 874 } 875 }); 876 } 877 878 /** 879 * Constructs a new component. Class <code>Component</code> can be 880 * extended directly to create a lightweight component that does not 881 * utilize an opaque native window. A lightweight component must be 882 * hosted by a native container somewhere higher up in the component 883 * tree (for example, by a <code>Frame</code> object). 884 */ 885 protected Component() { 886 appContext = AppContext.getAppContext(); 887 } 888 889 void initializeFocusTraversalKeys() { 890 focusTraversalKeys = new Set[3]; 891 } 892 893 /** 894 * Constructs a name for this component. Called by <code>getName</code> 895 * when the name is <code>null</code>. 896 */ 897 String constructComponentName() { 898 return null; // For strict compliance with prior platform versions, a Component 899 // that doesn't set its name should return null from 900 // getName() 901 } 902 903 /** 904 * Gets the name of the component. 905 * @return this component's name 906 * @see #setName 907 * @since JDK1.1 908 */ 909 public String getName() { 910 if (name == null && !nameExplicitlySet) { 911 synchronized(getObjectLock()) { 912 if (name == null && !nameExplicitlySet) 913 name = constructComponentName(); 914 } 915 } 916 return name; 917 } 918 919 /** 920 * Sets the name of the component to the specified string. 921 * @param name the string that is to be this 922 * component's name 923 * @see #getName 924 * @since JDK1.1 925 */ 926 public void setName(String name) { 927 String oldName; 928 synchronized(getObjectLock()) { 929 oldName = this.name; 930 this.name = name; 931 nameExplicitlySet = true; 932 } 933 firePropertyChange("name", oldName, name); 934 } 935 936 /** 937 * Gets the parent of this component. 938 * @return the parent container of this component 939 * @since JDK1.0 940 */ 941 public Container getParent() { 942 return getParent_NoClientCode(); 943 } 944 945 // NOTE: This method may be called by privileged threads. 946 // This functionality is implemented in a package-private method 947 // to insure that it cannot be overridden by client subclasses. 948 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 949 final Container getParent_NoClientCode() { 950 return parent; 951 } 952 953 // This method is overriden in the Window class to return null, 954 // because the parent field of the Window object contains 955 // the owner of the window, not its parent. 956 Container getContainer() { 957 return getParent(); 958 } 959 960 /** 961 * @deprecated As of JDK version 1.1, 962 * programs should not directly manipulate peers; 963 * replaced by <code>boolean isDisplayable()</code>. 964 */ 965 @Deprecated 966 public ComponentPeer getPeer() { 967 return peer; 968 } 969 970 /** 971 * Associate a <code>DropTarget</code> with this component. 972 * The <code>Component</code> will receive drops only if it 973 * is enabled. 974 * 975 * @see #isEnabled 976 * @param dt The DropTarget 977 */ 978 979 public synchronized void setDropTarget(DropTarget dt) { 980 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt))) 981 return; 982 983 DropTarget old; 984 985 if ((old = dropTarget) != null) { 986 if (peer != null) dropTarget.removeNotify(peer); 987 988 DropTarget t = dropTarget; 989 990 dropTarget = null; 991 992 try { 993 t.setComponent(null); 994 } catch (IllegalArgumentException iae) { 995 // ignore it. 996 } 997 } 998 999 // if we have a new one, and we have a peer, add it! 1000 1001 if ((dropTarget = dt) != null) { 1002 try { 1003 dropTarget.setComponent(this); 1004 if (peer != null) dropTarget.addNotify(peer); 1005 } catch (IllegalArgumentException iae) { 1006 if (old != null) { 1007 try { 1008 old.setComponent(this); 1009 if (peer != null) dropTarget.addNotify(peer); 1010 } catch (IllegalArgumentException iae1) { 1011 // ignore it! 1012 } 1013 } 1014 } 1015 } 1016 } 1017 1018 /** 1019 * Gets the <code>DropTarget</code> associated with this 1020 * <code>Component</code>. 1021 */ 1022 1023 public synchronized DropTarget getDropTarget() { return dropTarget; } 1024 1025 /** 1026 * Gets the <code>GraphicsConfiguration</code> associated with this 1027 * <code>Component</code>. 1028 * If the <code>Component</code> has not been assigned a specific 1029 * <code>GraphicsConfiguration</code>, 1030 * the <code>GraphicsConfiguration</code> of the 1031 * <code>Component</code> object's top-level container is 1032 * returned. 1033 * If the <code>Component</code> has been created, but not yet added 1034 * to a <code>Container</code>, this method returns <code>null</code>. 1035 * 1036 * @return the <code>GraphicsConfiguration</code> used by this 1037 * <code>Component</code> or <code>null</code> 1038 * @since 1.3 1039 */ 1040 public GraphicsConfiguration getGraphicsConfiguration() { 1041 synchronized(getTreeLock()) { 1042 return getGraphicsConfiguration_NoClientCode(); 1043 } 1044 } 1045 1046 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() { 1047 return graphicsConfig; 1048 } 1049 1050 void setGraphicsConfiguration(GraphicsConfiguration gc) { 1051 synchronized(getTreeLock()) { 1052 if (updateGraphicsData(gc)) { 1053 removeNotify(); 1054 addNotify(); 1055 } 1056 } 1057 } 1058 1059 boolean updateGraphicsData(GraphicsConfiguration gc) { 1060 checkTreeLock(); 1061 1062 graphicsConfig = gc; 1063 1064 ComponentPeer peer = getPeer(); 1065 if (peer != null) { 1066 return peer.updateGraphicsData(gc); 1067 } 1068 return false; 1069 } 1070 1071 /** 1072 * Checks that this component's <code>GraphicsDevice</code> 1073 * <code>idString</code> matches the string argument. 1074 */ 1075 void checkGD(String stringID) { 1076 if (graphicsConfig != null) { 1077 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) { 1078 throw new IllegalArgumentException( 1079 "adding a container to a container on a different GraphicsDevice"); 1080 } 1081 } 1082 } 1083 1084 /** 1085 * Gets this component's locking object (the object that owns the thread 1086 * synchronization monitor) for AWT component-tree and layout 1087 * operations. 1088 * @return this component's locking object 1089 */ 1090 public final Object getTreeLock() { 1091 return LOCK; 1092 } 1093 1094 final void checkTreeLock() { 1095 if (!Thread.holdsLock(getTreeLock())) { 1096 throw new IllegalStateException("This function should be called while holding treeLock"); 1097 } 1098 } 1099 1100 /** 1101 * Gets the toolkit of this component. Note that 1102 * the frame that contains a component controls which 1103 * toolkit is used by that component. Therefore if the component 1104 * is moved from one frame to another, the toolkit it uses may change. 1105 * @return the toolkit of this component 1106 * @since JDK1.0 1107 */ 1108 public Toolkit getToolkit() { 1109 return getToolkitImpl(); 1110 } 1111 1112 /* 1113 * This is called by the native code, so client code can't 1114 * be called on the toolkit thread. 1115 */ 1116 final Toolkit getToolkitImpl() { 1117 ComponentPeer peer = this.peer; 1118 if ((peer != null) && ! (peer instanceof LightweightPeer)){ 1119 return peer.getToolkit(); 1120 } 1121 Container parent = this.parent; 1122 if (parent != null) { 1123 return parent.getToolkitImpl(); 1124 } 1125 return Toolkit.getDefaultToolkit(); 1126 } 1127 1128 /** 1129 * Determines whether this component is valid. A component is valid 1130 * when it is correctly sized and positioned within its parent 1131 * container and all its children are also valid. 1132 * In order to account for peers' size requirements, components are invalidated 1133 * before they are first shown on the screen. By the time the parent container 1134 * is fully realized, all its components will be valid. 1135 * @return <code>true</code> if the component is valid, <code>false</code> 1136 * otherwise 1137 * @see #validate 1138 * @see #invalidate 1139 * @since JDK1.0 1140 */ 1141 public boolean isValid() { 1142 return (peer != null) && valid; 1143 } 1144 1145 /** 1146 * Determines whether this component is displayable. A component is 1147 * displayable when it is connected to a native screen resource. 1148 * <p> 1149 * A component is made displayable either when it is added to 1150 * a displayable containment hierarchy or when its containment 1151 * hierarchy is made displayable. 1152 * A containment hierarchy is made displayable when its ancestor 1153 * window is either packed or made visible. 1154 * <p> 1155 * A component is made undisplayable either when it is removed from 1156 * a displayable containment hierarchy or when its containment hierarchy 1157 * is made undisplayable. A containment hierarchy is made 1158 * undisplayable when its ancestor window is disposed. 1159 * 1160 * @return <code>true</code> if the component is displayable, 1161 * <code>false</code> otherwise 1162 * @see Container#add(Component) 1163 * @see Window#pack 1164 * @see Window#show 1165 * @see Container#remove(Component) 1166 * @see Window#dispose 1167 * @since 1.2 1168 */ 1169 public boolean isDisplayable() { 1170 return getPeer() != null; 1171 } 1172 1173 /** 1174 * Determines whether this component should be visible when its 1175 * parent is visible. Components are 1176 * initially visible, with the exception of top level components such 1177 * as <code>Frame</code> objects. 1178 * @return <code>true</code> if the component is visible, 1179 * <code>false</code> otherwise 1180 * @see #setVisible 1181 * @since JDK1.0 1182 */ 1183 @Transient 1184 public boolean isVisible() { 1185 return isVisible_NoClientCode(); 1186 } 1187 final boolean isVisible_NoClientCode() { 1188 return visible; 1189 } 1190 1191 /** 1192 * Determines whether this component will be displayed on the screen. 1193 * @return <code>true</code> if the component and all of its ancestors 1194 * until a toplevel window or null parent are visible, 1195 * <code>false</code> otherwise 1196 */ 1197 boolean isRecursivelyVisible() { 1198 return visible && (parent == null || parent.isRecursivelyVisible()); 1199 } 1200 1201 /** 1202 * Translates absolute coordinates into coordinates in the coordinate 1203 * space of this component. 1204 */ 1205 Point pointRelativeToComponent(Point absolute) { 1206 Point compCoords = getLocationOnScreen(); 1207 return new Point(absolute.x - compCoords.x, 1208 absolute.y - compCoords.y); 1209 } 1210 1211 /** 1212 * Assuming that mouse location is stored in PointerInfo passed 1213 * to this method, it finds a Component that is in the same 1214 * Window as this Component and is located under the mouse pointer. 1215 * If no such Component exists, null is returned. 1216 * NOTE: this method should be called under the protection of 1217 * tree lock, as it is done in Component.getMousePosition() and 1218 * Container.getMousePosition(boolean). 1219 */ 1220 Component findUnderMouseInWindow(PointerInfo pi) { 1221 if (!isShowing()) { 1222 return null; 1223 } 1224 Window win = getContainingWindow(); 1225 if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) { 1226 return null; 1227 } 1228 final boolean INCLUDE_DISABLED = true; 1229 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation()); 1230 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x, 1231 relativeToWindow.y, 1232 INCLUDE_DISABLED); 1233 return inTheSameWindow; 1234 } 1235 1236 /** 1237 * Returns the position of the mouse pointer in this <code>Component</code>'s 1238 * coordinate space if the <code>Component</code> is directly under the mouse 1239 * pointer, otherwise returns <code>null</code>. 1240 * If the <code>Component</code> is not showing on the screen, this method 1241 * returns <code>null</code> even if the mouse pointer is above the area 1242 * where the <code>Component</code> would be displayed. 1243 * If the <code>Component</code> is partially or fully obscured by other 1244 * <code>Component</code>s or native windows, this method returns a non-null 1245 * value only if the mouse pointer is located above the unobscured part of the 1246 * <code>Component</code>. 1247 * <p> 1248 * For <code>Container</code>s it returns a non-null value if the mouse is 1249 * above the <code>Container</code> itself or above any of its descendants. 1250 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children. 1251 * <p> 1252 * Sometimes the exact mouse coordinates are not important, and the only thing 1253 * that matters is whether a specific <code>Component</code> is under the mouse 1254 * pointer. If the return value of this method is <code>null</code>, mouse 1255 * pointer is not directly above the <code>Component</code>. 1256 * 1257 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true 1258 * @see #isShowing 1259 * @see Container#getMousePosition 1260 * @return mouse coordinates relative to this <code>Component</code>, or null 1261 * @since 1.5 1262 */ 1263 public Point getMousePosition() throws HeadlessException { 1264 if (GraphicsEnvironment.isHeadless()) { 1265 throw new HeadlessException(); 1266 } 1267 1268 PointerInfo pi = (PointerInfo)java.security.AccessController.doPrivileged( 1269 new java.security.PrivilegedAction() { 1270 public Object run() { 1271 return MouseInfo.getPointerInfo(); 1272 } 1273 } 1274 ); 1275 1276 synchronized (getTreeLock()) { 1277 Component inTheSameWindow = findUnderMouseInWindow(pi); 1278 if (!isSameOrAncestorOf(inTheSameWindow, true)) { 1279 return null; 1280 } 1281 return pointRelativeToComponent(pi.getLocation()); 1282 } 1283 } 1284 1285 /** 1286 * Overridden in Container. Must be called under TreeLock. 1287 */ 1288 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) { 1289 return comp == this; 1290 } 1291 1292 /** 1293 * Determines whether this component is showing on screen. This means 1294 * that the component must be visible, and it must be in a container 1295 * that is visible and showing. 1296 * <p> 1297 * <strong>Note:</strong> sometimes there is no way to detect whether the 1298 * {@code Component} is actually visible to the user. This can happen when: 1299 * <ul> 1300 * <li>the component has been added to a visible {@code ScrollPane} but 1301 * the {@code Component} is not currently in the scroll pane's view port. 1302 * <li>the {@code Component} is obscured by another {@code Component} or 1303 * {@code Container}. 1304 * </ul> 1305 * @return <code>true</code> if the component is showing, 1306 * <code>false</code> otherwise 1307 * @see #setVisible 1308 * @since JDK1.0 1309 */ 1310 public boolean isShowing() { 1311 if (visible && (peer != null)) { 1312 Container parent = this.parent; 1313 return (parent == null) || parent.isShowing(); 1314 } 1315 return false; 1316 } 1317 1318 /** 1319 * Determines whether this component is enabled. An enabled component 1320 * can respond to user input and generate events. Components are 1321 * enabled initially by default. A component may be enabled or disabled by 1322 * calling its <code>setEnabled</code> method. 1323 * @return <code>true</code> if the component is enabled, 1324 * <code>false</code> otherwise 1325 * @see #setEnabled 1326 * @since JDK1.0 1327 */ 1328 public boolean isEnabled() { 1329 return isEnabledImpl(); 1330 } 1331 1332 /* 1333 * This is called by the native code, so client code can't 1334 * be called on the toolkit thread. 1335 */ 1336 final boolean isEnabledImpl() { 1337 return enabled; 1338 } 1339 1340 /** 1341 * Enables or disables this component, depending on the value of the 1342 * parameter <code>b</code>. An enabled component can respond to user 1343 * input and generate events. Components are enabled initially by default. 1344 * 1345 * <p>Note: Disabling a lightweight component does not prevent it from 1346 * receiving MouseEvents. 1347 * <p>Note: Disabling a heavyweight container prevents all components 1348 * in this container from receiving any input events. But disabling a 1349 * lightweight container affects only this container. 1350 * 1351 * @param b If <code>true</code>, this component is 1352 * enabled; otherwise this component is disabled 1353 * @see #isEnabled 1354 * @see #isLightweight 1355 * @since JDK1.1 1356 */ 1357 public void setEnabled(boolean b) { 1358 enable(b); 1359 } 1360 1361 /** 1362 * @deprecated As of JDK version 1.1, 1363 * replaced by <code>setEnabled(boolean)</code>. 1364 */ 1365 @Deprecated 1366 public void enable() { 1367 if (!enabled) { 1368 synchronized (getTreeLock()) { 1369 enabled = true; 1370 ComponentPeer peer = this.peer; 1371 if (peer != null) { 1372 peer.setEnabled(true); 1373 if (visible) { 1374 updateCursorImmediately(); 1375 } 1376 } 1377 } 1378 if (accessibleContext != null) { 1379 accessibleContext.firePropertyChange( 1380 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1381 null, AccessibleState.ENABLED); 1382 } 1383 } 1384 } 1385 1386 /** 1387 * @deprecated As of JDK version 1.1, 1388 * replaced by <code>setEnabled(boolean)</code>. 1389 */ 1390 @Deprecated 1391 public void enable(boolean b) { 1392 if (b) { 1393 enable(); 1394 } else { 1395 disable(); 1396 } 1397 } 1398 1399 /** 1400 * @deprecated As of JDK version 1.1, 1401 * replaced by <code>setEnabled(boolean)</code>. 1402 */ 1403 @Deprecated 1404 public void disable() { 1405 if (enabled) { 1406 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1407 synchronized (getTreeLock()) { 1408 enabled = false; 1409 // A disabled lw container is allowed to contain a focus owner. 1410 if ((isFocusOwner() || (containsFocus() && !isLightweight())) && 1411 KeyboardFocusManager.isAutoFocusTransferEnabled()) 1412 { 1413 // Don't clear the global focus owner. If transferFocus 1414 // fails, we want the focus to stay on the disabled 1415 // Component so that keyboard traversal, et. al. still 1416 // makes sense to the user. 1417 transferFocus(false); 1418 } 1419 ComponentPeer peer = this.peer; 1420 if (peer != null) { 1421 peer.setEnabled(false); 1422 if (visible) { 1423 updateCursorImmediately(); 1424 } 1425 } 1426 } 1427 if (accessibleContext != null) { 1428 accessibleContext.firePropertyChange( 1429 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1430 null, AccessibleState.ENABLED); 1431 } 1432 } 1433 } 1434 1435 /** 1436 * Returns true if this component is painted to an offscreen image 1437 * ("buffer") that's copied to the screen later. Component 1438 * subclasses that support double buffering should override this 1439 * method to return true if double buffering is enabled. 1440 * 1441 * @return false by default 1442 */ 1443 public boolean isDoubleBuffered() { 1444 return false; 1445 } 1446 1447 /** 1448 * Enables or disables input method support for this component. If input 1449 * method support is enabled and the component also processes key events, 1450 * incoming events are offered to 1451 * the current input method and will only be processed by the component or 1452 * dispatched to its listeners if the input method does not consume them. 1453 * By default, input method support is enabled. 1454 * 1455 * @param enable true to enable, false to disable 1456 * @see #processKeyEvent 1457 * @since 1.2 1458 */ 1459 public void enableInputMethods(boolean enable) { 1460 if (enable) { 1461 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) 1462 return; 1463 1464 // If this component already has focus, then activate the 1465 // input method by dispatching a synthesized focus gained 1466 // event. 1467 if (isFocusOwner()) { 1468 InputContext inputContext = getInputContext(); 1469 if (inputContext != null) { 1470 FocusEvent focusGainedEvent = 1471 new FocusEvent(this, FocusEvent.FOCUS_GAINED); 1472 inputContext.dispatchEvent(focusGainedEvent); 1473 } 1474 } 1475 1476 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK; 1477 } else { 1478 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { 1479 InputContext inputContext = getInputContext(); 1480 if (inputContext != null) { 1481 inputContext.endComposition(); 1482 inputContext.removeNotify(this); 1483 } 1484 } 1485 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK; 1486 } 1487 } 1488 1489 /** 1490 * Shows or hides this component depending on the value of parameter 1491 * <code>b</code>. 1492 * @param b if <code>true</code>, shows this component; 1493 * otherwise, hides this component 1494 * @see #isVisible 1495 * @since JDK1.1 1496 */ 1497 public void setVisible(boolean b) { 1498 show(b); 1499 } 1500 1501 /** 1502 * @deprecated As of JDK version 1.1, 1503 * replaced by <code>setVisible(boolean)</code>. 1504 */ 1505 @Deprecated 1506 public void show() { 1507 if (!visible) { 1508 synchronized (getTreeLock()) { 1509 visible = true; 1510 mixOnShowing(); 1511 ComponentPeer peer = this.peer; 1512 if (peer != null) { 1513 peer.setVisible(true); 1514 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1515 this, parent, 1516 HierarchyEvent.SHOWING_CHANGED, 1517 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1518 if (peer instanceof LightweightPeer) { 1519 repaint(); 1520 } 1521 updateCursorImmediately(); 1522 } 1523 1524 if (componentListener != null || 1525 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1526 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1527 ComponentEvent e = new ComponentEvent(this, 1528 ComponentEvent.COMPONENT_SHOWN); 1529 Toolkit.getEventQueue().postEvent(e); 1530 } 1531 } 1532 Container parent = this.parent; 1533 if (parent != null) { 1534 parent.invalidate(); 1535 } 1536 } 1537 } 1538 1539 /** 1540 * @deprecated As of JDK version 1.1, 1541 * replaced by <code>setVisible(boolean)</code>. 1542 */ 1543 @Deprecated 1544 public void show(boolean b) { 1545 if (b) { 1546 show(); 1547 } else { 1548 hide(); 1549 } 1550 } 1551 1552 boolean containsFocus() { 1553 return isFocusOwner(); 1554 } 1555 1556 void clearMostRecentFocusOwnerOnHide() { 1557 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1558 } 1559 1560 void clearCurrentFocusCycleRootOnHide() { 1561 /* do nothing */ 1562 } 1563 1564 /** 1565 * @deprecated As of JDK version 1.1, 1566 * replaced by <code>setVisible(boolean)</code>. 1567 */ 1568 @Deprecated 1569 public void hide() { 1570 isPacked = false; 1571 1572 if (visible) { 1573 clearCurrentFocusCycleRootOnHide(); 1574 clearMostRecentFocusOwnerOnHide(); 1575 synchronized (getTreeLock()) { 1576 visible = false; 1577 mixOnHiding(isLightweight()); 1578 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) { 1579 transferFocus(true); 1580 } 1581 ComponentPeer peer = this.peer; 1582 if (peer != null) { 1583 peer.setVisible(false); 1584 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1585 this, parent, 1586 HierarchyEvent.SHOWING_CHANGED, 1587 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1588 if (peer instanceof LightweightPeer) { 1589 repaint(); 1590 } 1591 updateCursorImmediately(); 1592 } 1593 if (componentListener != null || 1594 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1595 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1596 ComponentEvent e = new ComponentEvent(this, 1597 ComponentEvent.COMPONENT_HIDDEN); 1598 Toolkit.getEventQueue().postEvent(e); 1599 } 1600 } 1601 Container parent = this.parent; 1602 if (parent != null) { 1603 parent.invalidate(); 1604 } 1605 } 1606 } 1607 1608 /** 1609 * Gets the foreground color of this component. 1610 * @return this component's foreground color; if this component does 1611 * not have a foreground color, the foreground color of its parent 1612 * is returned 1613 * @see #setForeground 1614 * @since JDK1.0 1615 * @beaninfo 1616 * bound: true 1617 */ 1618 @Transient 1619 public Color getForeground() { 1620 Color foreground = this.foreground; 1621 if (foreground != null) { 1622 return foreground; 1623 } 1624 Container parent = this.parent; 1625 return (parent != null) ? parent.getForeground() : null; 1626 } 1627 1628 /** 1629 * Sets the foreground color of this component. 1630 * @param c the color to become this component's 1631 * foreground color; if this parameter is <code>null</code> 1632 * then this component will inherit 1633 * the foreground color of its parent 1634 * @see #getForeground 1635 * @since JDK1.0 1636 */ 1637 public void setForeground(Color c) { 1638 Color oldColor = foreground; 1639 ComponentPeer peer = this.peer; 1640 foreground = c; 1641 if (peer != null) { 1642 c = getForeground(); 1643 if (c != null) { 1644 peer.setForeground(c); 1645 } 1646 } 1647 // This is a bound property, so report the change to 1648 // any registered listeners. (Cheap if there are none.) 1649 firePropertyChange("foreground", oldColor, c); 1650 } 1651 1652 /** 1653 * Returns whether the foreground color has been explicitly set for this 1654 * Component. If this method returns <code>false</code>, this Component is 1655 * inheriting its foreground color from an ancestor. 1656 * 1657 * @return <code>true</code> if the foreground color has been explicitly 1658 * set for this Component; <code>false</code> otherwise. 1659 * @since 1.4 1660 */ 1661 public boolean isForegroundSet() { 1662 return (foreground != null); 1663 } 1664 1665 /** 1666 * Gets the background color of this component. 1667 * @return this component's background color; if this component does 1668 * not have a background color, 1669 * the background color of its parent is returned 1670 * @see #setBackground 1671 * @since JDK1.0 1672 */ 1673 @Transient 1674 public Color getBackground() { 1675 Color background = this.background; 1676 if (background != null) { 1677 return background; 1678 } 1679 Container parent = this.parent; 1680 return (parent != null) ? parent.getBackground() : null; 1681 } 1682 1683 /** 1684 * Sets the background color of this component. 1685 * <p> 1686 * The background color affects each component differently and the 1687 * parts of the component that are affected by the background color 1688 * may differ between operating systems. 1689 * 1690 * @param c the color to become this component's color; 1691 * if this parameter is <code>null</code>, then this 1692 * component will inherit the background color of its parent 1693 * @see #getBackground 1694 * @since JDK1.0 1695 * @beaninfo 1696 * bound: true 1697 */ 1698 public void setBackground(Color c) { 1699 Color oldColor = background; 1700 ComponentPeer peer = this.peer; 1701 background = c; 1702 if (peer != null) { 1703 c = getBackground(); 1704 if (c != null) { 1705 peer.setBackground(c); 1706 } 1707 } 1708 // This is a bound property, so report the change to 1709 // any registered listeners. (Cheap if there are none.) 1710 firePropertyChange("background", oldColor, c); 1711 } 1712 1713 /** 1714 * Returns whether the background color has been explicitly set for this 1715 * Component. If this method returns <code>false</code>, this Component is 1716 * inheriting its background color from an ancestor. 1717 * 1718 * @return <code>true</code> if the background color has been explicitly 1719 * set for this Component; <code>false</code> otherwise. 1720 * @since 1.4 1721 */ 1722 public boolean isBackgroundSet() { 1723 return (background != null); 1724 } 1725 1726 /** 1727 * Gets the font of this component. 1728 * @return this component's font; if a font has not been set 1729 * for this component, the font of its parent is returned 1730 * @see #setFont 1731 * @since JDK1.0 1732 */ 1733 @Transient 1734 public Font getFont() { 1735 return getFont_NoClientCode(); 1736 } 1737 1738 // NOTE: This method may be called by privileged threads. 1739 // This functionality is implemented in a package-private method 1740 // to insure that it cannot be overridden by client subclasses. 1741 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 1742 final Font getFont_NoClientCode() { 1743 Font font = this.font; 1744 if (font != null) { 1745 return font; 1746 } 1747 Container parent = this.parent; 1748 return (parent != null) ? parent.getFont_NoClientCode() : null; 1749 } 1750 1751 /** 1752 * Sets the font of this component. 1753 * @param f the font to become this component's font; 1754 * if this parameter is <code>null</code> then this 1755 * component will inherit the font of its parent 1756 * @see #getFont 1757 * @since JDK1.0 1758 * @beaninfo 1759 * bound: true 1760 */ 1761 public void setFont(Font f) { 1762 Font oldFont, newFont; 1763 synchronized(getTreeLock()) { 1764 synchronized (this) { 1765 oldFont = font; 1766 newFont = font = f; 1767 } 1768 ComponentPeer peer = this.peer; 1769 if (peer != null) { 1770 f = getFont(); 1771 if (f != null) { 1772 peer.setFont(f); 1773 peerFont = f; 1774 } 1775 } 1776 } 1777 // This is a bound property, so report the change to 1778 // any registered listeners. (Cheap if there are none.) 1779 firePropertyChange("font", oldFont, newFont); 1780 1781 // This could change the preferred size of the Component. 1782 // Fix for 6213660. Should compare old and new fonts and do not 1783 // call invalidate() if they are equal. 1784 if (f != oldFont && (oldFont == null || 1785 !oldFont.equals(f))) { 1786 invalidateIfValid(); 1787 } 1788 } 1789 1790 /** 1791 * Returns whether the font has been explicitly set for this Component. If 1792 * this method returns <code>false</code>, this Component is inheriting its 1793 * font from an ancestor. 1794 * 1795 * @return <code>true</code> if the font has been explicitly set for this 1796 * Component; <code>false</code> otherwise. 1797 * @since 1.4 1798 */ 1799 public boolean isFontSet() { 1800 return (font != null); 1801 } 1802 1803 /** 1804 * Gets the locale of this component. 1805 * @return this component's locale; if this component does not 1806 * have a locale, the locale of its parent is returned 1807 * @see #setLocale 1808 * @exception IllegalComponentStateException if the <code>Component</code> 1809 * does not have its own locale and has not yet been added to 1810 * a containment hierarchy such that the locale can be determined 1811 * from the containing parent 1812 * @since JDK1.1 1813 */ 1814 public Locale getLocale() { 1815 Locale locale = this.locale; 1816 if (locale != null) { 1817 return locale; 1818 } 1819 Container parent = this.parent; 1820 1821 if (parent == null) { 1822 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale"); 1823 } else { 1824 return parent.getLocale(); 1825 } 1826 } 1827 1828 /** 1829 * Sets the locale of this component. This is a bound property. 1830 * @param l the locale to become this component's locale 1831 * @see #getLocale 1832 * @since JDK1.1 1833 */ 1834 public void setLocale(Locale l) { 1835 Locale oldValue = locale; 1836 locale = l; 1837 1838 // This is a bound property, so report the change to 1839 // any registered listeners. (Cheap if there are none.) 1840 firePropertyChange("locale", oldValue, l); 1841 1842 // This could change the preferred size of the Component. 1843 invalidateIfValid(); 1844 } 1845 1846 /** 1847 * Gets the instance of <code>ColorModel</code> used to display 1848 * the component on the output device. 1849 * @return the color model used by this component 1850 * @see java.awt.image.ColorModel 1851 * @see java.awt.peer.ComponentPeer#getColorModel() 1852 * @see Toolkit#getColorModel() 1853 * @since JDK1.0 1854 */ 1855 public ColorModel getColorModel() { 1856 ComponentPeer peer = this.peer; 1857 if ((peer != null) && ! (peer instanceof LightweightPeer)) { 1858 return peer.getColorModel(); 1859 } else if (GraphicsEnvironment.isHeadless()) { 1860 return ColorModel.getRGBdefault(); 1861 } // else 1862 return getToolkit().getColorModel(); 1863 } 1864 1865 /** 1866 * Gets the location of this component in the form of a 1867 * point specifying the component's top-left corner. 1868 * The location will be relative to the parent's coordinate space. 1869 * <p> 1870 * Due to the asynchronous nature of native event handling, this 1871 * method can return outdated values (for instance, after several calls 1872 * of <code>setLocation()</code> in rapid succession). For this 1873 * reason, the recommended method of obtaining a component's position is 1874 * within <code>java.awt.event.ComponentListener.componentMoved()</code>, 1875 * which is called after the operating system has finished moving the 1876 * component. 1877 * </p> 1878 * @return an instance of <code>Point</code> representing 1879 * the top-left corner of the component's bounds in 1880 * the coordinate space of the component's parent 1881 * @see #setLocation 1882 * @see #getLocationOnScreen 1883 * @since JDK1.1 1884 */ 1885 public Point getLocation() { 1886 return location(); 1887 } 1888 1889 /** 1890 * Gets the location of this component in the form of a point 1891 * specifying the component's top-left corner in the screen's 1892 * coordinate space. 1893 * @return an instance of <code>Point</code> representing 1894 * the top-left corner of the component's bounds in the 1895 * coordinate space of the screen 1896 * @throws <code>IllegalComponentStateException</code> if the 1897 * component is not showing on the screen 1898 * @see #setLocation 1899 * @see #getLocation 1900 */ 1901 public Point getLocationOnScreen() { 1902 synchronized (getTreeLock()) { 1903 return getLocationOnScreen_NoTreeLock(); 1904 } 1905 } 1906 1907 /* 1908 * a package private version of getLocationOnScreen 1909 * used by GlobalCursormanager to update cursor 1910 */ 1911 final Point getLocationOnScreen_NoTreeLock() { 1912 1913 if (peer != null && isShowing()) { 1914 if (peer instanceof LightweightPeer) { 1915 // lightweight component location needs to be translated 1916 // relative to a native component. 1917 Container host = getNativeContainer(); 1918 Point pt = host.peer.getLocationOnScreen(); 1919 for(Component c = this; c != host; c = c.getParent()) { 1920 pt.x += c.x; 1921 pt.y += c.y; 1922 } 1923 return pt; 1924 } else { 1925 Point pt = peer.getLocationOnScreen(); 1926 return pt; 1927 } 1928 } else { 1929 throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); 1930 } 1931 } 1932 1933 1934 /** 1935 * @deprecated As of JDK version 1.1, 1936 * replaced by <code>getLocation()</code>. 1937 */ 1938 @Deprecated 1939 public Point location() { 1940 return location_NoClientCode(); 1941 } 1942 1943 private Point location_NoClientCode() { 1944 return new Point(x, y); 1945 } 1946 1947 /** 1948 * Moves this component to a new location. The top-left corner of 1949 * the new location is specified by the <code>x</code> and <code>y</code> 1950 * parameters in the coordinate space of this component's parent. 1951 * @param x the <i>x</i>-coordinate of the new location's 1952 * top-left corner in the parent's coordinate space 1953 * @param y the <i>y</i>-coordinate of the new location's 1954 * top-left corner in the parent's coordinate space 1955 * @see #getLocation 1956 * @see #setBounds 1957 * @since JDK1.1 1958 */ 1959 public void setLocation(int x, int y) { 1960 move(x, y); 1961 } 1962 1963 /** 1964 * @deprecated As of JDK version 1.1, 1965 * replaced by <code>setLocation(int, int)</code>. 1966 */ 1967 @Deprecated 1968 public void move(int x, int y) { 1969 synchronized(getTreeLock()) { 1970 setBoundsOp(ComponentPeer.SET_LOCATION); 1971 setBounds(x, y, width, height); 1972 } 1973 } 1974 1975 /** 1976 * Moves this component to a new location. The top-left corner of 1977 * the new location is specified by point <code>p</code>. Point 1978 * <code>p</code> is given in the parent's coordinate space. 1979 * @param p the point defining the top-left corner 1980 * of the new location, given in the coordinate space of this 1981 * component's parent 1982 * @see #getLocation 1983 * @see #setBounds 1984 * @since JDK1.1 1985 */ 1986 public void setLocation(Point p) { 1987 setLocation(p.x, p.y); 1988 } 1989 1990 /** 1991 * Returns the size of this component in the form of a 1992 * <code>Dimension</code> object. The <code>height</code> 1993 * field of the <code>Dimension</code> object contains 1994 * this component's height, and the <code>width</code> 1995 * field of the <code>Dimension</code> object contains 1996 * this component's width. 1997 * @return a <code>Dimension</code> object that indicates the 1998 * size of this component 1999 * @see #setSize 2000 * @since JDK1.1 2001 */ 2002 public Dimension getSize() { 2003 return size(); 2004 } 2005 2006 /** 2007 * @deprecated As of JDK version 1.1, 2008 * replaced by <code>getSize()</code>. 2009 */ 2010 @Deprecated 2011 public Dimension size() { 2012 return new Dimension(width, height); 2013 } 2014 2015 /** 2016 * Resizes this component so that it has width <code>width</code> 2017 * and height <code>height</code>. 2018 * @param width the new width of this component in pixels 2019 * @param height the new height of this component in pixels 2020 * @see #getSize 2021 * @see #setBounds 2022 * @since JDK1.1 2023 */ 2024 public void setSize(int width, int height) { 2025 resize(width, height); 2026 } 2027 2028 /** 2029 * @deprecated As of JDK version 1.1, 2030 * replaced by <code>setSize(int, int)</code>. 2031 */ 2032 @Deprecated 2033 public void resize(int width, int height) { 2034 synchronized(getTreeLock()) { 2035 setBoundsOp(ComponentPeer.SET_SIZE); 2036 setBounds(x, y, width, height); 2037 } 2038 } 2039 2040 /** 2041 * Resizes this component so that it has width <code>d.width</code> 2042 * and height <code>d.height</code>. 2043 * @param d the dimension specifying the new size 2044 * of this component 2045 * @see #setSize 2046 * @see #setBounds 2047 * @since JDK1.1 2048 */ 2049 public void setSize(Dimension d) { 2050 resize(d); 2051 } 2052 2053 /** 2054 * @deprecated As of JDK version 1.1, 2055 * replaced by <code>setSize(Dimension)</code>. 2056 */ 2057 @Deprecated 2058 public void resize(Dimension d) { 2059 setSize(d.width, d.height); 2060 } 2061 2062 /** 2063 * Gets the bounds of this component in the form of a 2064 * <code>Rectangle</code> object. The bounds specify this 2065 * component's width, height, and location relative to 2066 * its parent. 2067 * @return a rectangle indicating this component's bounds 2068 * @see #setBounds 2069 * @see #getLocation 2070 * @see #getSize 2071 */ 2072 public Rectangle getBounds() { 2073 return bounds(); 2074 } 2075 2076 /** 2077 * @deprecated As of JDK version 1.1, 2078 * replaced by <code>getBounds()</code>. 2079 */ 2080 @Deprecated 2081 public Rectangle bounds() { 2082 return new Rectangle(x, y, width, height); 2083 } 2084 2085 /** 2086 * Moves and resizes this component. The new location of the top-left 2087 * corner is specified by <code>x</code> and <code>y</code>, and the 2088 * new size is specified by <code>width</code> and <code>height</code>. 2089 * @param x the new <i>x</i>-coordinate of this component 2090 * @param y the new <i>y</i>-coordinate of this component 2091 * @param width the new <code>width</code> of this component 2092 * @param height the new <code>height</code> of this 2093 * component 2094 * @see #getBounds 2095 * @see #setLocation(int, int) 2096 * @see #setLocation(Point) 2097 * @see #setSize(int, int) 2098 * @see #setSize(Dimension) 2099 * @since JDK1.1 2100 */ 2101 public void setBounds(int x, int y, int width, int height) { 2102 reshape(x, y, width, height); 2103 } 2104 2105 /** 2106 * @deprecated As of JDK version 1.1, 2107 * replaced by <code>setBounds(int, int, int, int)</code>. 2108 */ 2109 @Deprecated 2110 public void reshape(int x, int y, int width, int height) { 2111 synchronized (getTreeLock()) { 2112 try { 2113 setBoundsOp(ComponentPeer.SET_BOUNDS); 2114 boolean resized = (this.width != width) || (this.height != height); 2115 boolean moved = (this.x != x) || (this.y != y); 2116 if (!resized && !moved) { 2117 return; 2118 } 2119 int oldX = this.x; 2120 int oldY = this.y; 2121 int oldWidth = this.width; 2122 int oldHeight = this.height; 2123 this.x = x; 2124 this.y = y; 2125 this.width = width; 2126 this.height = height; 2127 2128 if (resized) { 2129 isPacked = false; 2130 } 2131 2132 boolean needNotify = true; 2133 mixOnReshaping(); 2134 if (peer != null) { 2135 // LightwightPeer is an empty stub so can skip peer.reshape 2136 if (!(peer instanceof LightweightPeer)) { 2137 reshapeNativePeer(x, y, width, height, getBoundsOp()); 2138 // Check peer actualy changed coordinates 2139 resized = (oldWidth != this.width) || (oldHeight != this.height); 2140 moved = (oldX != this.x) || (oldY != this.y); 2141 // fix for 5025858: do not send ComponentEvents for toplevel 2142 // windows here as it is done from peer or native code when 2143 // the window is really resized or moved, otherwise some 2144 // events may be sent twice 2145 if (this instanceof Window) { 2146 needNotify = false; 2147 } 2148 } 2149 if (resized) { 2150 invalidate(); 2151 } 2152 if (parent != null) { 2153 parent.invalidateIfValid(); 2154 } 2155 } 2156 if (needNotify) { 2157 notifyNewBounds(resized, moved); 2158 } 2159 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight); 2160 } finally { 2161 setBoundsOp(ComponentPeer.RESET_OPERATION); 2162 } 2163 } 2164 } 2165 2166 private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth, 2167 int oldHeight) 2168 { 2169 if (parent != null && peer instanceof LightweightPeer && isShowing()) { 2170 // Have the parent redraw the area this component occupied. 2171 parent.repaint(oldX, oldY, oldWidth, oldHeight); 2172 // Have the parent redraw the area this component *now* occupies. 2173 repaint(); 2174 } 2175 } 2176 2177 private void reshapeNativePeer(int x, int y, int width, int height, int op) { 2178 // native peer might be offset by more than direct 2179 // parent since parent might be lightweight. 2180 int nativeX = x; 2181 int nativeY = y; 2182 for (Component c = parent; 2183 (c != null) && (c.peer instanceof LightweightPeer); 2184 c = c.parent) 2185 { 2186 nativeX += c.x; 2187 nativeY += c.y; 2188 } 2189 peer.setBounds(nativeX, nativeY, width, height, op); 2190 } 2191 2192 2193 private void notifyNewBounds(boolean resized, boolean moved) { 2194 if (componentListener != null 2195 || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 2196 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) 2197 { 2198 if (resized) { 2199 ComponentEvent e = new ComponentEvent(this, 2200 ComponentEvent.COMPONENT_RESIZED); 2201 Toolkit.getEventQueue().postEvent(e); 2202 } 2203 if (moved) { 2204 ComponentEvent e = new ComponentEvent(this, 2205 ComponentEvent.COMPONENT_MOVED); 2206 Toolkit.getEventQueue().postEvent(e); 2207 } 2208 } else { 2209 if (this instanceof Container && ((Container)this).countComponents() > 0) { 2210 boolean enabledOnToolkit = 2211 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); 2212 if (resized) { 2213 2214 ((Container)this).createChildHierarchyEvents( 2215 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit); 2216 } 2217 if (moved) { 2218 ((Container)this).createChildHierarchyEvents( 2219 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit); 2220 } 2221 } 2222 } 2223 } 2224 2225 /** 2226 * Moves and resizes this component to conform to the new 2227 * bounding rectangle <code>r</code>. This component's new 2228 * position is specified by <code>r.x</code> and <code>r.y</code>, 2229 * and its new size is specified by <code>r.width</code> and 2230 * <code>r.height</code> 2231 * @param r the new bounding rectangle for this component 2232 * @see #getBounds 2233 * @see #setLocation(int, int) 2234 * @see #setLocation(Point) 2235 * @see #setSize(int, int) 2236 * @see #setSize(Dimension) 2237 * @since JDK1.1 2238 */ 2239 public void setBounds(Rectangle r) { 2240 setBounds(r.x, r.y, r.width, r.height); 2241 } 2242 2243 2244 /** 2245 * Returns the current x coordinate of the components origin. 2246 * This method is preferable to writing 2247 * <code>component.getBounds().x</code>, 2248 * or <code>component.getLocation().x</code> because it doesn't 2249 * cause any heap allocations. 2250 * 2251 * @return the current x coordinate of the components origin 2252 * @since 1.2 2253 */ 2254 public int getX() { 2255 return x; 2256 } 2257 2258 2259 /** 2260 * Returns the current y coordinate of the components origin. 2261 * This method is preferable to writing 2262 * <code>component.getBounds().y</code>, 2263 * or <code>component.getLocation().y</code> because it 2264 * doesn't cause any heap allocations. 2265 * 2266 * @return the current y coordinate of the components origin 2267 * @since 1.2 2268 */ 2269 public int getY() { 2270 return y; 2271 } 2272 2273 2274 /** 2275 * Returns the current width of this component. 2276 * This method is preferable to writing 2277 * <code>component.getBounds().width</code>, 2278 * or <code>component.getSize().width</code> because it 2279 * doesn't cause any heap allocations. 2280 * 2281 * @return the current width of this component 2282 * @since 1.2 2283 */ 2284 public int getWidth() { 2285 return width; 2286 } 2287 2288 2289 /** 2290 * Returns the current height of this component. 2291 * This method is preferable to writing 2292 * <code>component.getBounds().height</code>, 2293 * or <code>component.getSize().height</code> because it 2294 * doesn't cause any heap allocations. 2295 * 2296 * @return the current height of this component 2297 * @since 1.2 2298 */ 2299 public int getHeight() { 2300 return height; 2301 } 2302 2303 /** 2304 * Stores the bounds of this component into "return value" <b>rv</b> and 2305 * return <b>rv</b>. If rv is <code>null</code> a new 2306 * <code>Rectangle</code> is allocated. 2307 * This version of <code>getBounds</code> is useful if the caller 2308 * wants to avoid allocating a new <code>Rectangle</code> object 2309 * on the heap. 2310 * 2311 * @param rv the return value, modified to the components bounds 2312 * @return rv 2313 */ 2314 public Rectangle getBounds(Rectangle rv) { 2315 if (rv == null) { 2316 return new Rectangle(getX(), getY(), getWidth(), getHeight()); 2317 } 2318 else { 2319 rv.setBounds(getX(), getY(), getWidth(), getHeight()); 2320 return rv; 2321 } 2322 } 2323 2324 /** 2325 * Stores the width/height of this component into "return value" <b>rv</b> 2326 * and return <b>rv</b>. If rv is <code>null</code> a new 2327 * <code>Dimension</code> object is allocated. This version of 2328 * <code>getSize</code> is useful if the caller wants to avoid 2329 * allocating a new <code>Dimension</code> object on the heap. 2330 * 2331 * @param rv the return value, modified to the components size 2332 * @return rv 2333 */ 2334 public Dimension getSize(Dimension rv) { 2335 if (rv == null) { 2336 return new Dimension(getWidth(), getHeight()); 2337 } 2338 else { 2339 rv.setSize(getWidth(), getHeight()); 2340 return rv; 2341 } 2342 } 2343 2344 /** 2345 * Stores the x,y origin of this component into "return value" <b>rv</b> 2346 * and return <b>rv</b>. If rv is <code>null</code> a new 2347 * <code>Point</code> is allocated. 2348 * This version of <code>getLocation</code> is useful if the 2349 * caller wants to avoid allocating a new <code>Point</code> 2350 * object on the heap. 2351 * 2352 * @param rv the return value, modified to the components location 2353 * @return rv 2354 */ 2355 public Point getLocation(Point rv) { 2356 if (rv == null) { 2357 return new Point(getX(), getY()); 2358 } 2359 else { 2360 rv.setLocation(getX(), getY()); 2361 return rv; 2362 } 2363 } 2364 2365 /** 2366 * Returns true if this component is completely opaque, returns 2367 * false by default. 2368 * <p> 2369 * An opaque component paints every pixel within its 2370 * rectangular region. A non-opaque component paints only some of 2371 * its pixels, allowing the pixels underneath it to "show through". 2372 * A component that does not fully paint its pixels therefore 2373 * provides a degree of transparency. Only lightweight 2374 * components can be transparent. 2375 * <p> 2376 * Subclasses that guarantee to always completely paint their 2377 * contents should override this method and return true. All 2378 * of the "heavyweight" AWT components are opaque. 2379 * 2380 * @return true if this component is completely opaque 2381 * @see #isLightweight 2382 * @since 1.2 2383 */ 2384 public boolean isOpaque() { 2385 if (getPeer() == null) { 2386 return false; 2387 } 2388 else { 2389 return !isLightweight(); 2390 } 2391 } 2392 2393 2394 /** 2395 * A lightweight component doesn't have a native toolkit peer. 2396 * Subclasses of <code>Component</code> and <code>Container</code>, 2397 * other than the ones defined in this package like <code>Button</code> 2398 * or <code>Scrollbar</code>, are lightweight. 2399 * All of the Swing components are lightweights. 2400 * <p> 2401 * This method will always return <code>false</code> if this component 2402 * is not displayable because it is impossible to determine the 2403 * weight of an undisplayable component. 2404 * 2405 * @return true if this component has a lightweight peer; false if 2406 * it has a native peer or no peer 2407 * @see #isDisplayable 2408 * @since 1.2 2409 */ 2410 public boolean isLightweight() { 2411 return getPeer() instanceof LightweightPeer; 2412 } 2413 2414 2415 /** 2416 * Sets the preferred size of this component to a constant 2417 * value. Subsequent calls to <code>getPreferredSize</code> will always 2418 * return this value. Setting the preferred size to <code>null</code> 2419 * restores the default behavior. 2420 * 2421 * @param preferredSize The new preferred size, or null 2422 * @see #getPreferredSize 2423 * @see #isPreferredSizeSet 2424 * @since 1.5 2425 */ 2426 public void setPreferredSize(Dimension preferredSize) { 2427 Dimension old; 2428 // If the preferred size was set, use it as the old value, otherwise 2429 // use null to indicate we didn't previously have a set preferred 2430 // size. 2431 if (prefSizeSet) { 2432 old = this.prefSize; 2433 } 2434 else { 2435 old = null; 2436 } 2437 this.prefSize = preferredSize; 2438 prefSizeSet = (preferredSize != null); 2439 firePropertyChange("preferredSize", old, preferredSize); 2440 } 2441 2442 2443 /** 2444 * Returns true if the preferred size has been set to a 2445 * non-<code>null</code> value otherwise returns false. 2446 * 2447 * @return true if <code>setPreferredSize</code> has been invoked 2448 * with a non-null value. 2449 * @since 1.5 2450 */ 2451 public boolean isPreferredSizeSet() { 2452 return prefSizeSet; 2453 } 2454 2455 2456 /** 2457 * Gets the preferred size of this component. 2458 * @return a dimension object indicating this component's preferred size 2459 * @see #getMinimumSize 2460 * @see LayoutManager 2461 */ 2462 public Dimension getPreferredSize() { 2463 return preferredSize(); 2464 } 2465 2466 2467 /** 2468 * @deprecated As of JDK version 1.1, 2469 * replaced by <code>getPreferredSize()</code>. 2470 */ 2471 @Deprecated 2472 public Dimension preferredSize() { 2473 /* Avoid grabbing the lock if a reasonable cached size value 2474 * is available. 2475 */ 2476 Dimension dim = prefSize; 2477 if (dim == null || !(isPreferredSizeSet() || isValid())) { 2478 synchronized (getTreeLock()) { 2479 prefSize = (peer != null) ? 2480 peer.getPreferredSize() : 2481 getMinimumSize(); 2482 dim = prefSize; 2483 } 2484 } 2485 return new Dimension(dim); 2486 } 2487 2488 /** 2489 * Sets the minimum size of this component to a constant 2490 * value. Subsequent calls to <code>getMinimumSize</code> will always 2491 * return this value. Setting the minimum size to <code>null</code> 2492 * restores the default behavior. 2493 * 2494 * @param minimumSize the new minimum size of this component 2495 * @see #getMinimumSize 2496 * @see #isMinimumSizeSet 2497 * @since 1.5 2498 */ 2499 public void setMinimumSize(Dimension minimumSize) { 2500 Dimension old; 2501 // If the minimum size was set, use it as the old value, otherwise 2502 // use null to indicate we didn't previously have a set minimum 2503 // size. 2504 if (minSizeSet) { 2505 old = this.minSize; 2506 } 2507 else { 2508 old = null; 2509 } 2510 this.minSize = minimumSize; 2511 minSizeSet = (minimumSize != null); 2512 firePropertyChange("minimumSize", old, minimumSize); 2513 } 2514 2515 /** 2516 * Returns whether or not <code>setMinimumSize</code> has been 2517 * invoked with a non-null value. 2518 * 2519 * @return true if <code>setMinimumSize</code> has been invoked with a 2520 * non-null value. 2521 * @since 1.5 2522 */ 2523 public boolean isMinimumSizeSet() { 2524 return minSizeSet; 2525 } 2526 2527 /** 2528 * Gets the mininimum size of this component. 2529 * @return a dimension object indicating this component's minimum size 2530 * @see #getPreferredSize 2531 * @see LayoutManager 2532 */ 2533 public Dimension getMinimumSize() { 2534 return minimumSize(); 2535 } 2536 2537 /** 2538 * @deprecated As of JDK version 1.1, 2539 * replaced by <code>getMinimumSize()</code>. 2540 */ 2541 @Deprecated 2542 public Dimension minimumSize() { 2543 /* Avoid grabbing the lock if a reasonable cached size value 2544 * is available. 2545 */ 2546 Dimension dim = minSize; 2547 if (dim == null || !(isMinimumSizeSet() || isValid())) { 2548 synchronized (getTreeLock()) { 2549 minSize = (peer != null) ? 2550 peer.getMinimumSize() : 2551 size(); 2552 dim = minSize; 2553 } 2554 } 2555 return new Dimension(dim); 2556 } 2557 2558 /** 2559 * Sets the maximum size of this component to a constant 2560 * value. Subsequent calls to <code>getMaximumSize</code> will always 2561 * return this value. Setting the maximum size to <code>null</code> 2562 * restores the default behavior. 2563 * 2564 * @param maximumSize a <code>Dimension</code> containing the 2565 * desired maximum allowable size 2566 * @see #getMaximumSize 2567 * @see #isMaximumSizeSet 2568 * @since 1.5 2569 */ 2570 public void setMaximumSize(Dimension maximumSize) { 2571 // If the maximum size was set, use it as the old value, otherwise 2572 // use null to indicate we didn't previously have a set maximum 2573 // size. 2574 Dimension old; 2575 if (maxSizeSet) { 2576 old = this.maxSize; 2577 } 2578 else { 2579 old = null; 2580 } 2581 this.maxSize = maximumSize; 2582 maxSizeSet = (maximumSize != null); 2583 firePropertyChange("maximumSize", old, maximumSize); 2584 } 2585 2586 /** 2587 * Returns true if the maximum size has been set to a non-<code>null</code> 2588 * value otherwise returns false. 2589 * 2590 * @return true if <code>maximumSize</code> is non-<code>null</code>, 2591 * false otherwise 2592 * @since 1.5 2593 */ 2594 public boolean isMaximumSizeSet() { 2595 return maxSizeSet; 2596 } 2597 2598 /** 2599 * Gets the maximum size of this component. 2600 * @return a dimension object indicating this component's maximum size 2601 * @see #getMinimumSize 2602 * @see #getPreferredSize 2603 * @see LayoutManager 2604 */ 2605 public Dimension getMaximumSize() { 2606 if (isMaximumSizeSet()) { 2607 return new Dimension(maxSize); 2608 } 2609 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); 2610 } 2611 2612 /** 2613 * Returns the alignment along the x axis. This specifies how 2614 * the component would like to be aligned relative to other 2615 * components. The value should be a number between 0 and 1 2616 * where 0 represents alignment along the origin, 1 is aligned 2617 * the furthest away from the origin, 0.5 is centered, etc. 2618 */ 2619 public float getAlignmentX() { 2620 return CENTER_ALIGNMENT; 2621 } 2622 2623 /** 2624 * Returns the alignment along the y axis. This specifies how 2625 * the component would like to be aligned relative to other 2626 * components. The value should be a number between 0 and 1 2627 * where 0 represents alignment along the origin, 1 is aligned 2628 * the furthest away from the origin, 0.5 is centered, etc. 2629 */ 2630 public float getAlignmentY() { 2631 return CENTER_ALIGNMENT; 2632 } 2633 2634 /** 2635 * Returns the baseline. The baseline is measured from the top of 2636 * the component. This method is primarily meant for 2637 * <code>LayoutManager</code>s to align components along their 2638 * baseline. A return value less than 0 indicates this component 2639 * does not have a reasonable baseline and that 2640 * <code>LayoutManager</code>s should not align this component on 2641 * its baseline. 2642 * <p> 2643 * The default implementation returns -1. Subclasses that support 2644 * baseline should override appropriately. If a value >= 0 is 2645 * returned, then the component has a valid baseline for any 2646 * size >= the minimum size and <code>getBaselineResizeBehavior</code> 2647 * can be used to determine how the baseline changes with size. 2648 * 2649 * @param width the width to get the baseline for 2650 * @param height the height to get the baseline for 2651 * @return the baseline or < 0 indicating there is no reasonable 2652 * baseline 2653 * @throws IllegalArgumentException if width or height is < 0 2654 * @see #getBaselineResizeBehavior 2655 * @see java.awt.FontMetrics 2656 * @since 1.6 2657 */ 2658 public int getBaseline(int width, int height) { 2659 if (width < 0 || height < 0) { 2660 throw new IllegalArgumentException( 2661 "Width and height must be >= 0"); 2662 } 2663 return -1; 2664 } 2665 2666 /** 2667 * Returns an enum indicating how the baseline of the component 2668 * changes as the size changes. This method is primarily meant for 2669 * layout managers and GUI builders. 2670 * <p> 2671 * The default implementation returns 2672 * <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a 2673 * baseline should override appropriately. Subclasses should 2674 * never return <code>null</code>; if the baseline can not be 2675 * calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers 2676 * should first ask for the baseline using 2677 * <code>getBaseline</code> and if a value >= 0 is returned use 2678 * this method. It is acceptable for this method to return a 2679 * value other than <code>BaselineResizeBehavior.OTHER</code> even if 2680 * <code>getBaseline</code> returns a value less than 0. 2681 * 2682 * @return an enum indicating how the baseline changes as the component 2683 * size changes 2684 * @see #getBaseline(int, int) 2685 * @since 1.6 2686 */ 2687 public BaselineResizeBehavior getBaselineResizeBehavior() { 2688 return BaselineResizeBehavior.OTHER; 2689 } 2690 2691 /** 2692 * Prompts the layout manager to lay out this component. This is 2693 * usually called when the component (more specifically, container) 2694 * is validated. 2695 * @see #validate 2696 * @see LayoutManager 2697 */ 2698 public void doLayout() { 2699 layout(); 2700 } 2701 2702 /** 2703 * @deprecated As of JDK version 1.1, 2704 * replaced by <code>doLayout()</code>. 2705 */ 2706 @Deprecated 2707 public void layout() { 2708 } 2709 2710 /** 2711 * Ensures that this component has a valid layout. This method is 2712 * primarily intended to operate on instances of <code>Container</code>. 2713 * @see #invalidate 2714 * @see #doLayout() 2715 * @see LayoutManager 2716 * @see Container#validate 2717 * @since JDK1.0 2718 */ 2719 public void validate() { 2720 synchronized (getTreeLock()) { 2721 ComponentPeer peer = this.peer; 2722 boolean wasValid = isValid(); 2723 if (!wasValid && peer != null) { 2724 Font newfont = getFont(); 2725 Font oldfont = peerFont; 2726 if (newfont != oldfont && (oldfont == null 2727 || !oldfont.equals(newfont))) { 2728 peer.setFont(newfont); 2729 peerFont = newfont; 2730 } 2731 peer.layout(); 2732 } 2733 valid = true; 2734 if (!wasValid) { 2735 mixOnValidating(); 2736 } 2737 } 2738 } 2739 2740 /** 2741 * Invalidates this component. This component and all parents 2742 * above it are marked as needing to be laid out. This method can 2743 * be called often, so it needs to execute quickly. 2744 * @see #validate 2745 * @see #doLayout 2746 * @see LayoutManager 2747 * @since JDK1.0 2748 */ 2749 public void invalidate() { 2750 synchronized (getTreeLock()) { 2751 /* Nullify cached layout and size information. 2752 * For efficiency, propagate invalidate() upwards only if 2753 * some other component hasn't already done so first. 2754 */ 2755 valid = false; 2756 if (!isPreferredSizeSet()) { 2757 prefSize = null; 2758 } 2759 if (!isMinimumSizeSet()) { 2760 minSize = null; 2761 } 2762 if (!isMaximumSizeSet()) { 2763 maxSize = null; 2764 } 2765 if (parent != null) { 2766 parent.invalidateIfValid(); 2767 } 2768 } 2769 } 2770 2771 /** Invalidates the component unless it is already invalid. 2772 */ 2773 final void invalidateIfValid() { 2774 if (isValid()) { 2775 invalidate(); 2776 } 2777 } 2778 2779 /** 2780 * Creates a graphics context for this component. This method will 2781 * return <code>null</code> if this component is currently not 2782 * displayable. 2783 * @return a graphics context for this component, or <code>null</code> 2784 * if it has none 2785 * @see #paint 2786 * @since JDK1.0 2787 */ 2788 public Graphics getGraphics() { 2789 if (peer instanceof LightweightPeer) { 2790 // This is for a lightweight component, need to 2791 // translate coordinate spaces and clip relative 2792 // to the parent. 2793 if (parent == null) return null; 2794 Graphics g = parent.getGraphics(); 2795 if (g == null) return null; 2796 if (g instanceof ConstrainableGraphics) { 2797 ((ConstrainableGraphics) g).constrain(x, y, width, height); 2798 } else { 2799 g.translate(x,y); 2800 g.setClip(0, 0, width, height); 2801 } 2802 g.setFont(getFont()); 2803 return g; 2804 } else { 2805 ComponentPeer peer = this.peer; 2806 return (peer != null) ? peer.getGraphics() : null; 2807 } 2808 } 2809 2810 final Graphics getGraphics_NoClientCode() { 2811 ComponentPeer peer = this.peer; 2812 if (peer instanceof LightweightPeer) { 2813 // This is for a lightweight component, need to 2814 // translate coordinate spaces and clip relative 2815 // to the parent. 2816 Container parent = this.parent; 2817 if (parent == null) return null; 2818 Graphics g = parent.getGraphics_NoClientCode(); 2819 if (g == null) return null; 2820 if (g instanceof ConstrainableGraphics) { 2821 ((ConstrainableGraphics) g).constrain(x, y, width, height); 2822 } else { 2823 g.translate(x,y); 2824 g.setClip(0, 0, width, height); 2825 } 2826 g.setFont(getFont_NoClientCode()); 2827 return g; 2828 } else { 2829 return (peer != null) ? peer.getGraphics() : null; 2830 } 2831 } 2832 2833 /** 2834 * Gets the font metrics for the specified font. 2835 * Warning: Since Font metrics are affected by the 2836 * {@link java.awt.font.FontRenderContext FontRenderContext} and 2837 * this method does not provide one, it can return only metrics for 2838 * the default render context which may not match that used when 2839 * rendering on the Component if {@link Graphics2D} functionality is being 2840 * used. Instead metrics can be obtained at rendering time by calling 2841 * {@link Graphics#getFontMetrics()} or text measurement APIs on the 2842 * {@link Font Font} class. 2843 * @param font the font for which font metrics is to be 2844 * obtained 2845 * @return the font metrics for <code>font</code> 2846 * @see #getFont 2847 * @see #getPeer 2848 * @see java.awt.peer.ComponentPeer#getFontMetrics(Font) 2849 * @see Toolkit#getFontMetrics(Font) 2850 * @since JDK1.0 2851 */ 2852 public FontMetrics getFontMetrics(Font font) { 2853 // REMIND: PlatformFont flag should be obsolete soon... 2854 if (sun.font.FontManager.usePlatformFontMetrics()) { 2855 if (peer != null && 2856 !(peer instanceof LightweightPeer)) { 2857 return peer.getFontMetrics(font); 2858 } 2859 } 2860 return sun.font.FontDesignMetrics.getMetrics(font); 2861 } 2862 2863 /** 2864 * Sets the cursor image to the specified cursor. This cursor 2865 * image is displayed when the <code>contains</code> method for 2866 * this component returns true for the current cursor location, and 2867 * this Component is visible, displayable, and enabled. Setting the 2868 * cursor of a <code>Container</code> causes that cursor to be displayed 2869 * within all of the container's subcomponents, except for those 2870 * that have a non-<code>null</code> cursor. 2871 * <p> 2872 * The method may have no visual effect if the Java platform 2873 * implementation and/or the native system do not support 2874 * changing the mouse cursor shape. 2875 * @param cursor One of the constants defined 2876 * by the <code>Cursor</code> class; 2877 * if this parameter is <code>null</code> 2878 * then this component will inherit 2879 * the cursor of its parent 2880 * @see #isEnabled 2881 * @see #isShowing 2882 * @see #getCursor 2883 * @see #contains 2884 * @see Toolkit#createCustomCursor 2885 * @see Cursor 2886 * @since JDK1.1 2887 */ 2888 public void setCursor(Cursor cursor) { 2889 this.cursor = cursor; 2890 updateCursorImmediately(); 2891 } 2892 2893 /** 2894 * Updates the cursor. May not be invoked from the native 2895 * message pump. 2896 */ 2897 final void updateCursorImmediately() { 2898 if (peer instanceof LightweightPeer) { 2899 Container nativeContainer = getNativeContainer(); 2900 2901 if (nativeContainer == null) return; 2902 2903 ComponentPeer cPeer = nativeContainer.getPeer(); 2904 2905 if (cPeer != null) { 2906 cPeer.updateCursorImmediately(); 2907 } 2908 } else if (peer != null) { 2909 peer.updateCursorImmediately(); 2910 } 2911 } 2912 2913 /** 2914 * Gets the cursor set in the component. If the component does 2915 * not have a cursor set, the cursor of its parent is returned. 2916 * If no cursor is set in the entire hierarchy, 2917 * <code>Cursor.DEFAULT_CURSOR</code> is returned. 2918 * @see #setCursor 2919 * @since JDK1.1 2920 */ 2921 public Cursor getCursor() { 2922 return getCursor_NoClientCode(); 2923 } 2924 2925 final Cursor getCursor_NoClientCode() { 2926 Cursor cursor = this.cursor; 2927 if (cursor != null) { 2928 return cursor; 2929 } 2930 Container parent = this.parent; 2931 if (parent != null) { 2932 return parent.getCursor_NoClientCode(); 2933 } else { 2934 return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); 2935 } 2936 } 2937 2938 /** 2939 * Returns whether the cursor has been explicitly set for this Component. 2940 * If this method returns <code>false</code>, this Component is inheriting 2941 * its cursor from an ancestor. 2942 * 2943 * @return <code>true</code> if the cursor has been explicitly set for this 2944 * Component; <code>false</code> otherwise. 2945 * @since 1.4 2946 */ 2947 public boolean isCursorSet() { 2948 return (cursor != null); 2949 } 2950 2951 /** 2952 * Paints this component. 2953 * <p> 2954 * This method is called when the contents of the component should 2955 * be painted; such as when the component is first being shown or 2956 * is damaged and in need of repair. The clip rectangle in the 2957 * <code>Graphics</code> parameter is set to the area 2958 * which needs to be painted. 2959 * Subclasses of <code>Component</code> that override this 2960 * method need not call <code>super.paint(g)</code>. 2961 * <p> 2962 * For performance reasons, <code>Component</code>s with zero width 2963 * or height aren't considered to need painting when they are first shown, 2964 * and also aren't considered to need repair. 2965 * <p> 2966 * <b>Note</b>: For more information on the paint mechanisms utilitized 2967 * by AWT and Swing, including information on how to write the most 2968 * efficient painting code, see 2969 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 2970 * 2971 * @param g the graphics context to use for painting 2972 * @see #update 2973 * @since JDK1.0 2974 */ 2975 public void paint(Graphics g) { 2976 } 2977 2978 /** 2979 * Updates this component. 2980 * <p> 2981 * If this component is not a lightweight component, the 2982 * AWT calls the <code>update</code> method in response to 2983 * a call to <code>repaint</code>. You can assume that 2984 * the background is not cleared. 2985 * <p> 2986 * The <code>update</code> method of <code>Component</code> 2987 * calls this component's <code>paint</code> method to redraw 2988 * this component. This method is commonly overridden by subclasses 2989 * which need to do additional work in response to a call to 2990 * <code>repaint</code>. 2991 * Subclasses of Component that override this method should either 2992 * call <code>super.update(g)</code>, or call <code>paint(g)</code> 2993 * directly from their <code>update</code> method. 2994 * <p> 2995 * The origin of the graphics context, its 2996 * (<code>0</code>, <code>0</code>) coordinate point, is the 2997 * top-left corner of this component. The clipping region of the 2998 * graphics context is the bounding rectangle of this component. 2999 * 3000 * <p> 3001 * <b>Note</b>: For more information on the paint mechanisms utilitized 3002 * by AWT and Swing, including information on how to write the most 3003 * efficient painting code, see 3004 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3005 * 3006 * @param g the specified context to use for updating 3007 * @see #paint 3008 * @see #repaint() 3009 * @since JDK1.0 3010 */ 3011 public void update(Graphics g) { 3012 paint(g); 3013 } 3014 3015 /** 3016 * Paints this component and all of its subcomponents. 3017 * <p> 3018 * The origin of the graphics context, its 3019 * (<code>0</code>, <code>0</code>) coordinate point, is the 3020 * top-left corner of this component. The clipping region of the 3021 * graphics context is the bounding rectangle of this component. 3022 * 3023 * @param g the graphics context to use for painting 3024 * @see #paint 3025 * @since JDK1.0 3026 */ 3027 public void paintAll(Graphics g) { 3028 if (isShowing()) { 3029 GraphicsCallback.PeerPaintCallback.getInstance(). 3030 runOneComponent(this, new Rectangle(0, 0, width, height), 3031 g, g.getClip(), 3032 GraphicsCallback.LIGHTWEIGHTS | 3033 GraphicsCallback.HEAVYWEIGHTS); 3034 } 3035 } 3036 3037 /** 3038 * Simulates the peer callbacks into java.awt for painting of 3039 * lightweight Components. 3040 * @param g the graphics context to use for painting 3041 * @see #paintAll 3042 */ 3043 void lightweightPaint(Graphics g) { 3044 paint(g); 3045 } 3046 3047 /** 3048 * Paints all the heavyweight subcomponents. 3049 */ 3050 void paintHeavyweightComponents(Graphics g) { 3051 } 3052 3053 /** 3054 * Repaints this component. 3055 * <p> 3056 * If this component is a lightweight component, this method 3057 * causes a call to this component's <code>paint</code> 3058 * method as soon as possible. Otherwise, this method causes 3059 * a call to this component's <code>update</code> method as soon 3060 * as possible. 3061 * <p> 3062 * <b>Note</b>: For more information on the paint mechanisms utilitized 3063 * by AWT and Swing, including information on how to write the most 3064 * efficient painting code, see 3065 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3066 3067 * 3068 * @see #update(Graphics) 3069 * @since JDK1.0 3070 */ 3071 public void repaint() { 3072 repaint(0, 0, 0, width, height); 3073 } 3074 3075 /** 3076 * Repaints the component. If this component is a lightweight 3077 * component, this results in a call to <code>paint</code> 3078 * within <code>tm</code> milliseconds. 3079 * <p> 3080 * <b>Note</b>: For more information on the paint mechanisms utilitized 3081 * by AWT and Swing, including information on how to write the most 3082 * efficient painting code, see 3083 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3084 * 3085 * @param tm maximum time in milliseconds before update 3086 * @see #paint 3087 * @see #update(Graphics) 3088 * @since JDK1.0 3089 */ 3090 public void repaint(long tm) { 3091 repaint(tm, 0, 0, width, height); 3092 } 3093 3094 /** 3095 * Repaints the specified rectangle of this component. 3096 * <p> 3097 * If this component is a lightweight component, this method 3098 * causes a call to this component's <code>paint</code> method 3099 * as soon as possible. Otherwise, this method causes a call to 3100 * this component's <code>update</code> method as soon as possible. 3101 * <p> 3102 * <b>Note</b>: For more information on the paint mechanisms utilitized 3103 * by AWT and Swing, including information on how to write the most 3104 * efficient painting code, see 3105 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3106 * 3107 * @param x the <i>x</i> coordinate 3108 * @param y the <i>y</i> coordinate 3109 * @param width the width 3110 * @param height the height 3111 * @see #update(Graphics) 3112 * @since JDK1.0 3113 */ 3114 public void repaint(int x, int y, int width, int height) { 3115 repaint(0, x, y, width, height); 3116 } 3117 3118 /** 3119 * Repaints the specified rectangle of this component within 3120 * <code>tm</code> milliseconds. 3121 * <p> 3122 * If this component is a lightweight component, this method causes 3123 * a call to this component's <code>paint</code> method. 3124 * Otherwise, this method causes a call to this component's 3125 * <code>update</code> method. 3126 * <p> 3127 * <b>Note</b>: For more information on the paint mechanisms utilitized 3128 * by AWT and Swing, including information on how to write the most 3129 * efficient painting code, see 3130 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3131 * 3132 * @param tm maximum time in milliseconds before update 3133 * @param x the <i>x</i> coordinate 3134 * @param y the <i>y</i> coordinate 3135 * @param width the width 3136 * @param height the height 3137 * @see #update(Graphics) 3138 * @since JDK1.0 3139 */ 3140 public void repaint(long tm, int x, int y, int width, int height) { 3141 if (this.peer instanceof LightweightPeer) { 3142 // Needs to be translated to parent coordinates since 3143 // a parent native container provides the actual repaint 3144 // services. Additionally, the request is restricted to 3145 // the bounds of the component. 3146 if (parent != null) { 3147 if (x < 0) { 3148 width += x; 3149 x = 0; 3150 } 3151 if (y < 0) { 3152 height += y; 3153 y = 0; 3154 } 3155 3156 int pwidth = (width > this.width) ? this.width : width; 3157 int pheight = (height > this.height) ? this.height : height; 3158 3159 if (pwidth <= 0 || pheight <= 0) { 3160 return; 3161 } 3162 3163 int px = this.x + x; 3164 int py = this.y + y; 3165 parent.repaint(tm, px, py, pwidth, pheight); 3166 } 3167 } else { 3168 if (isVisible() && (this.peer != null) && 3169 (width > 0) && (height > 0)) { 3170 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE, 3171 new Rectangle(x, y, width, height)); 3172 Toolkit.getEventQueue().postEvent(e); 3173 } 3174 } 3175 } 3176 3177 /** 3178 * Prints this component. Applications should override this method 3179 * for components that must do special processing before being 3180 * printed or should be printed differently than they are painted. 3181 * <p> 3182 * The default implementation of this method calls the 3183 * <code>paint</code> method. 3184 * <p> 3185 * The origin of the graphics context, its 3186 * (<code>0</code>, <code>0</code>) coordinate point, is the 3187 * top-left corner of this component. The clipping region of the 3188 * graphics context is the bounding rectangle of this component. 3189 * @param g the graphics context to use for printing 3190 * @see #paint(Graphics) 3191 * @since JDK1.0 3192 */ 3193 public void print(Graphics g) { 3194 paint(g); 3195 } 3196 3197 /** 3198 * Prints this component and all of its subcomponents. 3199 * <p> 3200 * The origin of the graphics context, its 3201 * (<code>0</code>, <code>0</code>) coordinate point, is the 3202 * top-left corner of this component. The clipping region of the 3203 * graphics context is the bounding rectangle of this component. 3204 * @param g the graphics context to use for printing 3205 * @see #print(Graphics) 3206 * @since JDK1.0 3207 */ 3208 public void printAll(Graphics g) { 3209 if (isShowing()) { 3210 GraphicsCallback.PeerPrintCallback.getInstance(). 3211 runOneComponent(this, new Rectangle(0, 0, width, height), 3212 g, g.getClip(), 3213 GraphicsCallback.LIGHTWEIGHTS | 3214 GraphicsCallback.HEAVYWEIGHTS); 3215 } 3216 } 3217 3218 /** 3219 * Simulates the peer callbacks into java.awt for printing of 3220 * lightweight Components. 3221 * @param g the graphics context to use for printing 3222 * @see #printAll 3223 */ 3224 void lightweightPrint(Graphics g) { 3225 print(g); 3226 } 3227 3228 /** 3229 * Prints all the heavyweight subcomponents. 3230 */ 3231 void printHeavyweightComponents(Graphics g) { 3232 } 3233 3234 private Insets getInsets_NoClientCode() { 3235 ComponentPeer peer = this.peer; 3236 if (peer instanceof ContainerPeer) { 3237 return (Insets)((ContainerPeer)peer).getInsets().clone(); 3238 } 3239 return new Insets(0, 0, 0, 0); 3240 } 3241 3242 /** 3243 * Repaints the component when the image has changed. 3244 * This <code>imageUpdate</code> method of an <code>ImageObserver</code> 3245 * is called when more information about an 3246 * image which had been previously requested using an asynchronous 3247 * routine such as the <code>drawImage</code> method of 3248 * <code>Graphics</code> becomes available. 3249 * See the definition of <code>imageUpdate</code> for 3250 * more information on this method and its arguments. 3251 * <p> 3252 * The <code>imageUpdate</code> method of <code>Component</code> 3253 * incrementally draws an image on the component as more of the bits 3254 * of the image are available. 3255 * <p> 3256 * If the system property <code>awt.image.incrementaldraw</code> 3257 * is missing or has the value <code>true</code>, the image is 3258 * incrementally drawn. If the system property has any other value, 3259 * then the image is not drawn until it has been completely loaded. 3260 * <p> 3261 * Also, if incremental drawing is in effect, the value of the 3262 * system property <code>awt.image.redrawrate</code> is interpreted 3263 * as an integer to give the maximum redraw rate, in milliseconds. If 3264 * the system property is missing or cannot be interpreted as an 3265 * integer, the redraw rate is once every 100ms. 3266 * <p> 3267 * The interpretation of the <code>x</code>, <code>y</code>, 3268 * <code>width</code>, and <code>height</code> arguments depends on 3269 * the value of the <code>infoflags</code> argument. 3270 * 3271 * @param img the image being observed 3272 * @param infoflags see <code>imageUpdate</code> for more information 3273 * @param x the <i>x</i> coordinate 3274 * @param y the <i>y</i> coordinate 3275 * @param w the width 3276 * @param h the height 3277 * @return <code>false</code> if the infoflags indicate that the 3278 * image is completely loaded; <code>true</code> otherwise. 3279 * 3280 * @see java.awt.image.ImageObserver 3281 * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver) 3282 * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver) 3283 * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver) 3284 * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver) 3285 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) 3286 * @since JDK1.0 3287 */ 3288 public boolean imageUpdate(Image img, int infoflags, 3289 int x, int y, int w, int h) { 3290 int rate = -1; 3291 if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) { 3292 rate = 0; 3293 } else if ((infoflags & SOMEBITS) != 0) { 3294 if (isInc) { 3295 rate = incRate; 3296 if (rate < 0) { 3297 rate = 0; 3298 } 3299 } 3300 } 3301 if (rate >= 0) { 3302 repaint(rate, 0, 0, width, height); 3303 } 3304 return (infoflags & (ALLBITS|ABORT)) == 0; 3305 } 3306 3307 /** 3308 * Creates an image from the specified image producer. 3309 * @param producer the image producer 3310 * @return the image produced 3311 * @since JDK1.0 3312 */ 3313 public Image createImage(ImageProducer producer) { 3314 ComponentPeer peer = this.peer; 3315 if ((peer != null) && ! (peer instanceof LightweightPeer)) { 3316 return peer.createImage(producer); 3317 } 3318 return getToolkit().createImage(producer); 3319 } 3320 3321 /** 3322 * Creates an off-screen drawable image 3323 * to be used for double buffering. 3324 * @param width the specified width 3325 * @param height the specified height 3326 * @return an off-screen drawable image, which can be used for double 3327 * buffering. The return value may be <code>null</code> if the 3328 * component is not displayable. This will always happen if 3329 * <code>GraphicsEnvironment.isHeadless()</code> returns 3330 * <code>true</code>. 3331 * @see #isDisplayable 3332 * @see GraphicsEnvironment#isHeadless 3333 * @since JDK1.0 3334 */ 3335 public Image createImage(int width, int height) { 3336 ComponentPeer peer = this.peer; 3337 if (peer instanceof LightweightPeer) { 3338 if (parent != null) { return parent.createImage(width, height); } 3339 else { return null;} 3340 } else { 3341 return (peer != null) ? peer.createImage(width, height) : null; 3342 } 3343 } 3344 3345 /** 3346 * Creates a volatile off-screen drawable image 3347 * to be used for double buffering. 3348 * @param width the specified width. 3349 * @param height the specified height. 3350 * @return an off-screen drawable image, which can be used for double 3351 * buffering. The return value may be <code>null</code> if the 3352 * component is not displayable. This will always happen if 3353 * <code>GraphicsEnvironment.isHeadless()</code> returns 3354 * <code>true</code>. 3355 * @see java.awt.image.VolatileImage 3356 * @see #isDisplayable 3357 * @see GraphicsEnvironment#isHeadless 3358 * @since 1.4 3359 */ 3360 public VolatileImage createVolatileImage(int width, int height) { 3361 ComponentPeer peer = this.peer; 3362 if (peer instanceof LightweightPeer) { 3363 if (parent != null) { 3364 return parent.createVolatileImage(width, height); 3365 } 3366 else { return null;} 3367 } else { 3368 return (peer != null) ? 3369 peer.createVolatileImage(width, height) : null; 3370 } 3371 } 3372 3373 /** 3374 * Creates a volatile off-screen drawable image, with the given capabilities. 3375 * The contents of this image may be lost at any time due 3376 * to operating system issues, so the image must be managed 3377 * via the <code>VolatileImage</code> interface. 3378 * @param width the specified width. 3379 * @param height the specified height. 3380 * @param caps the image capabilities 3381 * @exception AWTException if an image with the specified capabilities cannot 3382 * be created 3383 * @return a VolatileImage object, which can be used 3384 * to manage surface contents loss and capabilities. 3385 * @see java.awt.image.VolatileImage 3386 * @since 1.4 3387 */ 3388 public VolatileImage createVolatileImage(int width, int height, 3389 ImageCapabilities caps) throws AWTException { 3390 // REMIND : check caps 3391 return createVolatileImage(width, height); 3392 } 3393 3394 /** 3395 * Prepares an image for rendering on this component. The image 3396 * data is downloaded asynchronously in another thread and the 3397 * appropriate screen representation of the image is generated. 3398 * @param image the <code>Image</code> for which to 3399 * prepare a screen representation 3400 * @param observer the <code>ImageObserver</code> object 3401 * to be notified as the image is being prepared 3402 * @return <code>true</code> if the image has already been fully 3403 * prepared; <code>false</code> otherwise 3404 * @since JDK1.0 3405 */ 3406 public boolean prepareImage(Image image, ImageObserver observer) { 3407 return prepareImage(image, -1, -1, observer); 3408 } 3409 3410 /** 3411 * Prepares an image for rendering on this component at the 3412 * specified width and height. 3413 * <p> 3414 * The image data is downloaded asynchronously in another thread, 3415 * and an appropriately scaled screen representation of the image is 3416 * generated. 3417 * @param image the instance of <code>Image</code> 3418 * for which to prepare a screen representation 3419 * @param width the width of the desired screen representation 3420 * @param height the height of the desired screen representation 3421 * @param observer the <code>ImageObserver</code> object 3422 * to be notified as the image is being prepared 3423 * @return <code>true</code> if the image has already been fully 3424 * prepared; <code>false</code> otherwise 3425 * @see java.awt.image.ImageObserver 3426 * @since JDK1.0 3427 */ 3428 public boolean prepareImage(Image image, int width, int height, 3429 ImageObserver observer) { 3430 ComponentPeer peer = this.peer; 3431 if (peer instanceof LightweightPeer) { 3432 return (parent != null) 3433 ? parent.prepareImage(image, width, height, observer) 3434 : getToolkit().prepareImage(image, width, height, observer); 3435 } else { 3436 return (peer != null) 3437 ? peer.prepareImage(image, width, height, observer) 3438 : getToolkit().prepareImage(image, width, height, observer); 3439 } 3440 } 3441 3442 /** 3443 * Returns the status of the construction of a screen representation 3444 * of the specified image. 3445 * <p> 3446 * This method does not cause the image to begin loading. An 3447 * application must use the <code>prepareImage</code> method 3448 * to force the loading of an image. 3449 * <p> 3450 * Information on the flags returned by this method can be found 3451 * with the discussion of the <code>ImageObserver</code> interface. 3452 * @param image the <code>Image</code> object whose status 3453 * is being checked 3454 * @param observer the <code>ImageObserver</code> 3455 * object to be notified as the image is being prepared 3456 * @return the bitwise inclusive <b>OR</b> of 3457 * <code>ImageObserver</code> flags indicating what 3458 * information about the image is currently available 3459 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) 3460 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) 3461 * @see java.awt.image.ImageObserver 3462 * @since JDK1.0 3463 */ 3464 public int checkImage(Image image, ImageObserver observer) { 3465 return checkImage(image, -1, -1, observer); 3466 } 3467 3468 /** 3469 * Returns the status of the construction of a screen representation 3470 * of the specified image. 3471 * <p> 3472 * This method does not cause the image to begin loading. An 3473 * application must use the <code>prepareImage</code> method 3474 * to force the loading of an image. 3475 * <p> 3476 * The <code>checkImage</code> method of <code>Component</code> 3477 * calls its peer's <code>checkImage</code> method to calculate 3478 * the flags. If this component does not yet have a peer, the 3479 * component's toolkit's <code>checkImage</code> method is called 3480 * instead. 3481 * <p> 3482 * Information on the flags returned by this method can be found 3483 * with the discussion of the <code>ImageObserver</code> interface. 3484 * @param image the <code>Image</code> object whose status 3485 * is being checked 3486 * @param width the width of the scaled version 3487 * whose status is to be checked 3488 * @param height the height of the scaled version 3489 * whose status is to be checked 3490 * @param observer the <code>ImageObserver</code> object 3491 * to be notified as the image is being prepared 3492 * @return the bitwise inclusive <b>OR</b> of 3493 * <code>ImageObserver</code> flags indicating what 3494 * information about the image is currently available 3495 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) 3496 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) 3497 * @see java.awt.image.ImageObserver 3498 * @since JDK1.0 3499 */ 3500 public int checkImage(Image image, int width, int height, 3501 ImageObserver observer) { 3502 ComponentPeer peer = this.peer; 3503 if (peer instanceof LightweightPeer) { 3504 return (parent != null) 3505 ? parent.checkImage(image, width, height, observer) 3506 : getToolkit().checkImage(image, width, height, observer); 3507 } else { 3508 return (peer != null) 3509 ? peer.checkImage(image, width, height, observer) 3510 : getToolkit().checkImage(image, width, height, observer); 3511 } 3512 } 3513 3514 /** 3515 * Creates a new strategy for multi-buffering on this component. 3516 * Multi-buffering is useful for rendering performance. This method 3517 * attempts to create the best strategy available with the number of 3518 * buffers supplied. It will always create a <code>BufferStrategy</code> 3519 * with that number of buffers. 3520 * A page-flipping strategy is attempted first, then a blitting strategy 3521 * using accelerated buffers. Finally, an unaccelerated blitting 3522 * strategy is used. 3523 * <p> 3524 * Each time this method is called, 3525 * the existing buffer strategy for this component is discarded. 3526 * @param numBuffers number of buffers to create, including the front buffer 3527 * @exception IllegalArgumentException if numBuffers is less than 1. 3528 * @exception IllegalStateException if the component is not displayable 3529 * @see #isDisplayable 3530 * @see Window#getBufferStrategy() 3531 * @see Canvas#getBufferStrategy() 3532 * @since 1.4 3533 */ 3534 void createBufferStrategy(int numBuffers) { 3535 BufferCapabilities bufferCaps; 3536 if (numBuffers > 1) { 3537 // Try to create a page-flipping strategy 3538 bufferCaps = new BufferCapabilities(new ImageCapabilities(true), 3539 new ImageCapabilities(true), 3540 BufferCapabilities.FlipContents.UNDEFINED); 3541 try { 3542 createBufferStrategy(numBuffers, bufferCaps); 3543 return; // Success 3544 } catch (AWTException e) { 3545 // Failed 3546 } 3547 } 3548 // Try a blitting (but still accelerated) strategy 3549 bufferCaps = new BufferCapabilities(new ImageCapabilities(true), 3550 new ImageCapabilities(true), 3551 null); 3552 try { 3553 createBufferStrategy(numBuffers, bufferCaps); 3554 return; // Success 3555 } catch (AWTException e) { 3556 // Failed 3557 } 3558 // Try an unaccelerated blitting strategy 3559 bufferCaps = new BufferCapabilities(new ImageCapabilities(false), 3560 new ImageCapabilities(false), 3561 null); 3562 try { 3563 createBufferStrategy(numBuffers, bufferCaps); 3564 return; // Success 3565 } catch (AWTException e) { 3566 // Failed 3567 } 3568 // Code should never reach here (an unaccelerated blitting 3569 // strategy should always work) 3570 throw new InternalError("Could not create a buffer strategy"); 3571 } 3572 3573 /** 3574 * Creates a new strategy for multi-buffering on this component with the 3575 * required buffer capabilities. This is useful, for example, if only 3576 * accelerated memory or page flipping is desired (as specified by the 3577 * buffer capabilities). 3578 * <p> 3579 * Each time this method 3580 * is called, <code>dispose</code> will be invoked on the existing 3581 * <code>BufferStrategy</code>. 3582 * @param numBuffers number of buffers to create 3583 * @param caps the required capabilities for creating the buffer strategy; 3584 * cannot be <code>null</code> 3585 * @exception AWTException if the capabilities supplied could not be 3586 * supported or met; this may happen, for example, if there is not enough 3587 * accelerated memory currently available, or if page flipping is specified 3588 * but not possible. 3589 * @exception IllegalArgumentException if numBuffers is less than 1, or if 3590 * caps is <code>null</code> 3591 * @see Window#getBufferStrategy() 3592 * @see Canvas#getBufferStrategy() 3593 * @since 1.4 3594 */ 3595 void createBufferStrategy(int numBuffers, 3596 BufferCapabilities caps) throws AWTException { 3597 // Check arguments 3598 if (numBuffers < 1) { 3599 throw new IllegalArgumentException( 3600 "Number of buffers must be at least 1"); 3601 } 3602 if (caps == null) { 3603 throw new IllegalArgumentException("No capabilities specified"); 3604 } 3605 // Destroy old buffers 3606 if (bufferStrategy != null) { 3607 bufferStrategy.dispose(); 3608 } 3609 if (numBuffers == 1) { 3610 bufferStrategy = new SingleBufferStrategy(caps); 3611 } else { 3612 SunGraphicsEnvironment sge = (SunGraphicsEnvironment) 3613 GraphicsEnvironment.getLocalGraphicsEnvironment(); 3614 if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) { 3615 caps = new ProxyCapabilities(caps); 3616 } 3617 // assert numBuffers > 1; 3618 if (caps.isPageFlipping()) { 3619 bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps); 3620 } else { 3621 bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps); 3622 } 3623 } 3624 } 3625 3626 /** 3627 * This is a proxy capabilities class used when a FlipBufferStrategy 3628 * is created instead of the requested Blit strategy. 3629 * 3630 * @see sun.awt.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer) 3631 */ 3632 private class ProxyCapabilities extends ExtendedBufferCapabilities { 3633 private BufferCapabilities orig; 3634 private ProxyCapabilities(BufferCapabilities orig) { 3635 super(orig.getFrontBufferCapabilities(), 3636 orig.getBackBufferCapabilities(), 3637 orig.getFlipContents() == 3638 BufferCapabilities.FlipContents.BACKGROUND ? 3639 BufferCapabilities.FlipContents.BACKGROUND : 3640 BufferCapabilities.FlipContents.COPIED); 3641 this.orig = orig; 3642 } 3643 } 3644 3645 /** 3646 * @return the buffer strategy used by this component 3647 * @see Window#createBufferStrategy 3648 * @see Canvas#createBufferStrategy 3649 * @since 1.4 3650 */ 3651 BufferStrategy getBufferStrategy() { 3652 return bufferStrategy; 3653 } 3654 3655 /** 3656 * @return the back buffer currently used by this component's 3657 * BufferStrategy. If there is no BufferStrategy or no 3658 * back buffer, this method returns null. 3659 */ 3660 Image getBackBuffer() { 3661 if (bufferStrategy != null) { 3662 if (bufferStrategy instanceof BltBufferStrategy) { 3663 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy; 3664 return bltBS.getBackBuffer(); 3665 } else if (bufferStrategy instanceof FlipBufferStrategy) { 3666 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy; 3667 return flipBS.getBackBuffer(); 3668 } 3669 } 3670 return null; 3671 } 3672 3673 /** 3674 * Inner class for flipping buffers on a component. That component must 3675 * be a <code>Canvas</code> or <code>Window</code>. 3676 * @see Canvas 3677 * @see Window 3678 * @see java.awt.image.BufferStrategy 3679 * @author Michael Martak 3680 * @since 1.4 3681 */ 3682 protected class FlipBufferStrategy extends BufferStrategy { 3683 /** 3684 * The number of buffers 3685 */ 3686 protected int numBuffers; // = 0 3687 /** 3688 * The buffering capabilities 3689 */ 3690 protected BufferCapabilities caps; // = null 3691 /** 3692 * The drawing buffer 3693 */ 3694 protected Image drawBuffer; // = null 3695 /** 3696 * The drawing buffer as a volatile image 3697 */ 3698 protected VolatileImage drawVBuffer; // = null 3699 /** 3700 * Whether or not the drawing buffer has been recently restored from 3701 * a lost state. 3702 */ 3703 protected boolean validatedContents; // = false 3704 /** 3705 * Size of the back buffers. (Note: these fields were added in 6.0 3706 * but kept package-private to avoid exposing them in the spec. 3707 * None of these fields/methods really should have been marked 3708 * protected when they were introduced in 1.4, but now we just have 3709 * to live with that decision.) 3710 */ 3711 int width; 3712 int height; 3713 3714 /** 3715 * Creates a new flipping buffer strategy for this component. 3716 * The component must be a <code>Canvas</code> or <code>Window</code>. 3717 * @see Canvas 3718 * @see Window 3719 * @param numBuffers the number of buffers 3720 * @param caps the capabilities of the buffers 3721 * @exception AWTException if the capabilities supplied could not be 3722 * supported or met 3723 * @exception ClassCastException if the component is not a canvas or 3724 * window. 3725 */ 3726 protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps) 3727 throws AWTException 3728 { 3729 if (!(Component.this instanceof Window) && 3730 !(Component.this instanceof Canvas)) 3731 { 3732 throw new ClassCastException( 3733 "Component must be a Canvas or Window"); 3734 } 3735 this.numBuffers = numBuffers; 3736 this.caps = caps; 3737 createBuffers(numBuffers, caps); 3738 } 3739 3740 /** 3741 * Creates one or more complex, flipping buffers with the given 3742 * capabilities. 3743 * @param numBuffers number of buffers to create; must be greater than 3744 * one 3745 * @param caps the capabilities of the buffers. 3746 * <code>BufferCapabilities.isPageFlipping</code> must be 3747 * <code>true</code>. 3748 * @exception AWTException if the capabilities supplied could not be 3749 * supported or met 3750 * @exception IllegalStateException if the component has no peer 3751 * @exception IllegalArgumentException if numBuffers is less than two, 3752 * or if <code>BufferCapabilities.isPageFlipping</code> is not 3753 * <code>true</code>. 3754 * @see java.awt.BufferCapabilities#isPageFlipping() 3755 */ 3756 protected void createBuffers(int numBuffers, BufferCapabilities caps) 3757 throws AWTException 3758 { 3759 if (numBuffers < 2) { 3760 throw new IllegalArgumentException( 3761 "Number of buffers cannot be less than two"); 3762 } else if (peer == null) { 3763 throw new IllegalStateException( 3764 "Component must have a valid peer"); 3765 } else if (caps == null || !caps.isPageFlipping()) { 3766 throw new IllegalArgumentException( 3767 "Page flipping capabilities must be specified"); 3768 } 3769 3770 // save the current bounds 3771 width = getWidth(); 3772 height = getHeight(); 3773 3774 if (drawBuffer != null) { 3775 // dispose the existing backbuffers 3776 drawBuffer = null; 3777 drawVBuffer = null; 3778 destroyBuffers(); 3779 // ... then recreate the backbuffers 3780 } 3781 3782 if (caps instanceof ExtendedBufferCapabilities) { 3783 ExtendedBufferCapabilities ebc = 3784 (ExtendedBufferCapabilities)caps; 3785 if (ebc.getVSync() == VSYNC_ON) { 3786 // if this buffer strategy is not allowed to be v-synced, 3787 // change the caps that we pass to the peer but keep on 3788 // trying to create v-synced buffers; 3789 // do not throw IAE here in case it is disallowed, see 3790 // ExtendedBufferCapabilities for more info 3791 if (!VSyncedBSManager.vsyncAllowed(this)) { 3792 caps = ebc.derive(VSYNC_DEFAULT); 3793 } 3794 } 3795 } 3796 3797 peer.createBuffers(numBuffers, caps); 3798 updateInternalBuffers(); 3799 } 3800 3801 /** 3802 * Updates internal buffers (both volatile and non-volatile) 3803 * by requesting the back-buffer from the peer. 3804 */ 3805 private void updateInternalBuffers() { 3806 // get the images associated with the draw buffer 3807 drawBuffer = getBackBuffer(); 3808 if (drawBuffer instanceof VolatileImage) { 3809 drawVBuffer = (VolatileImage)drawBuffer; 3810 } else { 3811 drawVBuffer = null; 3812 } 3813 } 3814 3815 /** 3816 * @return direct access to the back buffer, as an image. 3817 * @exception IllegalStateException if the buffers have not yet 3818 * been created 3819 */ 3820 protected Image getBackBuffer() { 3821 if (peer != null) { 3822 return peer.getBackBuffer(); 3823 } else { 3824 throw new IllegalStateException( 3825 "Component must have a valid peer"); 3826 } 3827 } 3828 3829 /** 3830 * Flipping moves the contents of the back buffer to the front buffer, 3831 * either by copying or by moving the video pointer. 3832 * @param flipAction an integer value describing the flipping action 3833 * for the contents of the back buffer. This should be one of the 3834 * values of the <code>BufferCapabilities.FlipContents</code> 3835 * property. 3836 * @exception IllegalStateException if the buffers have not yet 3837 * been created 3838 * @see java.awt.BufferCapabilities#getFlipContents() 3839 */ 3840 protected void flip(BufferCapabilities.FlipContents flipAction) { 3841 if (peer != null) { 3842 Image backBuffer = getBackBuffer(); 3843 if (backBuffer != null) { 3844 peer.flip(0, 0, 3845 backBuffer.getWidth(null), 3846 backBuffer.getHeight(null), flipAction); 3847 } 3848 } else { 3849 throw new IllegalStateException( 3850 "Component must have a valid peer"); 3851 } 3852 } 3853 3854 void flipSubRegion(int x1, int y1, int x2, int y2, 3855 BufferCapabilities.FlipContents flipAction) 3856 { 3857 if (peer != null) { 3858 peer.flip(x1, y1, x2, y2, flipAction); 3859 } else { 3860 throw new IllegalStateException( 3861 "Component must have a valid peer"); 3862 } 3863 } 3864 3865 /** 3866 * Destroys the buffers created through this object 3867 */ 3868 protected void destroyBuffers() { 3869 VSyncedBSManager.releaseVsync(this); 3870 if (peer != null) { 3871 peer.destroyBuffers(); 3872 } else { 3873 throw new IllegalStateException( 3874 "Component must have a valid peer"); 3875 } 3876 } 3877 3878 /** 3879 * @return the buffering capabilities of this strategy 3880 */ 3881 public BufferCapabilities getCapabilities() { 3882 if (caps instanceof ProxyCapabilities) { 3883 return ((ProxyCapabilities)caps).orig; 3884 } else { 3885 return caps; 3886 } 3887 } 3888 3889 /** 3890 * @return the graphics on the drawing buffer. This method may not 3891 * be synchronized for performance reasons; use of this method by multiple 3892 * threads should be handled at the application level. Disposal of the 3893 * graphics object must be handled by the application. 3894 */ 3895 public Graphics getDrawGraphics() { 3896 revalidate(); 3897 return drawBuffer.getGraphics(); 3898 } 3899 3900 /** 3901 * Restore the drawing buffer if it has been lost 3902 */ 3903 protected void revalidate() { 3904 revalidate(true); 3905 } 3906 3907 void revalidate(boolean checkSize) { 3908 validatedContents = false; 3909 3910 if (checkSize && (getWidth() != width || getHeight() != height)) { 3911 // component has been resized; recreate the backbuffers 3912 try { 3913 createBuffers(numBuffers, caps); 3914 } catch (AWTException e) { 3915 // shouldn't be possible 3916 } 3917 validatedContents = true; 3918 } 3919 3920 // get the buffers from the peer every time since they 3921 // might have been replaced in response to a display change event 3922 updateInternalBuffers(); 3923 3924 // now validate the backbuffer 3925 if (drawVBuffer != null) { 3926 GraphicsConfiguration gc = 3927 getGraphicsConfiguration_NoClientCode(); 3928 int returnCode = drawVBuffer.validate(gc); 3929 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 3930 try { 3931 createBuffers(numBuffers, caps); 3932 } catch (AWTException e) { 3933 // shouldn't be possible 3934 } 3935 if (drawVBuffer != null) { 3936 // backbuffers were recreated, so validate again 3937 drawVBuffer.validate(gc); 3938 } 3939 validatedContents = true; 3940 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 3941 validatedContents = true; 3942 } 3943 } 3944 } 3945 3946 /** 3947 * @return whether the drawing buffer was lost since the last call to 3948 * <code>getDrawGraphics</code> 3949 */ 3950 public boolean contentsLost() { 3951 if (drawVBuffer == null) { 3952 return false; 3953 } 3954 return drawVBuffer.contentsLost(); 3955 } 3956 3957 /** 3958 * @return whether the drawing buffer was recently restored from a lost 3959 * state and reinitialized to the default background color (white) 3960 */ 3961 public boolean contentsRestored() { 3962 return validatedContents; 3963 } 3964 3965 /** 3966 * Makes the next available buffer visible by either blitting or 3967 * flipping. 3968 */ 3969 public void show() { 3970 flip(caps.getFlipContents()); 3971 } 3972 3973 /** 3974 * Makes specified region of the the next available buffer visible 3975 * by either blitting or flipping. 3976 */ 3977 void showSubRegion(int x1, int y1, int x2, int y2) { 3978 flipSubRegion(x1, y1, x2, y2, caps.getFlipContents()); 3979 } 3980 3981 /** 3982 * {@inheritDoc} 3983 * @since 1.6 3984 */ 3985 public void dispose() { 3986 if (Component.this.bufferStrategy == this) { 3987 Component.this.bufferStrategy = null; 3988 if (peer != null) { 3989 destroyBuffers(); 3990 } 3991 } 3992 } 3993 3994 } // Inner class FlipBufferStrategy 3995 3996 /** 3997 * Inner class for blitting offscreen surfaces to a component. 3998 * 3999 * @author Michael Martak 4000 * @since 1.4 4001 */ 4002 protected class BltBufferStrategy extends BufferStrategy { 4003 4004 /** 4005 * The buffering capabilities 4006 */ 4007 protected BufferCapabilities caps; // = null 4008 /** 4009 * The back buffers 4010 */ 4011 protected VolatileImage[] backBuffers; // = null 4012 /** 4013 * Whether or not the drawing buffer has been recently restored from 4014 * a lost state. 4015 */ 4016 protected boolean validatedContents; // = false 4017 /** 4018 * Size of the back buffers 4019 */ 4020 protected int width; 4021 protected int height; 4022 4023 /** 4024 * Insets for the hosting Component. The size of the back buffer 4025 * is constrained by these. 4026 */ 4027 private Insets insets; 4028 4029 /** 4030 * Creates a new blt buffer strategy around a component 4031 * @param numBuffers number of buffers to create, including the 4032 * front buffer 4033 * @param caps the capabilities of the buffers 4034 */ 4035 protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) { 4036 this.caps = caps; 4037 createBackBuffers(numBuffers - 1); 4038 } 4039 4040 /** 4041 * {@inheritDoc} 4042 * @since 1.6 4043 */ 4044 public void dispose() { 4045 if (backBuffers != null) { 4046 for (int counter = backBuffers.length - 1; counter >= 0; 4047 counter--) { 4048 if (backBuffers[counter] != null) { 4049 backBuffers[counter].flush(); 4050 backBuffers[counter] = null; 4051 } 4052 } 4053 } 4054 if (Component.this.bufferStrategy == this) { 4055 Component.this.bufferStrategy = null; 4056 } 4057 } 4058 4059 /** 4060 * Creates the back buffers 4061 */ 4062 protected void createBackBuffers(int numBuffers) { 4063 if (numBuffers == 0) { 4064 backBuffers = null; 4065 } else { 4066 // save the current bounds 4067 width = getWidth(); 4068 height = getHeight(); 4069 insets = getInsets_NoClientCode(); 4070 int iWidth = width - insets.left - insets.right; 4071 int iHeight = height - insets.top - insets.bottom; 4072 4073 // It is possible for the component's width and/or height 4074 // to be 0 here. Force the size of the backbuffers to 4075 // be > 0 so that creating the image won't fail. 4076 iWidth = Math.max(1, iWidth); 4077 iHeight = Math.max(1, iHeight); 4078 if (backBuffers == null) { 4079 backBuffers = new VolatileImage[numBuffers]; 4080 } else { 4081 // flush any existing backbuffers 4082 for (int i = 0; i < numBuffers; i++) { 4083 if (backBuffers[i] != null) { 4084 backBuffers[i].flush(); 4085 backBuffers[i] = null; 4086 } 4087 } 4088 } 4089 4090 // create the backbuffers 4091 for (int i = 0; i < numBuffers; i++) { 4092 backBuffers[i] = createVolatileImage(iWidth, iHeight); 4093 } 4094 } 4095 } 4096 4097 /** 4098 * @return the buffering capabilities of this strategy 4099 */ 4100 public BufferCapabilities getCapabilities() { 4101 return caps; 4102 } 4103 4104 /** 4105 * @return the draw graphics 4106 */ 4107 public Graphics getDrawGraphics() { 4108 revalidate(); 4109 Image backBuffer = getBackBuffer(); 4110 if (backBuffer == null) { 4111 return getGraphics(); 4112 } 4113 SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics(); 4114 g.constrain(-insets.left, -insets.top, 4115 backBuffer.getWidth(null) + insets.left, 4116 backBuffer.getHeight(null) + insets.top); 4117 return g; 4118 } 4119 4120 /** 4121 * @return direct access to the back buffer, as an image. 4122 * If there is no back buffer, returns null. 4123 */ 4124 Image getBackBuffer() { 4125 if (backBuffers != null) { 4126 return backBuffers[backBuffers.length - 1]; 4127 } else { 4128 return null; 4129 } 4130 } 4131 4132 /** 4133 * Makes the next available buffer visible. 4134 */ 4135 public void show() { 4136 showSubRegion(insets.left, insets.top, 4137 width - insets.right, 4138 height - insets.bottom); 4139 } 4140 4141 /** 4142 * Package-private method to present a specific rectangular area 4143 * of this buffer. This class currently shows only the entire 4144 * buffer, by calling showSubRegion() with the full dimensions of 4145 * the buffer. Subclasses (e.g., BltSubRegionBufferStrategy 4146 * and FlipSubRegionBufferStrategy) may have region-specific show 4147 * methods that call this method with actual sub regions of the 4148 * buffer. 4149 */ 4150 void showSubRegion(int x1, int y1, int x2, int y2) { 4151 if (backBuffers == null) { 4152 return; 4153 } 4154 // Adjust location to be relative to client area. 4155 x1 -= insets.left; 4156 x2 -= insets.left; 4157 y1 -= insets.top; 4158 y2 -= insets.top; 4159 Graphics g = getGraphics_NoClientCode(); 4160 if (g == null) { 4161 // Not showing, bail 4162 return; 4163 } 4164 try { 4165 // First image copy is in terms of Frame's coordinates, need 4166 // to translate to client area. 4167 g.translate(insets.left, insets.top); 4168 for (int i = 0; i < backBuffers.length; i++) { 4169 g.drawImage(backBuffers[i], 4170 x1, y1, x2, y2, 4171 x1, y1, x2, y2, 4172 null); 4173 g.dispose(); 4174 g = null; 4175 g = backBuffers[i].getGraphics(); 4176 } 4177 } finally { 4178 if (g != null) { 4179 g.dispose(); 4180 } 4181 } 4182 } 4183 4184 /** 4185 * Restore the drawing buffer if it has been lost 4186 */ 4187 protected void revalidate() { 4188 revalidate(true); 4189 } 4190 4191 void revalidate(boolean checkSize) { 4192 validatedContents = false; 4193 4194 if (backBuffers == null) { 4195 return; 4196 } 4197 4198 if (checkSize) { 4199 Insets insets = getInsets_NoClientCode(); 4200 if (getWidth() != width || getHeight() != height || 4201 !insets.equals(this.insets)) { 4202 // component has been resized; recreate the backbuffers 4203 createBackBuffers(backBuffers.length); 4204 validatedContents = true; 4205 } 4206 } 4207 4208 // now validate the backbuffer 4209 GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); 4210 int returnCode = 4211 backBuffers[backBuffers.length - 1].validate(gc); 4212 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 4213 if (checkSize) { 4214 createBackBuffers(backBuffers.length); 4215 // backbuffers were recreated, so validate again 4216 backBuffers[backBuffers.length - 1].validate(gc); 4217 } 4218 // else case means we're called from Swing on the toolkit 4219 // thread, don't recreate buffers as that'll deadlock 4220 // (creating VolatileImages invokes getting GraphicsConfig 4221 // which grabs treelock). 4222 validatedContents = true; 4223 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 4224 validatedContents = true; 4225 } 4226 } 4227 4228 /** 4229 * @return whether the drawing buffer was lost since the last call to 4230 * <code>getDrawGraphics</code> 4231 */ 4232 public boolean contentsLost() { 4233 if (backBuffers == null) { 4234 return false; 4235 } else { 4236 return backBuffers[backBuffers.length - 1].contentsLost(); 4237 } 4238 } 4239 4240 /** 4241 * @return whether the drawing buffer was recently restored from a lost 4242 * state and reinitialized to the default background color (white) 4243 */ 4244 public boolean contentsRestored() { 4245 return validatedContents; 4246 } 4247 } // Inner class BltBufferStrategy 4248 4249 /** 4250 * Private class to perform sub-region flipping. 4251 */ 4252 private class FlipSubRegionBufferStrategy extends FlipBufferStrategy 4253 implements SubRegionShowable 4254 { 4255 4256 protected FlipSubRegionBufferStrategy(int numBuffers, 4257 BufferCapabilities caps) 4258 throws AWTException 4259 { 4260 super(numBuffers, caps); 4261 } 4262 4263 public void show(int x1, int y1, int x2, int y2) { 4264 showSubRegion(x1, y1, x2, y2); 4265 } 4266 4267 // This is invoked by Swing on the toolkit thread. 4268 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4269 if (!contentsLost()) { 4270 showSubRegion(x1, y1, x2, y2); 4271 return !contentsLost(); 4272 } 4273 return false; 4274 } 4275 } 4276 4277 /** 4278 * Private class to perform sub-region blitting. Swing will use 4279 * this subclass via the SubRegionShowable interface in order to 4280 * copy only the area changed during a repaint. 4281 * @see javax.swing.BufferStrategyPaintManager 4282 */ 4283 private class BltSubRegionBufferStrategy extends BltBufferStrategy 4284 implements SubRegionShowable 4285 { 4286 4287 protected BltSubRegionBufferStrategy(int numBuffers, 4288 BufferCapabilities caps) 4289 { 4290 super(numBuffers, caps); 4291 } 4292 4293 public void show(int x1, int y1, int x2, int y2) { 4294 showSubRegion(x1, y1, x2, y2); 4295 } 4296 4297 // This method is called by Swing on the toolkit thread. 4298 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4299 if (!contentsLost()) { 4300 showSubRegion(x1, y1, x2, y2); 4301 return !contentsLost(); 4302 } 4303 return false; 4304 } 4305 } 4306 4307 /** 4308 * Inner class for flipping buffers on a component. That component must 4309 * be a <code>Canvas</code> or <code>Window</code>. 4310 * @see Canvas 4311 * @see Window 4312 * @see java.awt.image.BufferStrategy 4313 * @author Michael Martak 4314 * @since 1.4 4315 */ 4316 private class SingleBufferStrategy extends BufferStrategy { 4317 4318 private BufferCapabilities caps; 4319 4320 public SingleBufferStrategy(BufferCapabilities caps) { 4321 this.caps = caps; 4322 } 4323 public BufferCapabilities getCapabilities() { 4324 return caps; 4325 } 4326 public Graphics getDrawGraphics() { 4327 return getGraphics(); 4328 } 4329 public boolean contentsLost() { 4330 return false; 4331 } 4332 public boolean contentsRestored() { 4333 return false; 4334 } 4335 public void show() { 4336 // Do nothing 4337 } 4338 } // Inner class SingleBufferStrategy 4339 4340 /** 4341 * Sets whether or not paint messages received from the operating system 4342 * should be ignored. This does not affect paint events generated in 4343 * software by the AWT, unless they are an immediate response to an 4344 * OS-level paint message. 4345 * <p> 4346 * This is useful, for example, if running under full-screen mode and 4347 * better performance is desired, or if page-flipping is used as the 4348 * buffer strategy. 4349 * 4350 * @since 1.4 4351 * @see #getIgnoreRepaint 4352 * @see Canvas#createBufferStrategy 4353 * @see Window#createBufferStrategy 4354 * @see java.awt.image.BufferStrategy 4355 * @see GraphicsDevice#setFullScreenWindow 4356 */ 4357 public void setIgnoreRepaint(boolean ignoreRepaint) { 4358 this.ignoreRepaint = ignoreRepaint; 4359 } 4360 4361 /** 4362 * @return whether or not paint messages received from the operating system 4363 * should be ignored. 4364 * 4365 * @since 1.4 4366 * @see #setIgnoreRepaint 4367 */ 4368 public boolean getIgnoreRepaint() { 4369 return ignoreRepaint; 4370 } 4371 4372 /** 4373 * Checks whether this component "contains" the specified point, 4374 * where <code>x</code> and <code>y</code> are defined to be 4375 * relative to the coordinate system of this component. 4376 * @param x the <i>x</i> coordinate of the point 4377 * @param y the <i>y</i> coordinate of the point 4378 * @see #getComponentAt(int, int) 4379 * @since JDK1.1 4380 */ 4381 public boolean contains(int x, int y) { 4382 return inside(x, y); 4383 } 4384 4385 /** 4386 * @deprecated As of JDK version 1.1, 4387 * replaced by contains(int, int). 4388 */ 4389 @Deprecated 4390 public boolean inside(int x, int y) { 4391 return (x >= 0) && (x < width) && (y >= 0) && (y < height); 4392 } 4393 4394 /** 4395 * Checks whether this component "contains" the specified point, 4396 * where the point's <i>x</i> and <i>y</i> coordinates are defined 4397 * to be relative to the coordinate system of this component. 4398 * @param p the point 4399 * @see #getComponentAt(Point) 4400 * @since JDK1.1 4401 */ 4402 public boolean contains(Point p) { 4403 return contains(p.x, p.y); 4404 } 4405 4406 /** 4407 * Determines if this component or one of its immediate 4408 * subcomponents contains the (<i>x</i>, <i>y</i>) location, 4409 * and if so, returns the containing component. This method only 4410 * looks one level deep. If the point (<i>x</i>, <i>y</i>) is 4411 * inside a subcomponent that itself has subcomponents, it does not 4412 * go looking down the subcomponent tree. 4413 * <p> 4414 * The <code>locate</code> method of <code>Component</code> simply 4415 * returns the component itself if the (<i>x</i>, <i>y</i>) 4416 * coordinate location is inside its bounding box, and <code>null</code> 4417 * otherwise. 4418 * @param x the <i>x</i> coordinate 4419 * @param y the <i>y</i> coordinate 4420 * @return the component or subcomponent that contains the 4421 * (<i>x</i>, <i>y</i>) location; 4422 * <code>null</code> if the location 4423 * is outside this component 4424 * @see #contains(int, int) 4425 * @since JDK1.0 4426 */ 4427 public Component getComponentAt(int x, int y) { 4428 return locate(x, y); 4429 } 4430 4431 /** 4432 * @deprecated As of JDK version 1.1, 4433 * replaced by getComponentAt(int, int). 4434 */ 4435 @Deprecated 4436 public Component locate(int x, int y) { 4437 return contains(x, y) ? this : null; 4438 } 4439 4440 /** 4441 * Returns the component or subcomponent that contains the 4442 * specified point. 4443 * @param p the point 4444 * @see java.awt.Component#contains 4445 * @since JDK1.1 4446 */ 4447 public Component getComponentAt(Point p) { 4448 return getComponentAt(p.x, p.y); 4449 } 4450 4451 /** 4452 * @deprecated As of JDK version 1.1, 4453 * replaced by <code>dispatchEvent(AWTEvent e)</code>. 4454 */ 4455 @Deprecated 4456 public void deliverEvent(Event e) { 4457 postEvent(e); 4458 } 4459 4460 /** 4461 * Dispatches an event to this component or one of its sub components. 4462 * Calls <code>processEvent</code> before returning for 1.1-style 4463 * events which have been enabled for the <code>Component</code>. 4464 * @param e the event 4465 */ 4466 public final void dispatchEvent(AWTEvent e) { 4467 dispatchEventImpl(e); 4468 } 4469 4470 void dispatchEventImpl(AWTEvent e) { 4471 int id = e.getID(); 4472 4473 // Check that this component belongs to this app-context 4474 AppContext compContext = appContext; 4475 if (compContext != null && !compContext.equals(AppContext.getAppContext())) { 4476 if (eventLog.isLoggable(Level.FINE)) { 4477 eventLog.log(Level.FINE, "Event " + e + " is being dispatched on the wrong AppContext"); 4478 } 4479 } 4480 4481 if (eventLog.isLoggable(Level.FINEST)) { 4482 eventLog.log(Level.FINEST, "{0}", e); 4483 } 4484 4485 /* 4486 * 0. Set timestamp and modifiers of current event. 4487 */ 4488 EventQueue.setCurrentEventAndMostRecentTime(e); 4489 4490 /* 4491 * 1. Pre-dispatchers. Do any necessary retargeting/reordering here 4492 * before we notify AWTEventListeners. 4493 */ 4494 4495 if (e instanceof SunDropTargetEvent) { 4496 ((SunDropTargetEvent)e).dispatch(); 4497 return; 4498 } 4499 4500 if (!e.focusManagerIsDispatching) { 4501 // Invoke the private focus retargeting method which provides 4502 // lightweight Component support 4503 if (e.isPosted) { 4504 e = KeyboardFocusManager.retargetFocusEvent(e); 4505 e.isPosted = true; 4506 } 4507 4508 // Now, with the event properly targeted to a lightweight 4509 // descendant if necessary, invoke the public focus retargeting 4510 // and dispatching function 4511 if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 4512 dispatchEvent(e)) 4513 { 4514 return; 4515 } 4516 } 4517 if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) { 4518 focusLog.log(Level.FINEST, "" + e); 4519 } 4520 // MouseWheel may need to be retargeted here so that 4521 // AWTEventListener sees the event go to the correct 4522 // Component. If the MouseWheelEvent needs to go to an ancestor, 4523 // the event is dispatched to the ancestor, and dispatching here 4524 // stops. 4525 if (id == MouseEvent.MOUSE_WHEEL && 4526 (!eventTypeEnabled(id)) && 4527 (peer != null && !peer.handlesWheelScrolling()) && 4528 (dispatchMouseWheelToAncestor((MouseWheelEvent)e))) 4529 { 4530 return; 4531 } 4532 4533 /* 4534 * 2. Allow the Toolkit to pass this to AWTEventListeners. 4535 */ 4536 Toolkit toolkit = Toolkit.getDefaultToolkit(); 4537 toolkit.notifyAWTEventListeners(e); 4538 4539 4540 /* 4541 * 3. If no one has consumed a key event, allow the 4542 * KeyboardFocusManager to process it. 4543 */ 4544 if (!e.isConsumed()) { 4545 if (e instanceof java.awt.event.KeyEvent) { 4546 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 4547 processKeyEvent(this, (KeyEvent)e); 4548 if (e.isConsumed()) { 4549 return; 4550 } 4551 } 4552 } 4553 4554 /* 4555 * 4. Allow input methods to process the event 4556 */ 4557 if (areInputMethodsEnabled()) { 4558 // We need to pass on InputMethodEvents since some host 4559 // input method adapters send them through the Java 4560 // event queue instead of directly to the component, 4561 // and the input context also handles the Java composition window 4562 if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea)) 4563 || 4564 // Otherwise, we only pass on input and focus events, because 4565 // a) input methods shouldn't know about semantic or component-level events 4566 // b) passing on the events takes time 4567 // c) isConsumed() is always true for semantic events. 4568 (e instanceof InputEvent) || (e instanceof FocusEvent)) { 4569 InputContext inputContext = getInputContext(); 4570 4571 4572 if (inputContext != null) { 4573 inputContext.dispatchEvent(e); 4574 if (e.isConsumed()) { 4575 if ((e instanceof FocusEvent) && focusLog.isLoggable(Level.FINEST)) { 4576 focusLog.log(Level.FINEST, "3579: Skipping " + e); 4577 } 4578 return; 4579 } 4580 } 4581 } 4582 } else { 4583 // When non-clients get focus, we need to explicitly disable the native 4584 // input method. The native input method is actually not disabled when 4585 // the active/passive/peered clients loose focus. 4586 if (id == FocusEvent.FOCUS_GAINED) { 4587 InputContext inputContext = getInputContext(); 4588 if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) { 4589 ((sun.awt.im.InputContext)inputContext).disableNativeIM(); 4590 } 4591 } 4592 } 4593 4594 4595 /* 4596 * 5. Pre-process any special events before delivery 4597 */ 4598 switch(id) { 4599 // Handling of the PAINT and UPDATE events is now done in the 4600 // peer's handleEvent() method so the background can be cleared 4601 // selectively for non-native components on Windows only. 4602 // - Fred.Ecks@Eng.sun.com, 5-8-98 4603 4604 case KeyEvent.KEY_PRESSED: 4605 case KeyEvent.KEY_RELEASED: 4606 Container p = (Container)((this instanceof Container) ? this : parent); 4607 if (p != null) { 4608 p.preProcessKeyEvent((KeyEvent)e); 4609 if (e.isConsumed()) { 4610 if (focusLog.isLoggable(Level.FINEST)) { 4611 focusLog.log(Level.FINEST, "Pre-process consumed event"); 4612 } 4613 return; 4614 } 4615 } 4616 break; 4617 4618 case WindowEvent.WINDOW_CLOSING: 4619 if (toolkit instanceof WindowClosingListener) { 4620 windowClosingException = ((WindowClosingListener) 4621 toolkit).windowClosingNotify((WindowEvent)e); 4622 if (checkWindowClosingException()) { 4623 return; 4624 } 4625 } 4626 break; 4627 4628 default: 4629 break; 4630 } 4631 4632 /* 4633 * 6. Deliver event for normal processing 4634 */ 4635 if (newEventsOnly) { 4636 // Filtering needs to really be moved to happen at a lower 4637 // level in order to get maximum performance gain; it is 4638 // here temporarily to ensure the API spec is honored. 4639 // 4640 if (eventEnabled(e)) { 4641 processEvent(e); 4642 } 4643 } else if (id == MouseEvent.MOUSE_WHEEL) { 4644 // newEventsOnly will be false for a listenerless ScrollPane, but 4645 // MouseWheelEvents still need to be dispatched to it so scrolling 4646 // can be done. 4647 autoProcessMouseWheel((MouseWheelEvent)e); 4648 } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) { 4649 // 4650 // backward compatibility 4651 // 4652 Event olde = e.convertToOld(); 4653 if (olde != null) { 4654 int key = olde.key; 4655 int modifiers = olde.modifiers; 4656 4657 postEvent(olde); 4658 if (olde.isConsumed()) { 4659 e.consume(); 4660 } 4661 // if target changed key or modifier values, copy them 4662 // back to original event 4663 // 4664 switch(olde.id) { 4665 case Event.KEY_PRESS: 4666 case Event.KEY_RELEASE: 4667 case Event.KEY_ACTION: 4668 case Event.KEY_ACTION_RELEASE: 4669 if (olde.key != key) { 4670 ((KeyEvent)e).setKeyChar(olde.getKeyEventChar()); 4671 } 4672 if (olde.modifiers != modifiers) { 4673 ((KeyEvent)e).setModifiers(olde.modifiers); 4674 } 4675 break; 4676 default: 4677 break; 4678 } 4679 } 4680 } 4681 4682 /* 4683 * 8. Special handling for 4061116 : Hook for browser to close modal 4684 * dialogs. 4685 */ 4686 if (id == WindowEvent.WINDOW_CLOSING && !e.isConsumed()) { 4687 if (toolkit instanceof WindowClosingListener) { 4688 windowClosingException = 4689 ((WindowClosingListener)toolkit). 4690 windowClosingDelivered((WindowEvent)e); 4691 if (checkWindowClosingException()) { 4692 return; 4693 } 4694 } 4695 } 4696 4697 /* 4698 * 9. Allow the peer to process the event. 4699 * Except KeyEvents, they will be processed by peer after 4700 * all KeyEventPostProcessors 4701 * (see DefaultKeyboardFocusManager.dispatchKeyEvent()) 4702 */ 4703 if (!(e instanceof KeyEvent)) { 4704 ComponentPeer tpeer = peer; 4705 if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) { 4706 // if focus owner is lightweight then its native container 4707 // processes event 4708 Component source = (Component)e.getSource(); 4709 if (source != null) { 4710 Container target = source.getNativeContainer(); 4711 if (target != null) { 4712 tpeer = target.getPeer(); 4713 } 4714 } 4715 } 4716 if (tpeer != null) { 4717 tpeer.handleEvent(e); 4718 } 4719 } 4720 } // dispatchEventImpl() 4721 4722 /* 4723 * If newEventsOnly is false, method is called so that ScrollPane can 4724 * override it and handle common-case mouse wheel scrolling. NOP 4725 * for Component. 4726 */ 4727 void autoProcessMouseWheel(MouseWheelEvent e) {} 4728 4729 /* 4730 * Dispatch given MouseWheelEvent to the first ancestor for which 4731 * MouseWheelEvents are enabled. 4732 * 4733 * Returns whether or not event was dispatched to an ancestor 4734 */ 4735 boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) { 4736 int newX, newY; 4737 newX = e.getX() + getX(); // Coordinates take into account at least 4738 newY = e.getY() + getY(); // the cursor's position relative to this 4739 // Component (e.getX()), and this Component's 4740 // position relative to its parent. 4741 MouseWheelEvent newMWE; 4742 4743 if (eventLog.isLoggable(Level.FINEST)) { 4744 eventLog.log(Level.FINEST, "dispatchMouseWheelToAncestor"); 4745 eventLog.log(Level.FINEST, "orig event src is of " + e.getSource().getClass()); 4746 } 4747 4748 /* parent field for Window refers to the owning Window. 4749 * MouseWheelEvents should NOT be propagated into owning Windows 4750 */ 4751 synchronized (getTreeLock()) { 4752 Container anc = getParent(); 4753 while (anc != null && !anc.eventEnabled(e)) { 4754 // fix coordinates to be relative to new event source 4755 newX += anc.getX(); 4756 newY += anc.getY(); 4757 4758 if (!(anc instanceof Window)) { 4759 anc = anc.getParent(); 4760 } 4761 else { 4762 break; 4763 } 4764 } 4765 4766 if (eventLog.isLoggable(Level.FINEST)) { 4767 eventLog.log(Level.FINEST, "new event src is " + anc.getClass()); 4768 } 4769 4770 if (anc != null && anc.eventEnabled(e)) { 4771 // Change event to be from new source, with new x,y 4772 // For now, just create a new event - yucky 4773 4774 newMWE = new MouseWheelEvent(anc, // new source 4775 e.getID(), 4776 e.getWhen(), 4777 e.getModifiers(), 4778 newX, // x relative to new source 4779 newY, // y relative to new source 4780 e.getXOnScreen(), 4781 e.getYOnScreen(), 4782 e.getClickCount(), 4783 e.isPopupTrigger(), 4784 e.getScrollType(), 4785 e.getScrollAmount(), 4786 e.getWheelRotation(), 4787 e.getPreciseWheelRotation()); 4788 ((AWTEvent)e).copyPrivateDataInto(newMWE); 4789 // When dispatching a wheel event to 4790 // ancestor, there is no need trying to find descendant 4791 // lightweights to dispatch event to. 4792 // If we dispatch the event to toplevel ancestor, 4793 // this could encolse the loop: 6480024. 4794 anc.dispatchEventToSelf(newMWE); 4795 } 4796 } 4797 return true; 4798 } 4799 4800 boolean checkWindowClosingException() { 4801 if (windowClosingException != null) { 4802 if (this instanceof Dialog) { 4803 ((Dialog)this).interruptBlocking(); 4804 } else { 4805 windowClosingException.fillInStackTrace(); 4806 windowClosingException.printStackTrace(); 4807 windowClosingException = null; 4808 } 4809 return true; 4810 } 4811 return false; 4812 } 4813 4814 boolean areInputMethodsEnabled() { 4815 // in 1.2, we assume input method support is required for all 4816 // components that handle key events, but components can turn off 4817 // input methods by calling enableInputMethods(false). 4818 return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) && 4819 ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null); 4820 } 4821 4822 // REMIND: remove when filtering is handled at lower level 4823 boolean eventEnabled(AWTEvent e) { 4824 return eventTypeEnabled(e.id); 4825 } 4826 4827 boolean eventTypeEnabled(int type) { 4828 switch(type) { 4829 case ComponentEvent.COMPONENT_MOVED: 4830 case ComponentEvent.COMPONENT_RESIZED: 4831 case ComponentEvent.COMPONENT_SHOWN: 4832 case ComponentEvent.COMPONENT_HIDDEN: 4833 if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 4834 componentListener != null) { 4835 return true; 4836 } 4837 break; 4838 case FocusEvent.FOCUS_GAINED: 4839 case FocusEvent.FOCUS_LOST: 4840 if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 || 4841 focusListener != null) { 4842 return true; 4843 } 4844 break; 4845 case KeyEvent.KEY_PRESSED: 4846 case KeyEvent.KEY_RELEASED: 4847 case KeyEvent.KEY_TYPED: 4848 if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || 4849 keyListener != null) { 4850 return true; 4851 } 4852 break; 4853 case MouseEvent.MOUSE_PRESSED: 4854 case MouseEvent.MOUSE_RELEASED: 4855 case MouseEvent.MOUSE_ENTERED: 4856 case MouseEvent.MOUSE_EXITED: 4857 case MouseEvent.MOUSE_CLICKED: 4858 if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 || 4859 mouseListener != null) { 4860 return true; 4861 } 4862 break; 4863 case MouseEvent.MOUSE_MOVED: 4864 case MouseEvent.MOUSE_DRAGGED: 4865 if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 || 4866 mouseMotionListener != null) { 4867 return true; 4868 } 4869 break; 4870 case MouseEvent.MOUSE_WHEEL: 4871 if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 || 4872 mouseWheelListener != null) { 4873 return true; 4874 } 4875 break; 4876 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: 4877 case InputMethodEvent.CARET_POSITION_CHANGED: 4878 if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 || 4879 inputMethodListener != null) { 4880 return true; 4881 } 4882 break; 4883 case HierarchyEvent.HIERARCHY_CHANGED: 4884 if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 4885 hierarchyListener != null) { 4886 return true; 4887 } 4888 break; 4889 case HierarchyEvent.ANCESTOR_MOVED: 4890 case HierarchyEvent.ANCESTOR_RESIZED: 4891 if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || 4892 hierarchyBoundsListener != null) { 4893 return true; 4894 } 4895 break; 4896 case ActionEvent.ACTION_PERFORMED: 4897 if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) { 4898 return true; 4899 } 4900 break; 4901 case TextEvent.TEXT_VALUE_CHANGED: 4902 if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) { 4903 return true; 4904 } 4905 break; 4906 case ItemEvent.ITEM_STATE_CHANGED: 4907 if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) { 4908 return true; 4909 } 4910 break; 4911 case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED: 4912 if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) { 4913 return true; 4914 } 4915 break; 4916 default: 4917 break; 4918 } 4919 // 4920 // Always pass on events defined by external programs. 4921 // 4922 if (type > AWTEvent.RESERVED_ID_MAX) { 4923 return true; 4924 } 4925 return false; 4926 } 4927 4928 /** 4929 * @deprecated As of JDK version 1.1, 4930 * replaced by dispatchEvent(AWTEvent). 4931 */ 4932 @Deprecated 4933 public boolean postEvent(Event e) { 4934 ComponentPeer peer = this.peer; 4935 4936 if (handleEvent(e)) { 4937 e.consume(); 4938 return true; 4939 } 4940 4941 Component parent = this.parent; 4942 int eventx = e.x; 4943 int eventy = e.y; 4944 if (parent != null) { 4945 e.translate(x, y); 4946 if (parent.postEvent(e)) { 4947 e.consume(); 4948 return true; 4949 } 4950 // restore coords 4951 e.x = eventx; 4952 e.y = eventy; 4953 } 4954 return false; 4955 } 4956 4957 // Event source interfaces 4958 4959 /** 4960 * Adds the specified component listener to receive component events from 4961 * this component. 4962 * If listener <code>l</code> is <code>null</code>, 4963 * no exception is thrown and no action is performed. 4964 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 4965 * >AWT Threading Issues</a> for details on AWT's threading model. 4966 * 4967 * @param l the component listener 4968 * @see java.awt.event.ComponentEvent 4969 * @see java.awt.event.ComponentListener 4970 * @see #removeComponentListener 4971 * @see #getComponentListeners 4972 * @since JDK1.1 4973 */ 4974 public synchronized void addComponentListener(ComponentListener l) { 4975 if (l == null) { 4976 return; 4977 } 4978 componentListener = AWTEventMulticaster.add(componentListener, l); 4979 newEventsOnly = true; 4980 } 4981 4982 /** 4983 * Removes the specified component listener so that it no longer 4984 * receives component events from this component. This method performs 4985 * no function, nor does it throw an exception, if the listener 4986 * specified by the argument was not previously added to this component. 4987 * If listener <code>l</code> is <code>null</code>, 4988 * no exception is thrown and no action is performed. 4989 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 4990 * >AWT Threading Issues</a> for details on AWT's threading model. 4991 * @param l the component listener 4992 * @see java.awt.event.ComponentEvent 4993 * @see java.awt.event.ComponentListener 4994 * @see #addComponentListener 4995 * @see #getComponentListeners 4996 * @since JDK1.1 4997 */ 4998 public synchronized void removeComponentListener(ComponentListener l) { 4999 if (l == null) { 5000 return; 5001 } 5002 componentListener = AWTEventMulticaster.remove(componentListener, l); 5003 } 5004 5005 /** 5006 * Returns an array of all the component listeners 5007 * registered on this component. 5008 * 5009 * @return all of this comonent's <code>ComponentListener</code>s 5010 * or an empty array if no component 5011 * listeners are currently registered 5012 * 5013 * @see #addComponentListener 5014 * @see #removeComponentListener 5015 * @since 1.4 5016 */ 5017 public synchronized ComponentListener[] getComponentListeners() { 5018 return (ComponentListener[]) (getListeners(ComponentListener.class)); 5019 } 5020 5021 /** 5022 * Adds the specified focus listener to receive focus events from 5023 * this component when this component gains input focus. 5024 * If listener <code>l</code> is <code>null</code>, 5025 * no exception is thrown and no action is performed. 5026 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5027 * >AWT Threading Issues</a> for details on AWT's threading model. 5028 * 5029 * @param l the focus listener 5030 * @see java.awt.event.FocusEvent 5031 * @see java.awt.event.FocusListener 5032 * @see #removeFocusListener 5033 * @see #getFocusListeners 5034 * @since JDK1.1 5035 */ 5036 public synchronized void addFocusListener(FocusListener l) { 5037 if (l == null) { 5038 return; 5039 } 5040 focusListener = AWTEventMulticaster.add(focusListener, l); 5041 newEventsOnly = true; 5042 5043 // if this is a lightweight component, enable focus events 5044 // in the native container. 5045 if (peer instanceof LightweightPeer) { 5046 parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK); 5047 } 5048 } 5049 5050 /** 5051 * Removes the specified focus listener so that it no longer 5052 * receives focus events from this component. This method performs 5053 * no function, nor does it throw an exception, if the listener 5054 * specified by the argument was not previously added to this component. 5055 * If listener <code>l</code> is <code>null</code>, 5056 * no exception is thrown and no action is performed. 5057 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5058 * >AWT Threading Issues</a> for details on AWT's threading model. 5059 * 5060 * @param l the focus listener 5061 * @see java.awt.event.FocusEvent 5062 * @see java.awt.event.FocusListener 5063 * @see #addFocusListener 5064 * @see #getFocusListeners 5065 * @since JDK1.1 5066 */ 5067 public synchronized void removeFocusListener(FocusListener l) { 5068 if (l == null) { 5069 return; 5070 } 5071 focusListener = AWTEventMulticaster.remove(focusListener, l); 5072 } 5073 5074 /** 5075 * Returns an array of all the focus listeners 5076 * registered on this component. 5077 * 5078 * @return all of this component's <code>FocusListener</code>s 5079 * or an empty array if no component 5080 * listeners are currently registered 5081 * 5082 * @see #addFocusListener 5083 * @see #removeFocusListener 5084 * @since 1.4 5085 */ 5086 public synchronized FocusListener[] getFocusListeners() { 5087 return (FocusListener[]) (getListeners(FocusListener.class)); 5088 } 5089 5090 /** 5091 * Adds the specified hierarchy listener to receive hierarchy changed 5092 * events from this component when the hierarchy to which this container 5093 * belongs changes. 5094 * If listener <code>l</code> is <code>null</code>, 5095 * no exception is thrown and no action is performed. 5096 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5097 * >AWT Threading Issues</a> for details on AWT's threading model. 5098 * 5099 * @param l the hierarchy listener 5100 * @see java.awt.event.HierarchyEvent 5101 * @see java.awt.event.HierarchyListener 5102 * @see #removeHierarchyListener 5103 * @see #getHierarchyListeners 5104 * @since 1.3 5105 */ 5106 public void addHierarchyListener(HierarchyListener l) { 5107 if (l == null) { 5108 return; 5109 } 5110 boolean notifyAncestors; 5111 synchronized (this) { 5112 notifyAncestors = 5113 (hierarchyListener == null && 5114 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); 5115 hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l); 5116 notifyAncestors = (notifyAncestors && hierarchyListener != null); 5117 newEventsOnly = true; 5118 } 5119 if (notifyAncestors) { 5120 synchronized (getTreeLock()) { 5121 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, 5122 1); 5123 } 5124 } 5125 } 5126 5127 /** 5128 * Removes the specified hierarchy listener so that it no longer 5129 * receives hierarchy changed events from this component. This method 5130 * performs no function, nor does it throw an exception, if the listener 5131 * specified by the argument was not previously added to this component. 5132 * If listener <code>l</code> is <code>null</code>, 5133 * no exception is thrown and no action is performed. 5134 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5135 * >AWT Threading Issues</a> for details on AWT's threading model. 5136 * 5137 * @param l the hierarchy listener 5138 * @see java.awt.event.HierarchyEvent 5139 * @see java.awt.event.HierarchyListener 5140 * @see #addHierarchyListener 5141 * @see #getHierarchyListeners 5142 * @since 1.3 5143 */ 5144 public void removeHierarchyListener(HierarchyListener l) { 5145 if (l == null) { 5146 return; 5147 } 5148 boolean notifyAncestors; 5149 synchronized (this) { 5150 notifyAncestors = 5151 (hierarchyListener != null && 5152 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); 5153 hierarchyListener = 5154 AWTEventMulticaster.remove(hierarchyListener, l); 5155 notifyAncestors = (notifyAncestors && hierarchyListener == null); 5156 } 5157 if (notifyAncestors) { 5158 synchronized (getTreeLock()) { 5159 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, 5160 -1); 5161 } 5162 } 5163 } 5164 5165 /** 5166 * Returns an array of all the hierarchy listeners 5167 * registered on this component. 5168 * 5169 * @return all of this component's <code>HierarchyListener</code>s 5170 * or an empty array if no hierarchy 5171 * listeners are currently registered 5172 * 5173 * @see #addHierarchyListener 5174 * @see #removeHierarchyListener 5175 * @since 1.4 5176 */ 5177 public synchronized HierarchyListener[] getHierarchyListeners() { 5178 return (HierarchyListener[])(getListeners(HierarchyListener.class)); 5179 } 5180 5181 /** 5182 * Adds the specified hierarchy bounds listener to receive hierarchy 5183 * bounds events from this component when the hierarchy to which this 5184 * container belongs changes. 5185 * If listener <code>l</code> is <code>null</code>, 5186 * no exception is thrown and no action is performed. 5187 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5188 * >AWT Threading Issues</a> for details on AWT's threading model. 5189 * 5190 * @param l the hierarchy bounds listener 5191 * @see java.awt.event.HierarchyEvent 5192 * @see java.awt.event.HierarchyBoundsListener 5193 * @see #removeHierarchyBoundsListener 5194 * @see #getHierarchyBoundsListeners 5195 * @since 1.3 5196 */ 5197 public void addHierarchyBoundsListener(HierarchyBoundsListener l) { 5198 if (l == null) { 5199 return; 5200 } 5201 boolean notifyAncestors; 5202 synchronized (this) { 5203 notifyAncestors = 5204 (hierarchyBoundsListener == null && 5205 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); 5206 hierarchyBoundsListener = 5207 AWTEventMulticaster.add(hierarchyBoundsListener, l); 5208 notifyAncestors = (notifyAncestors && 5209 hierarchyBoundsListener != null); 5210 newEventsOnly = true; 5211 } 5212 if (notifyAncestors) { 5213 synchronized (getTreeLock()) { 5214 adjustListeningChildrenOnParent( 5215 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1); 5216 } 5217 } 5218 } 5219 5220 /** 5221 * Removes the specified hierarchy bounds listener so that it no longer 5222 * receives hierarchy bounds events from this component. This method 5223 * performs no function, nor does it throw an exception, if the listener 5224 * specified by the argument was not previously added to this component. 5225 * If listener <code>l</code> is <code>null</code>, 5226 * no exception is thrown and no action is performed. 5227 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5228 * >AWT Threading Issues</a> for details on AWT's threading model. 5229 * 5230 * @param l the hierarchy bounds listener 5231 * @see java.awt.event.HierarchyEvent 5232 * @see java.awt.event.HierarchyBoundsListener 5233 * @see #addHierarchyBoundsListener 5234 * @see #getHierarchyBoundsListeners 5235 * @since 1.3 5236 */ 5237 public void removeHierarchyBoundsListener(HierarchyBoundsListener l) { 5238 if (l == null) { 5239 return; 5240 } 5241 boolean notifyAncestors; 5242 synchronized (this) { 5243 notifyAncestors = 5244 (hierarchyBoundsListener != null && 5245 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); 5246 hierarchyBoundsListener = 5247 AWTEventMulticaster.remove(hierarchyBoundsListener, l); 5248 notifyAncestors = (notifyAncestors && 5249 hierarchyBoundsListener == null); 5250 } 5251 if (notifyAncestors) { 5252 synchronized (getTreeLock()) { 5253 adjustListeningChildrenOnParent( 5254 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1); 5255 } 5256 } 5257 } 5258 5259 // Should only be called while holding the tree lock 5260 int numListening(long mask) { 5261 // One mask or the other, but not neither or both. 5262 if (eventLog.isLoggable(Level.FINE)) { 5263 if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) && 5264 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)) 5265 { 5266 eventLog.log(Level.FINE, "Assertion failed"); 5267 } 5268 } 5269 if ((mask == AWTEvent.HIERARCHY_EVENT_MASK && 5270 (hierarchyListener != null || 5271 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) || 5272 (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK && 5273 (hierarchyBoundsListener != null || 5274 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) { 5275 return 1; 5276 } else { 5277 return 0; 5278 } 5279 } 5280 5281 // Should only be called while holding tree lock 5282 int countHierarchyMembers() { 5283 return 1; 5284 } 5285 // Should only be called while holding the tree lock 5286 int createHierarchyEvents(int id, Component changed, 5287 Container changedParent, long changeFlags, 5288 boolean enabledOnToolkit) { 5289 switch (id) { 5290 case HierarchyEvent.HIERARCHY_CHANGED: 5291 if (hierarchyListener != null || 5292 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 5293 enabledOnToolkit) { 5294 HierarchyEvent e = new HierarchyEvent(this, id, changed, 5295 changedParent, 5296 changeFlags); 5297 dispatchEvent(e); 5298 return 1; 5299 } 5300 break; 5301 case HierarchyEvent.ANCESTOR_MOVED: 5302 case HierarchyEvent.ANCESTOR_RESIZED: 5303 if (eventLog.isLoggable(Level.FINE)) { 5304 if (changeFlags != 0) { 5305 eventLog.log(Level.FINE, "Assertion (changeFlags == 0) failed"); 5306 } 5307 } 5308 if (hierarchyBoundsListener != null || 5309 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || 5310 enabledOnToolkit) { 5311 HierarchyEvent e = new HierarchyEvent(this, id, changed, 5312 changedParent); 5313 dispatchEvent(e); 5314 return 1; 5315 } 5316 break; 5317 default: 5318 // assert false 5319 if (eventLog.isLoggable(Level.FINE)) { 5320 eventLog.log(Level.FINE, "This code must never be reached"); 5321 } 5322 break; 5323 } 5324 return 0; 5325 } 5326 5327 /** 5328 * Returns an array of all the hierarchy bounds listeners 5329 * registered on this component. 5330 * 5331 * @return all of this component's <code>HierarchyBoundsListener</code>s 5332 * or an empty array if no hierarchy bounds 5333 * listeners are currently registered 5334 * 5335 * @see #addHierarchyBoundsListener 5336 * @see #removeHierarchyBoundsListener 5337 * @since 1.4 5338 */ 5339 public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() { 5340 return (HierarchyBoundsListener[]) 5341 (getListeners(HierarchyBoundsListener.class)); 5342 } 5343 5344 /* 5345 * Should only be called while holding the tree lock. 5346 * It's added only for overriding in java.awt.Window 5347 * because parent in Window is owner. 5348 */ 5349 void adjustListeningChildrenOnParent(long mask, int num) { 5350 if (parent != null) { 5351 parent.adjustListeningChildren(mask, num); 5352 } 5353 } 5354 5355 /** 5356 * Adds the specified key listener to receive key events from 5357 * this component. 5358 * If l is null, no exception is thrown and no action is performed. 5359 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5360 * >AWT Threading Issues</a> for details on AWT's threading model. 5361 * 5362 * @param l the key listener. 5363 * @see java.awt.event.KeyEvent 5364 * @see java.awt.event.KeyListener 5365 * @see #removeKeyListener 5366 * @see #getKeyListeners 5367 * @since JDK1.1 5368 */ 5369 public synchronized void addKeyListener(KeyListener l) { 5370 if (l == null) { 5371 return; 5372 } 5373 keyListener = AWTEventMulticaster.add(keyListener, l); 5374 newEventsOnly = true; 5375 5376 // if this is a lightweight component, enable key events 5377 // in the native container. 5378 if (peer instanceof LightweightPeer) { 5379 parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK); 5380 } 5381 } 5382 5383 /** 5384 * Removes the specified key listener so that it no longer 5385 * receives key events from this component. This method performs 5386 * no function, nor does it throw an exception, if the listener 5387 * specified by the argument was not previously added to this component. 5388 * If listener <code>l</code> is <code>null</code>, 5389 * no exception is thrown and no action is performed. 5390 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5391 * >AWT Threading Issues</a> for details on AWT's threading model. 5392 * 5393 * @param l the key listener 5394 * @see java.awt.event.KeyEvent 5395 * @see java.awt.event.KeyListener 5396 * @see #addKeyListener 5397 * @see #getKeyListeners 5398 * @since JDK1.1 5399 */ 5400 public synchronized void removeKeyListener(KeyListener l) { 5401 if (l == null) { 5402 return; 5403 } 5404 keyListener = AWTEventMulticaster.remove(keyListener, l); 5405 } 5406 5407 /** 5408 * Returns an array of all the key listeners 5409 * registered on this component. 5410 * 5411 * @return all of this component's <code>KeyListener</code>s 5412 * or an empty array if no key 5413 * listeners are currently registered 5414 * 5415 * @see #addKeyListener 5416 * @see #removeKeyListener 5417 * @since 1.4 5418 */ 5419 public synchronized KeyListener[] getKeyListeners() { 5420 return (KeyListener[]) (getListeners(KeyListener.class)); 5421 } 5422 5423 /** 5424 * Adds the specified mouse listener to receive mouse events from 5425 * this component. 5426 * If listener <code>l</code> is <code>null</code>, 5427 * no exception is thrown and no action is performed. 5428 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5429 * >AWT Threading Issues</a> for details on AWT's threading model. 5430 * 5431 * @param l the mouse listener 5432 * @see java.awt.event.MouseEvent 5433 * @see java.awt.event.MouseListener 5434 * @see #removeMouseListener 5435 * @see #getMouseListeners 5436 * @since JDK1.1 5437 */ 5438 public synchronized void addMouseListener(MouseListener l) { 5439 if (l == null) { 5440 return; 5441 } 5442 mouseListener = AWTEventMulticaster.add(mouseListener,l); 5443 newEventsOnly = true; 5444 5445 // if this is a lightweight component, enable mouse events 5446 // in the native container. 5447 if (peer instanceof LightweightPeer) { 5448 parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK); 5449 } 5450 } 5451 5452 /** 5453 * Removes the specified mouse listener so that it no longer 5454 * receives mouse events from this component. This method performs 5455 * no function, nor does it throw an exception, if the listener 5456 * specified by the argument was not previously added to this component. 5457 * If listener <code>l</code> is <code>null</code>, 5458 * no exception is thrown and no action is performed. 5459 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5460 * >AWT Threading Issues</a> for details on AWT's threading model. 5461 * 5462 * @param l the mouse listener 5463 * @see java.awt.event.MouseEvent 5464 * @see java.awt.event.MouseListener 5465 * @see #addMouseListener 5466 * @see #getMouseListeners 5467 * @since JDK1.1 5468 */ 5469 public synchronized void removeMouseListener(MouseListener l) { 5470 if (l == null) { 5471 return; 5472 } 5473 mouseListener = AWTEventMulticaster.remove(mouseListener, l); 5474 } 5475 5476 /** 5477 * Returns an array of all the mouse listeners 5478 * registered on this component. 5479 * 5480 * @return all of this component's <code>MouseListener</code>s 5481 * or an empty array if no mouse 5482 * listeners are currently registered 5483 * 5484 * @see #addMouseListener 5485 * @see #removeMouseListener 5486 * @since 1.4 5487 */ 5488 public synchronized MouseListener[] getMouseListeners() { 5489 return (MouseListener[]) (getListeners(MouseListener.class)); 5490 } 5491 5492 /** 5493 * Adds the specified mouse motion listener to receive mouse motion 5494 * events from this component. 5495 * If listener <code>l</code> is <code>null</code>, 5496 * no exception is thrown and no action is performed. 5497 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5498 * >AWT Threading Issues</a> for details on AWT's threading model. 5499 * 5500 * @param l the mouse motion listener 5501 * @see java.awt.event.MouseEvent 5502 * @see java.awt.event.MouseMotionListener 5503 * @see #removeMouseMotionListener 5504 * @see #getMouseMotionListeners 5505 * @since JDK1.1 5506 */ 5507 public synchronized void addMouseMotionListener(MouseMotionListener l) { 5508 if (l == null) { 5509 return; 5510 } 5511 mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l); 5512 newEventsOnly = true; 5513 5514 // if this is a lightweight component, enable mouse events 5515 // in the native container. 5516 if (peer instanceof LightweightPeer) { 5517 parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); 5518 } 5519 } 5520 5521 /** 5522 * Removes the specified mouse motion listener so that it no longer 5523 * receives mouse motion events from this component. This method performs 5524 * no function, nor does it throw an exception, if the listener 5525 * specified by the argument was not previously added to this component. 5526 * If listener <code>l</code> is <code>null</code>, 5527 * no exception is thrown and no action is performed. 5528 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5529 * >AWT Threading Issues</a> for details on AWT's threading model. 5530 * 5531 * @param l the mouse motion listener 5532 * @see java.awt.event.MouseEvent 5533 * @see java.awt.event.MouseMotionListener 5534 * @see #addMouseMotionListener 5535 * @see #getMouseMotionListeners 5536 * @since JDK1.1 5537 */ 5538 public synchronized void removeMouseMotionListener(MouseMotionListener l) { 5539 if (l == null) { 5540 return; 5541 } 5542 mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l); 5543 } 5544 5545 /** 5546 * Returns an array of all the mouse motion listeners 5547 * registered on this component. 5548 * 5549 * @return all of this component's <code>MouseMotionListener</code>s 5550 * or an empty array if no mouse motion 5551 * listeners are currently registered 5552 * 5553 * @see #addMouseMotionListener 5554 * @see #removeMouseMotionListener 5555 * @since 1.4 5556 */ 5557 public synchronized MouseMotionListener[] getMouseMotionListeners() { 5558 return (MouseMotionListener[]) (getListeners(MouseMotionListener.class)); 5559 } 5560 5561 /** 5562 * Adds the specified mouse wheel listener to receive mouse wheel events 5563 * from this component. Containers also receive mouse wheel events from 5564 * sub-components. 5565 * <p> 5566 * For information on how mouse wheel events are dispatched, see 5567 * the class description for {@link MouseWheelEvent}. 5568 * <p> 5569 * If l is <code>null</code>, no exception is thrown and no 5570 * action is performed. 5571 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5572 * >AWT Threading Issues</a> for details on AWT's threading model. 5573 * 5574 * @param l the mouse wheel listener 5575 * @see java.awt.event.MouseWheelEvent 5576 * @see java.awt.event.MouseWheelListener 5577 * @see #removeMouseWheelListener 5578 * @see #getMouseWheelListeners 5579 * @since 1.4 5580 */ 5581 public synchronized void addMouseWheelListener(MouseWheelListener l) { 5582 if (l == null) { 5583 return; 5584 } 5585 mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l); 5586 newEventsOnly = true; 5587 5588 // if this is a lightweight component, enable mouse events 5589 // in the native container. 5590 if (peer instanceof LightweightPeer) { 5591 parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK); 5592 } 5593 } 5594 5595 /** 5596 * Removes the specified mouse wheel listener so that it no longer 5597 * receives mouse wheel events from this component. This method performs 5598 * no function, nor does it throw an exception, if the listener 5599 * specified by the argument was not previously added to this component. 5600 * If l is null, no exception is thrown and no action is performed. 5601 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5602 * >AWT Threading Issues</a> for details on AWT's threading model. 5603 * 5604 * @param l the mouse wheel listener. 5605 * @see java.awt.event.MouseWheelEvent 5606 * @see java.awt.event.MouseWheelListener 5607 * @see #addMouseWheelListener 5608 * @see #getMouseWheelListeners 5609 * @since 1.4 5610 */ 5611 public synchronized void removeMouseWheelListener(MouseWheelListener l) { 5612 if (l == null) { 5613 return; 5614 } 5615 mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l); 5616 } 5617 5618 /** 5619 * Returns an array of all the mouse wheel listeners 5620 * registered on this component. 5621 * 5622 * @return all of this component's <code>MouseWheelListener</code>s 5623 * or an empty array if no mouse wheel 5624 * listeners are currently registered 5625 * 5626 * @see #addMouseWheelListener 5627 * @see #removeMouseWheelListener 5628 * @since 1.4 5629 */ 5630 public synchronized MouseWheelListener[] getMouseWheelListeners() { 5631 return (MouseWheelListener[]) (getListeners(MouseWheelListener.class)); 5632 } 5633 5634 /** 5635 * Adds the specified input method listener to receive 5636 * input method events from this component. A component will 5637 * only receive input method events from input methods 5638 * if it also overrides <code>getInputMethodRequests</code> to return an 5639 * <code>InputMethodRequests</code> instance. 5640 * If listener <code>l</code> is <code>null</code>, 5641 * no exception is thrown and no action is performed. 5642 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5643 * >AWT Threading Issues</a> for details on AWT's threading model. 5644 * 5645 * @param l the input method listener 5646 * @see java.awt.event.InputMethodEvent 5647 * @see java.awt.event.InputMethodListener 5648 * @see #removeInputMethodListener 5649 * @see #getInputMethodListeners 5650 * @see #getInputMethodRequests 5651 * @since 1.2 5652 */ 5653 public synchronized void addInputMethodListener(InputMethodListener l) { 5654 if (l == null) { 5655 return; 5656 } 5657 inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l); 5658 newEventsOnly = true; 5659 } 5660 5661 /** 5662 * Removes the specified input method listener so that it no longer 5663 * receives input method events from this component. This method performs 5664 * no function, nor does it throw an exception, if the listener 5665 * specified by the argument was not previously added to this component. 5666 * If listener <code>l</code> is <code>null</code>, 5667 * no exception is thrown and no action is performed. 5668 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5669 * >AWT Threading Issues</a> for details on AWT's threading model. 5670 * 5671 * @param l the input method listener 5672 * @see java.awt.event.InputMethodEvent 5673 * @see java.awt.event.InputMethodListener 5674 * @see #addInputMethodListener 5675 * @see #getInputMethodListeners 5676 * @since 1.2 5677 */ 5678 public synchronized void removeInputMethodListener(InputMethodListener l) { 5679 if (l == null) { 5680 return; 5681 } 5682 inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l); 5683 } 5684 5685 /** 5686 * Returns an array of all the input method listeners 5687 * registered on this component. 5688 * 5689 * @return all of this component's <code>InputMethodListener</code>s 5690 * or an empty array if no input method 5691 * listeners are currently registered 5692 * 5693 * @see #addInputMethodListener 5694 * @see #removeInputMethodListener 5695 * @since 1.4 5696 */ 5697 public synchronized InputMethodListener[] getInputMethodListeners() { 5698 return (InputMethodListener[]) (getListeners(InputMethodListener.class)); 5699 } 5700 5701 /** 5702 * Returns an array of all the objects currently registered 5703 * as <code><em>Foo</em>Listener</code>s 5704 * upon this <code>Component</code>. 5705 * <code><em>Foo</em>Listener</code>s are registered using the 5706 * <code>add<em>Foo</em>Listener</code> method. 5707 * 5708 * <p> 5709 * You can specify the <code>listenerType</code> argument 5710 * with a class literal, such as 5711 * <code><em>Foo</em>Listener.class</code>. 5712 * For example, you can query a 5713 * <code>Component</code> <code>c</code> 5714 * for its mouse listeners with the following code: 5715 * 5716 * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre> 5717 * 5718 * If no such listeners exist, this method returns an empty array. 5719 * 5720 * @param listenerType the type of listeners requested; this parameter 5721 * should specify an interface that descends from 5722 * <code>java.util.EventListener</code> 5723 * @return an array of all objects registered as 5724 * <code><em>Foo</em>Listener</code>s on this component, 5725 * or an empty array if no such listeners have been added 5726 * @exception ClassCastException if <code>listenerType</code> 5727 * doesn't specify a class or interface that implements 5728 * <code>java.util.EventListener</code> 5729 * 5730 * @see #getComponentListeners 5731 * @see #getFocusListeners 5732 * @see #getHierarchyListeners 5733 * @see #getHierarchyBoundsListeners 5734 * @see #getKeyListeners 5735 * @see #getMouseListeners 5736 * @see #getMouseMotionListeners 5737 * @see #getMouseWheelListeners 5738 * @see #getInputMethodListeners 5739 * @see #getPropertyChangeListeners 5740 * 5741 * @since 1.3 5742 */ 5743 public <T extends EventListener> T[] getListeners(Class<T> listenerType) { 5744 EventListener l = null; 5745 if (listenerType == ComponentListener.class) { 5746 l = componentListener; 5747 } else if (listenerType == FocusListener.class) { 5748 l = focusListener; 5749 } else if (listenerType == HierarchyListener.class) { 5750 l = hierarchyListener; 5751 } else if (listenerType == HierarchyBoundsListener.class) { 5752 l = hierarchyBoundsListener; 5753 } else if (listenerType == KeyListener.class) { 5754 l = keyListener; 5755 } else if (listenerType == MouseListener.class) { 5756 l = mouseListener; 5757 } else if (listenerType == MouseMotionListener.class) { 5758 l = mouseMotionListener; 5759 } else if (listenerType == MouseWheelListener.class) { 5760 l = mouseWheelListener; 5761 } else if (listenerType == InputMethodListener.class) { 5762 l = inputMethodListener; 5763 } else if (listenerType == PropertyChangeListener.class) { 5764 return (T[])getPropertyChangeListeners(); 5765 } 5766 return AWTEventMulticaster.getListeners(l, listenerType); 5767 } 5768 5769 /** 5770 * Gets the input method request handler which supports 5771 * requests from input methods for this component. A component 5772 * that supports on-the-spot text input must override this 5773 * method to return an <code>InputMethodRequests</code> instance. 5774 * At the same time, it also has to handle input method events. 5775 * 5776 * @return the input method request handler for this component, 5777 * <code>null</code> by default 5778 * @see #addInputMethodListener 5779 * @since 1.2 5780 */ 5781 public InputMethodRequests getInputMethodRequests() { 5782 return null; 5783 } 5784 5785 /** 5786 * Gets the input context used by this component for handling 5787 * the communication with input methods when text is entered 5788 * in this component. By default, the input context used for 5789 * the parent component is returned. Components may 5790 * override this to return a private input context. 5791 * 5792 * @return the input context used by this component; 5793 * <code>null</code> if no context can be determined 5794 * @since 1.2 5795 */ 5796 public InputContext getInputContext() { 5797 Container parent = this.parent; 5798 if (parent == null) { 5799 return null; 5800 } else { 5801 return parent.getInputContext(); 5802 } 5803 } 5804 5805 /** 5806 * Enables the events defined by the specified event mask parameter 5807 * to be delivered to this component. 5808 * <p> 5809 * Event types are automatically enabled when a listener for 5810 * that event type is added to the component. 5811 * <p> 5812 * This method only needs to be invoked by subclasses of 5813 * <code>Component</code> which desire to have the specified event 5814 * types delivered to <code>processEvent</code> regardless of whether 5815 * or not a listener is registered. 5816 * @param eventsToEnable the event mask defining the event types 5817 * @see #processEvent 5818 * @see #disableEvents 5819 * @see AWTEvent 5820 * @since JDK1.1 5821 */ 5822 protected final void enableEvents(long eventsToEnable) { 5823 long notifyAncestors = 0; 5824 synchronized (this) { 5825 if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && 5826 hierarchyListener == null && 5827 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) { 5828 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; 5829 } 5830 if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 && 5831 hierarchyBoundsListener == null && 5832 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) { 5833 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; 5834 } 5835 eventMask |= eventsToEnable; 5836 newEventsOnly = true; 5837 } 5838 5839 // if this is a lightweight component, enable mouse events 5840 // in the native container. 5841 if (peer instanceof LightweightPeer) { 5842 parent.proxyEnableEvents(eventMask); 5843 } 5844 if (notifyAncestors != 0) { 5845 synchronized (getTreeLock()) { 5846 adjustListeningChildrenOnParent(notifyAncestors, 1); 5847 } 5848 } 5849 } 5850 5851 /** 5852 * Disables the events defined by the specified event mask parameter 5853 * from being delivered to this component. 5854 * @param eventsToDisable the event mask defining the event types 5855 * @see #enableEvents 5856 * @since JDK1.1 5857 */ 5858 protected final void disableEvents(long eventsToDisable) { 5859 long notifyAncestors = 0; 5860 synchronized (this) { 5861 if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && 5862 hierarchyListener == null && 5863 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) { 5864 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; 5865 } 5866 if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 && 5867 hierarchyBoundsListener == null && 5868 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) { 5869 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; 5870 } 5871 eventMask &= ~eventsToDisable; 5872 } 5873 if (notifyAncestors != 0) { 5874 synchronized (getTreeLock()) { 5875 adjustListeningChildrenOnParent(notifyAncestors, -1); 5876 } 5877 } 5878 } 5879 5880 transient sun.awt.EventQueueItem[] eventCache; 5881 5882 /** 5883 * @see #isCoalescingEnabled 5884 * @see #checkCoalescing 5885 */ 5886 transient private boolean coalescingEnabled = checkCoalescing(); 5887 5888 /** 5889 * Weak map of known coalesceEvent overriders. 5890 * Value indicates whether overriden. 5891 * Bootstrap classes are not included. 5892 */ 5893 private static final Map<Class<?>, Boolean> coalesceMap = 5894 new java.util.WeakHashMap<Class<?>, Boolean>(); 5895 5896 /** 5897 * Indicates whether this class overrides coalesceEvents. 5898 * It is assumed that all classes that are loaded from the bootstrap 5899 * do not. 5900 * The boostrap class loader is assumed to be represented by null. 5901 * We do not check that the method really overrides 5902 * (it might be static, private or package private). 5903 */ 5904 private boolean checkCoalescing() { 5905 if (getClass().getClassLoader()==null) { 5906 return false; 5907 } 5908 final Class<? extends Component> clazz = getClass(); 5909 synchronized (coalesceMap) { 5910 // Check cache. 5911 Boolean value = coalesceMap.get(clazz); 5912 if (value != null) { 5913 return value; 5914 } 5915 5916 // Need to check non-bootstraps. 5917 Boolean enabled = java.security.AccessController.doPrivileged( 5918 new java.security.PrivilegedAction<Boolean>() { 5919 public Boolean run() { 5920 return isCoalesceEventsOverriden(clazz); 5921 } 5922 } 5923 ); 5924 coalesceMap.put(clazz, enabled); 5925 return enabled; 5926 } 5927 } 5928 5929 /** 5930 * Parameter types of coalesceEvents(AWTEvent,AWTEVent). 5931 */ 5932 private static final Class[] coalesceEventsParams = { 5933 AWTEvent.class, AWTEvent.class 5934 }; 5935 5936 /** 5937 * Indicates whether a class or its superclasses override coalesceEvents. 5938 * Must be called with lock on coalesceMap and privileged. 5939 * @see checkCoalsecing 5940 */ 5941 private static boolean isCoalesceEventsOverriden(Class<?> clazz) { 5942 assert Thread.holdsLock(coalesceMap); 5943 5944 // First check superclass - we may not need to bother ourselves. 5945 Class<?> superclass = clazz.getSuperclass(); 5946 if (superclass == null) { 5947 // Only occurs on implementations that 5948 // do not use null to represent the bootsrap class loader. 5949 return false; 5950 } 5951 if (superclass.getClassLoader() != null) { 5952 Boolean value = coalesceMap.get(superclass); 5953 if (value == null) { 5954 // Not done already - recurse. 5955 if (isCoalesceEventsOverriden(superclass)) { 5956 coalesceMap.put(superclass, true); 5957 return true; 5958 } 5959 } else if (value) { 5960 return true; 5961 } 5962 } 5963 5964 try { 5965 // Throws if not overriden. 5966 clazz.getDeclaredMethod( 5967 "coalesceEvents", coalesceEventsParams 5968 ); 5969 return true; 5970 } catch (NoSuchMethodException e) { 5971 // Not present in this class. 5972 return false; 5973 } 5974 } 5975 5976 /** 5977 * Indicates whether coalesceEvents may do something. 5978 */ 5979 final boolean isCoalescingEnabled() { 5980 return coalescingEnabled; 5981 } 5982 5983 5984 /** 5985 * Potentially coalesce an event being posted with an existing 5986 * event. This method is called by <code>EventQueue.postEvent</code> 5987 * if an event with the same ID as the event to be posted is found in 5988 * the queue (both events must have this component as their source). 5989 * This method either returns a coalesced event which replaces 5990 * the existing event (and the new event is then discarded), or 5991 * <code>null</code> to indicate that no combining should be done 5992 * (add the second event to the end of the queue). Either event 5993 * parameter may be modified and returned, as the other one is discarded 5994 * unless <code>null</code> is returned. 5995 * <p> 5996 * This implementation of <code>coalesceEvents</code> coalesces 5997 * two event types: mouse move (and drag) events, 5998 * and paint (and update) events. 5999 * For mouse move events the last event is always returned, causing 6000 * intermediate moves to be discarded. For paint events, the new 6001 * event is coalesced into a complex <code>RepaintArea</code> in the peer. 6002 * The new <code>AWTEvent</code> is always returned. 6003 * 6004 * @param existingEvent the event already on the <code>EventQueue</code> 6005 * @param newEvent the event being posted to the 6006 * <code>EventQueue</code> 6007 * @return a coalesced event, or <code>null</code> indicating that no 6008 * coalescing was done 6009 */ 6010 protected AWTEvent coalesceEvents(AWTEvent existingEvent, 6011 AWTEvent newEvent) { 6012 return null; 6013 } 6014 6015 /** 6016 * Processes events occurring on this component. By default this 6017 * method calls the appropriate 6018 * <code>process<event type>Event</code> 6019 * method for the given class of event. 6020 * <p>Note that if the event parameter is <code>null</code> 6021 * the behavior is unspecified and may result in an 6022 * exception. 6023 * 6024 * @param e the event 6025 * @see #processComponentEvent 6026 * @see #processFocusEvent 6027 * @see #processKeyEvent 6028 * @see #processMouseEvent 6029 * @see #processMouseMotionEvent 6030 * @see #processInputMethodEvent 6031 * @see #processHierarchyEvent 6032 * @see #processMouseWheelEvent 6033 * @since JDK1.1 6034 */ 6035 protected void processEvent(AWTEvent e) { 6036 if (e instanceof FocusEvent) { 6037 processFocusEvent((FocusEvent)e); 6038 6039 } else if (e instanceof MouseEvent) { 6040 switch(e.getID()) { 6041 case MouseEvent.MOUSE_PRESSED: 6042 case MouseEvent.MOUSE_RELEASED: 6043 case MouseEvent.MOUSE_CLICKED: 6044 case MouseEvent.MOUSE_ENTERED: 6045 case MouseEvent.MOUSE_EXITED: 6046 processMouseEvent((MouseEvent)e); 6047 break; 6048 case MouseEvent.MOUSE_MOVED: 6049 case MouseEvent.MOUSE_DRAGGED: 6050 processMouseMotionEvent((MouseEvent)e); 6051 break; 6052 case MouseEvent.MOUSE_WHEEL: 6053 processMouseWheelEvent((MouseWheelEvent)e); 6054 break; 6055 } 6056 6057 } else if (e instanceof KeyEvent) { 6058 processKeyEvent((KeyEvent)e); 6059 6060 } else if (e instanceof ComponentEvent) { 6061 processComponentEvent((ComponentEvent)e); 6062 } else if (e instanceof InputMethodEvent) { 6063 processInputMethodEvent((InputMethodEvent)e); 6064 } else if (e instanceof HierarchyEvent) { 6065 switch (e.getID()) { 6066 case HierarchyEvent.HIERARCHY_CHANGED: 6067 processHierarchyEvent((HierarchyEvent)e); 6068 break; 6069 case HierarchyEvent.ANCESTOR_MOVED: 6070 case HierarchyEvent.ANCESTOR_RESIZED: 6071 processHierarchyBoundsEvent((HierarchyEvent)e); 6072 break; 6073 } 6074 } 6075 } 6076 6077 /** 6078 * Processes component events occurring on this component by 6079 * dispatching them to any registered 6080 * <code>ComponentListener</code> objects. 6081 * <p> 6082 * This method is not called unless component events are 6083 * enabled for this component. Component events are enabled 6084 * when one of the following occurs: 6085 * <p><ul> 6086 * <li>A <code>ComponentListener</code> object is registered 6087 * via <code>addComponentListener</code>. 6088 * <li>Component events are enabled via <code>enableEvents</code>. 6089 * </ul> 6090 * <p>Note that if the event parameter is <code>null</code> 6091 * the behavior is unspecified and may result in an 6092 * exception. 6093 * 6094 * @param e the component event 6095 * @see java.awt.event.ComponentEvent 6096 * @see java.awt.event.ComponentListener 6097 * @see #addComponentListener 6098 * @see #enableEvents 6099 * @since JDK1.1 6100 */ 6101 protected void processComponentEvent(ComponentEvent e) { 6102 ComponentListener listener = componentListener; 6103 if (listener != null) { 6104 int id = e.getID(); 6105 switch(id) { 6106 case ComponentEvent.COMPONENT_RESIZED: 6107 listener.componentResized(e); 6108 break; 6109 case ComponentEvent.COMPONENT_MOVED: 6110 listener.componentMoved(e); 6111 break; 6112 case ComponentEvent.COMPONENT_SHOWN: 6113 listener.componentShown(e); 6114 break; 6115 case ComponentEvent.COMPONENT_HIDDEN: 6116 listener.componentHidden(e); 6117 break; 6118 } 6119 } 6120 } 6121 6122 /** 6123 * Processes focus events occurring on this component by 6124 * dispatching them to any registered 6125 * <code>FocusListener</code> objects. 6126 * <p> 6127 * This method is not called unless focus events are 6128 * enabled for this component. Focus events are enabled 6129 * when one of the following occurs: 6130 * <p><ul> 6131 * <li>A <code>FocusListener</code> object is registered 6132 * via <code>addFocusListener</code>. 6133 * <li>Focus events are enabled via <code>enableEvents</code>. 6134 * </ul> 6135 * <p> 6136 * If focus events are enabled for a <code>Component</code>, 6137 * the current <code>KeyboardFocusManager</code> determines 6138 * whether or not a focus event should be dispatched to 6139 * registered <code>FocusListener</code> objects. If the 6140 * events are to be dispatched, the <code>KeyboardFocusManager</code> 6141 * calls the <code>Component</code>'s <code>dispatchEvent</code> 6142 * method, which results in a call to the <code>Component</code>'s 6143 * <code>processFocusEvent</code> method. 6144 * <p> 6145 * If focus events are enabled for a <code>Component</code>, calling 6146 * the <code>Component</code>'s <code>dispatchEvent</code> method 6147 * with a <code>FocusEvent</code> as the argument will result in a 6148 * call to the <code>Component</code>'s <code>processFocusEvent</code> 6149 * method regardless of the current <code>KeyboardFocusManager</code>. 6150 * <p> 6151 * <p>Note that if the event parameter is <code>null</code> 6152 * the behavior is unspecified and may result in an 6153 * exception. 6154 * 6155 * @param e the focus event 6156 * @see java.awt.event.FocusEvent 6157 * @see java.awt.event.FocusListener 6158 * @see java.awt.KeyboardFocusManager 6159 * @see #addFocusListener 6160 * @see #enableEvents 6161 * @see #dispatchEvent 6162 * @since JDK1.1 6163 */ 6164 protected void processFocusEvent(FocusEvent e) { 6165 FocusListener listener = focusListener; 6166 if (listener != null) { 6167 int id = e.getID(); 6168 switch(id) { 6169 case FocusEvent.FOCUS_GAINED: 6170 listener.focusGained(e); 6171 break; 6172 case FocusEvent.FOCUS_LOST: 6173 listener.focusLost(e); 6174 break; 6175 } 6176 } 6177 } 6178 6179 /** 6180 * Processes key events occurring on this component by 6181 * dispatching them to any registered 6182 * <code>KeyListener</code> objects. 6183 * <p> 6184 * This method is not called unless key events are 6185 * enabled for this component. Key events are enabled 6186 * when one of the following occurs: 6187 * <p><ul> 6188 * <li>A <code>KeyListener</code> object is registered 6189 * via <code>addKeyListener</code>. 6190 * <li>Key events are enabled via <code>enableEvents</code>. 6191 * </ul> 6192 * 6193 * <p> 6194 * If key events are enabled for a <code>Component</code>, 6195 * the current <code>KeyboardFocusManager</code> determines 6196 * whether or not a key event should be dispatched to 6197 * registered <code>KeyListener</code> objects. The 6198 * <code>DefaultKeyboardFocusManager</code> will not dispatch 6199 * key events to a <code>Component</code> that is not the focus 6200 * owner or is not showing. 6201 * <p> 6202 * As of J2SE 1.4, <code>KeyEvent</code>s are redirected to 6203 * the focus owner. Please see the 6204 * <a href="doc-files/FocusSpec.html">Focus Specification</a> 6205 * for further information. 6206 * <p> 6207 * Calling a <code>Component</code>'s <code>dispatchEvent</code> 6208 * method with a <code>KeyEvent</code> as the argument will 6209 * result in a call to the <code>Component</code>'s 6210 * <code>processKeyEvent</code> method regardless of the 6211 * current <code>KeyboardFocusManager</code> as long as the 6212 * component is showing, focused, and enabled, and key events 6213 * are enabled on it. 6214 * <p>If the event parameter is <code>null</code> 6215 * the behavior is unspecified and may result in an 6216 * exception. 6217 * 6218 * @param e the key event 6219 * @see java.awt.event.KeyEvent 6220 * @see java.awt.event.KeyListener 6221 * @see java.awt.KeyboardFocusManager 6222 * @see java.awt.DefaultKeyboardFocusManager 6223 * @see #processEvent 6224 * @see #dispatchEvent 6225 * @see #addKeyListener 6226 * @see #enableEvents 6227 * @see #isShowing 6228 * @since JDK1.1 6229 */ 6230 protected void processKeyEvent(KeyEvent e) { 6231 KeyListener listener = keyListener; 6232 if (listener != null) { 6233 int id = e.getID(); 6234 switch(id) { 6235 case KeyEvent.KEY_TYPED: 6236 listener.keyTyped(e); 6237 break; 6238 case KeyEvent.KEY_PRESSED: 6239 listener.keyPressed(e); 6240 break; 6241 case KeyEvent.KEY_RELEASED: 6242 listener.keyReleased(e); 6243 break; 6244 } 6245 } 6246 } 6247 6248 /** 6249 * Processes mouse events occurring on this component by 6250 * dispatching them to any registered 6251 * <code>MouseListener</code> objects. 6252 * <p> 6253 * This method is not called unless mouse events are 6254 * enabled for this component. Mouse events are enabled 6255 * when one of the following occurs: 6256 * <p><ul> 6257 * <li>A <code>MouseListener</code> object is registered 6258 * via <code>addMouseListener</code>. 6259 * <li>Mouse events are enabled via <code>enableEvents</code>. 6260 * </ul> 6261 * <p>Note that if the event parameter is <code>null</code> 6262 * the behavior is unspecified and may result in an 6263 * exception. 6264 * 6265 * @param e the mouse event 6266 * @see java.awt.event.MouseEvent 6267 * @see java.awt.event.MouseListener 6268 * @see #addMouseListener 6269 * @see #enableEvents 6270 * @since JDK1.1 6271 */ 6272 protected void processMouseEvent(MouseEvent e) { 6273 MouseListener listener = mouseListener; 6274 if (listener != null) { 6275 int id = e.getID(); 6276 switch(id) { 6277 case MouseEvent.MOUSE_PRESSED: 6278 listener.mousePressed(e); 6279 break; 6280 case MouseEvent.MOUSE_RELEASED: 6281 listener.mouseReleased(e); 6282 break; 6283 case MouseEvent.MOUSE_CLICKED: 6284 listener.mouseClicked(e); 6285 break; 6286 case MouseEvent.MOUSE_EXITED: 6287 listener.mouseExited(e); 6288 break; 6289 case MouseEvent.MOUSE_ENTERED: 6290 listener.mouseEntered(e); 6291 break; 6292 } 6293 } 6294 } 6295 6296 /** 6297 * Processes mouse motion events occurring on this component by 6298 * dispatching them to any registered 6299 * <code>MouseMotionListener</code> objects. 6300 * <p> 6301 * This method is not called unless mouse motion events are 6302 * enabled for this component. Mouse motion events are enabled 6303 * when one of the following occurs: 6304 * <p><ul> 6305 * <li>A <code>MouseMotionListener</code> object is registered 6306 * via <code>addMouseMotionListener</code>. 6307 * <li>Mouse motion events are enabled via <code>enableEvents</code>. 6308 * </ul> 6309 * <p>Note that if the event parameter is <code>null</code> 6310 * the behavior is unspecified and may result in an 6311 * exception. 6312 * 6313 * @param e the mouse motion event 6314 * @see java.awt.event.MouseEvent 6315 * @see java.awt.event.MouseMotionListener 6316 * @see #addMouseMotionListener 6317 * @see #enableEvents 6318 * @since JDK1.1 6319 */ 6320 protected void processMouseMotionEvent(MouseEvent e) { 6321 MouseMotionListener listener = mouseMotionListener; 6322 if (listener != null) { 6323 int id = e.getID(); 6324 switch(id) { 6325 case MouseEvent.MOUSE_MOVED: 6326 listener.mouseMoved(e); 6327 break; 6328 case MouseEvent.MOUSE_DRAGGED: 6329 listener.mouseDragged(e); 6330 break; 6331 } 6332 } 6333 } 6334 6335 /** 6336 * Processes mouse wheel events occurring on this component by 6337 * dispatching them to any registered 6338 * <code>MouseWheelListener</code> objects. 6339 * <p> 6340 * This method is not called unless mouse wheel events are 6341 * enabled for this component. Mouse wheel events are enabled 6342 * when one of the following occurs: 6343 * <p><ul> 6344 * <li>A <code>MouseWheelListener</code> object is registered 6345 * via <code>addMouseWheelListener</code>. 6346 * <li>Mouse wheel events are enabled via <code>enableEvents</code>. 6347 * </ul> 6348 * <p> 6349 * For information on how mouse wheel events are dispatched, see 6350 * the class description for {@link MouseWheelEvent}. 6351 * <p> 6352 * Note that if the event parameter is <code>null</code> 6353 * the behavior is unspecified and may result in an 6354 * exception. 6355 * 6356 * @param e the mouse wheel event 6357 * @see java.awt.event.MouseWheelEvent 6358 * @see java.awt.event.MouseWheelListener 6359 * @see #addMouseWheelListener 6360 * @see #enableEvents 6361 * @since 1.4 6362 */ 6363 protected void processMouseWheelEvent(MouseWheelEvent e) { 6364 MouseWheelListener listener = mouseWheelListener; 6365 if (listener != null) { 6366 int id = e.getID(); 6367 switch(id) { 6368 case MouseEvent.MOUSE_WHEEL: 6369 listener.mouseWheelMoved(e); 6370 break; 6371 } 6372 } 6373 } 6374 6375 boolean postsOldMouseEvents() { 6376 return false; 6377 } 6378 6379 /** 6380 * Processes input method events occurring on this component by 6381 * dispatching them to any registered 6382 * <code>InputMethodListener</code> objects. 6383 * <p> 6384 * This method is not called unless input method events 6385 * are enabled for this component. Input method events are enabled 6386 * when one of the following occurs: 6387 * <p><ul> 6388 * <li>An <code>InputMethodListener</code> object is registered 6389 * via <code>addInputMethodListener</code>. 6390 * <li>Input method events are enabled via <code>enableEvents</code>. 6391 * </ul> 6392 * <p>Note that if the event parameter is <code>null</code> 6393 * the behavior is unspecified and may result in an 6394 * exception. 6395 * 6396 * @param e the input method event 6397 * @see java.awt.event.InputMethodEvent 6398 * @see java.awt.event.InputMethodListener 6399 * @see #addInputMethodListener 6400 * @see #enableEvents 6401 * @since 1.2 6402 */ 6403 protected void processInputMethodEvent(InputMethodEvent e) { 6404 InputMethodListener listener = inputMethodListener; 6405 if (listener != null) { 6406 int id = e.getID(); 6407 switch (id) { 6408 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: 6409 listener.inputMethodTextChanged(e); 6410 break; 6411 case InputMethodEvent.CARET_POSITION_CHANGED: 6412 listener.caretPositionChanged(e); 6413 break; 6414 } 6415 } 6416 } 6417 6418 /** 6419 * Processes hierarchy events occurring on this component by 6420 * dispatching them to any registered 6421 * <code>HierarchyListener</code> objects. 6422 * <p> 6423 * This method is not called unless hierarchy events 6424 * are enabled for this component. Hierarchy events are enabled 6425 * when one of the following occurs: 6426 * <p><ul> 6427 * <li>An <code>HierarchyListener</code> object is registered 6428 * via <code>addHierarchyListener</code>. 6429 * <li>Hierarchy events are enabled via <code>enableEvents</code>. 6430 * </ul> 6431 * <p>Note that if the event parameter is <code>null</code> 6432 * the behavior is unspecified and may result in an 6433 * exception. 6434 * 6435 * @param e the hierarchy event 6436 * @see java.awt.event.HierarchyEvent 6437 * @see java.awt.event.HierarchyListener 6438 * @see #addHierarchyListener 6439 * @see #enableEvents 6440 * @since 1.3 6441 */ 6442 protected void processHierarchyEvent(HierarchyEvent e) { 6443 HierarchyListener listener = hierarchyListener; 6444 if (listener != null) { 6445 int id = e.getID(); 6446 switch (id) { 6447 case HierarchyEvent.HIERARCHY_CHANGED: 6448 listener.hierarchyChanged(e); 6449 break; 6450 } 6451 } 6452 } 6453 6454 /** 6455 * Processes hierarchy bounds events occurring on this component by 6456 * dispatching them to any registered 6457 * <code>HierarchyBoundsListener</code> objects. 6458 * <p> 6459 * This method is not called unless hierarchy bounds events 6460 * are enabled for this component. Hierarchy bounds events are enabled 6461 * when one of the following occurs: 6462 * <p><ul> 6463 * <li>An <code>HierarchyBoundsListener</code> object is registered 6464 * via <code>addHierarchyBoundsListener</code>. 6465 * <li>Hierarchy bounds events are enabled via <code>enableEvents</code>. 6466 * </ul> 6467 * <p>Note that if the event parameter is <code>null</code> 6468 * the behavior is unspecified and may result in an 6469 * exception. 6470 * 6471 * @param e the hierarchy event 6472 * @see java.awt.event.HierarchyEvent 6473 * @see java.awt.event.HierarchyBoundsListener 6474 * @see #addHierarchyBoundsListener 6475 * @see #enableEvents 6476 * @since 1.3 6477 */ 6478 protected void processHierarchyBoundsEvent(HierarchyEvent e) { 6479 HierarchyBoundsListener listener = hierarchyBoundsListener; 6480 if (listener != null) { 6481 int id = e.getID(); 6482 switch (id) { 6483 case HierarchyEvent.ANCESTOR_MOVED: 6484 listener.ancestorMoved(e); 6485 break; 6486 case HierarchyEvent.ANCESTOR_RESIZED: 6487 listener.ancestorResized(e); 6488 break; 6489 } 6490 } 6491 } 6492 6493 /** 6494 * @deprecated As of JDK version 1.1 6495 * replaced by processEvent(AWTEvent). 6496 */ 6497 @Deprecated 6498 public boolean handleEvent(Event evt) { 6499 switch (evt.id) { 6500 case Event.MOUSE_ENTER: 6501 return mouseEnter(evt, evt.x, evt.y); 6502 6503 case Event.MOUSE_EXIT: 6504 return mouseExit(evt, evt.x, evt.y); 6505 6506 case Event.MOUSE_MOVE: 6507 return mouseMove(evt, evt.x, evt.y); 6508 6509 case Event.MOUSE_DOWN: 6510 return mouseDown(evt, evt.x, evt.y); 6511 6512 case Event.MOUSE_DRAG: 6513 return mouseDrag(evt, evt.x, evt.y); 6514 6515 case Event.MOUSE_UP: 6516 return mouseUp(evt, evt.x, evt.y); 6517 6518 case Event.KEY_PRESS: 6519 case Event.KEY_ACTION: 6520 return keyDown(evt, evt.key); 6521 6522 case Event.KEY_RELEASE: 6523 case Event.KEY_ACTION_RELEASE: 6524 return keyUp(evt, evt.key); 6525 6526 case Event.ACTION_EVENT: 6527 return action(evt, evt.arg); 6528 case Event.GOT_FOCUS: 6529 return gotFocus(evt, evt.arg); 6530 case Event.LOST_FOCUS: 6531 return lostFocus(evt, evt.arg); 6532 } 6533 return false; 6534 } 6535 6536 /** 6537 * @deprecated As of JDK version 1.1, 6538 * replaced by processMouseEvent(MouseEvent). 6539 */ 6540 @Deprecated 6541 public boolean mouseDown(Event evt, int x, int y) { 6542 return false; 6543 } 6544 6545 /** 6546 * @deprecated As of JDK version 1.1, 6547 * replaced by processMouseMotionEvent(MouseEvent). 6548 */ 6549 @Deprecated 6550 public boolean mouseDrag(Event evt, int x, int y) { 6551 return false; 6552 } 6553 6554 /** 6555 * @deprecated As of JDK version 1.1, 6556 * replaced by processMouseEvent(MouseEvent). 6557 */ 6558 @Deprecated 6559 public boolean mouseUp(Event evt, int x, int y) { 6560 return false; 6561 } 6562 6563 /** 6564 * @deprecated As of JDK version 1.1, 6565 * replaced by processMouseMotionEvent(MouseEvent). 6566 */ 6567 @Deprecated 6568 public boolean mouseMove(Event evt, int x, int y) { 6569 return false; 6570 } 6571 6572 /** 6573 * @deprecated As of JDK version 1.1, 6574 * replaced by processMouseEvent(MouseEvent). 6575 */ 6576 @Deprecated 6577 public boolean mouseEnter(Event evt, int x, int y) { 6578 return false; 6579 } 6580 6581 /** 6582 * @deprecated As of JDK version 1.1, 6583 * replaced by processMouseEvent(MouseEvent). 6584 */ 6585 @Deprecated 6586 public boolean mouseExit(Event evt, int x, int y) { 6587 return false; 6588 } 6589 6590 /** 6591 * @deprecated As of JDK version 1.1, 6592 * replaced by processKeyEvent(KeyEvent). 6593 */ 6594 @Deprecated 6595 public boolean keyDown(Event evt, int key) { 6596 return false; 6597 } 6598 6599 /** 6600 * @deprecated As of JDK version 1.1, 6601 * replaced by processKeyEvent(KeyEvent). 6602 */ 6603 @Deprecated 6604 public boolean keyUp(Event evt, int key) { 6605 return false; 6606 } 6607 6608 /** 6609 * @deprecated As of JDK version 1.1, 6610 * should register this component as ActionListener on component 6611 * which fires action events. 6612 */ 6613 @Deprecated 6614 public boolean action(Event evt, Object what) { 6615 return false; 6616 } 6617 6618 /** 6619 * Makes this <code>Component</code> displayable by connecting it to a 6620 * native screen resource. 6621 * This method is called internally by the toolkit and should 6622 * not be called directly by programs. 6623 * @see #isDisplayable 6624 * @see #removeNotify 6625 * @since JDK1.0 6626 */ 6627 public void addNotify() { 6628 synchronized (getTreeLock()) { 6629 ComponentPeer peer = this.peer; 6630 if (peer == null || peer instanceof LightweightPeer){ 6631 if (peer == null) { 6632 // Update both the Component's peer variable and the local 6633 // variable we use for thread safety. 6634 this.peer = peer = getToolkit().createComponent(this); 6635 } 6636 6637 // This is a lightweight component which means it won't be 6638 // able to get window-related events by itself. If any 6639 // have been enabled, then the nearest native container must 6640 // be enabled. 6641 if (parent != null) { 6642 long mask = 0; 6643 if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) { 6644 mask |= AWTEvent.MOUSE_EVENT_MASK; 6645 } 6646 if ((mouseMotionListener != null) || 6647 ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) { 6648 mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK; 6649 } 6650 if ((mouseWheelListener != null ) || 6651 ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) { 6652 mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK; 6653 } 6654 if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) { 6655 mask |= AWTEvent.FOCUS_EVENT_MASK; 6656 } 6657 if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) { 6658 mask |= AWTEvent.KEY_EVENT_MASK; 6659 } 6660 if (mask != 0) { 6661 parent.proxyEnableEvents(mask); 6662 } 6663 } 6664 } else { 6665 // It's native. If the parent is lightweight it 6666 // will need some help. 6667 Container parent = this.parent; 6668 if (parent != null && parent.peer instanceof LightweightPeer) { 6669 relocateComponent(); 6670 } 6671 } 6672 invalidate(); 6673 6674 int npopups = (popups != null? popups.size() : 0); 6675 for (int i = 0 ; i < npopups ; i++) { 6676 PopupMenu popup = (PopupMenu)popups.elementAt(i); 6677 popup.addNotify(); 6678 } 6679 6680 if (dropTarget != null) dropTarget.addNotify(peer); 6681 6682 peerFont = getFont(); 6683 6684 if (getContainer() != null && !isAddNotifyComplete) { 6685 getContainer().increaseComponentCount(this); 6686 } 6687 6688 6689 // Update stacking order 6690 updateZOrder(); 6691 6692 if (!isAddNotifyComplete) { 6693 mixOnShowing(); 6694 } 6695 6696 isAddNotifyComplete = true; 6697 6698 if (hierarchyListener != null || 6699 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 6700 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { 6701 HierarchyEvent e = 6702 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, 6703 this, parent, 6704 HierarchyEvent.DISPLAYABILITY_CHANGED | 6705 ((isRecursivelyVisible()) 6706 ? HierarchyEvent.SHOWING_CHANGED 6707 : 0)); 6708 dispatchEvent(e); 6709 } 6710 } 6711 } 6712 6713 /** 6714 * Makes this <code>Component</code> undisplayable by destroying it native 6715 * screen resource. 6716 * <p> 6717 * This method is called by the toolkit internally and should 6718 * not be called directly by programs. Code overriding 6719 * this method should call <code>super.removeNotify</code> as 6720 * the first line of the overriding method. 6721 * 6722 * @see #isDisplayable 6723 * @see #addNotify 6724 * @since JDK1.0 6725 */ 6726 public void removeNotify() { 6727 KeyboardFocusManager.clearMostRecentFocusOwner(this); 6728 if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 6729 getPermanentFocusOwner() == this) 6730 { 6731 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 6732 setGlobalPermanentFocusOwner(null); 6733 } 6734 6735 synchronized (getTreeLock()) { 6736 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) { 6737 transferFocus(true); 6738 } 6739 6740 if (getContainer() != null && isAddNotifyComplete) { 6741 getContainer().decreaseComponentCount(this); 6742 } 6743 6744 int npopups = (popups != null? popups.size() : 0); 6745 for (int i = 0 ; i < npopups ; i++) { 6746 PopupMenu popup = (PopupMenu)popups.elementAt(i); 6747 popup.removeNotify(); 6748 } 6749 // If there is any input context for this component, notify 6750 // that this component is being removed. (This has to be done 6751 // before hiding peer.) 6752 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { 6753 InputContext inputContext = getInputContext(); 6754 if (inputContext != null) { 6755 inputContext.removeNotify(this); 6756 } 6757 } 6758 6759 ComponentPeer p = peer; 6760 if (p != null) { 6761 boolean isLightweight = isLightweight(); 6762 6763 if (bufferStrategy instanceof FlipBufferStrategy) { 6764 ((FlipBufferStrategy)bufferStrategy).destroyBuffers(); 6765 } 6766 6767 if (dropTarget != null) dropTarget.removeNotify(peer); 6768 6769 // Hide peer first to stop system events such as cursor moves. 6770 if (visible) { 6771 p.setVisible(false); 6772 } 6773 6774 peer = null; // Stop peer updates. 6775 peerFont = null; 6776 6777 Toolkit.getEventQueue().removeSourceEvents(this, false); 6778 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 6779 discardKeyEvents(this); 6780 6781 p.dispose(); 6782 6783 mixOnHiding(isLightweight); 6784 6785 isAddNotifyComplete = false; 6786 // Nullifying compoundShape means that the component has normal shape 6787 // (or has no shape at all). 6788 this.compoundShape = null; 6789 } 6790 6791 if (hierarchyListener != null || 6792 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 6793 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { 6794 HierarchyEvent e = 6795 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, 6796 this, parent, 6797 HierarchyEvent.DISPLAYABILITY_CHANGED | 6798 ((isRecursivelyVisible()) 6799 ? HierarchyEvent.SHOWING_CHANGED 6800 : 0)); 6801 dispatchEvent(e); 6802 } 6803 } 6804 } 6805 6806 /** 6807 * @deprecated As of JDK version 1.1, 6808 * replaced by processFocusEvent(FocusEvent). 6809 */ 6810 @Deprecated 6811 public boolean gotFocus(Event evt, Object what) { 6812 return false; 6813 } 6814 6815 /** 6816 * @deprecated As of JDK version 1.1, 6817 * replaced by processFocusEvent(FocusEvent). 6818 */ 6819 @Deprecated 6820 public boolean lostFocus(Event evt, Object what) { 6821 return false; 6822 } 6823 6824 /** 6825 * Returns whether this <code>Component</code> can become the focus 6826 * owner. 6827 * 6828 * @return <code>true</code> if this <code>Component</code> is 6829 * focusable; <code>false</code> otherwise 6830 * @see #setFocusable 6831 * @since JDK1.1 6832 * @deprecated As of 1.4, replaced by <code>isFocusable()</code>. 6833 */ 6834 @Deprecated 6835 public boolean isFocusTraversable() { 6836 if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) { 6837 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT; 6838 } 6839 return focusable; 6840 } 6841 6842 /** 6843 * Returns whether this Component can be focused. 6844 * 6845 * @return <code>true</code> if this Component is focusable; 6846 * <code>false</code> otherwise. 6847 * @see #setFocusable 6848 * @since 1.4 6849 */ 6850 public boolean isFocusable() { 6851 return isFocusTraversable(); 6852 } 6853 6854 /** 6855 * Sets the focusable state of this Component to the specified value. This 6856 * value overrides the Component's default focusability. 6857 * 6858 * @param focusable indicates whether this Component is focusable 6859 * @see #isFocusable 6860 * @since 1.4 6861 * @beaninfo 6862 * bound: true 6863 */ 6864 public void setFocusable(boolean focusable) { 6865 boolean oldFocusable; 6866 synchronized (this) { 6867 oldFocusable = this.focusable; 6868 this.focusable = focusable; 6869 } 6870 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET; 6871 6872 firePropertyChange("focusable", oldFocusable, focusable); 6873 if (oldFocusable && !focusable) { 6874 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) { 6875 transferFocus(true); 6876 } 6877 KeyboardFocusManager.clearMostRecentFocusOwner(this); 6878 } 6879 } 6880 6881 final boolean isFocusTraversableOverridden() { 6882 return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT); 6883 } 6884 6885 /** 6886 * Sets the focus traversal keys for a given traversal operation for this 6887 * Component. 6888 * <p> 6889 * The default values for a Component's focus traversal keys are 6890 * implementation-dependent. Sun recommends that all implementations for a 6891 * particular native platform use the same default values. The 6892 * recommendations for Windows and Unix are listed below. These 6893 * recommendations are used in the Sun AWT implementations. 6894 * 6895 * <table border=1 summary="Recommended default values for a Component's focus traversal keys"> 6896 * <tr> 6897 * <th>Identifier</th> 6898 * <th>Meaning</th> 6899 * <th>Default</th> 6900 * </tr> 6901 * <tr> 6902 * <td>KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS</td> 6903 * <td>Normal forward keyboard traversal</td> 6904 * <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED</td> 6905 * </tr> 6906 * <tr> 6907 * <td>KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS</td> 6908 * <td>Normal reverse keyboard traversal</td> 6909 * <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED</td> 6910 * </tr> 6911 * <tr> 6912 * <td>KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS</td> 6913 * <td>Go up one focus traversal cycle</td> 6914 * <td>none</td> 6915 * </tr> 6916 * </table> 6917 * 6918 * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is 6919 * recommended. 6920 * <p> 6921 * Using the AWTKeyStroke API, client code can specify on which of two 6922 * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal 6923 * operation will occur. Regardless of which KeyEvent is specified, 6924 * however, all KeyEvents related to the focus traversal key, including the 6925 * associated KEY_TYPED event, will be consumed, and will not be dispatched 6926 * to any Component. It is a runtime error to specify a KEY_TYPED event as 6927 * mapping to a focus traversal operation, or to map the same event to 6928 * multiple default focus traversal operations. 6929 * <p> 6930 * If a value of null is specified for the Set, this Component inherits the 6931 * Set from its parent. If all ancestors of this Component have null 6932 * specified for the Set, then the current KeyboardFocusManager's default 6933 * Set is used. 6934 * 6935 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 6936 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 6937 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 6938 * @param keystrokes the Set of AWTKeyStroke for the specified operation 6939 * @see #getFocusTraversalKeys 6940 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 6941 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 6942 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 6943 * @throws IllegalArgumentException if id is not one of 6944 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 6945 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 6946 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes 6947 * contains null, or if any Object in keystrokes is not an 6948 * AWTKeyStroke, or if any keystroke represents a KEY_TYPED event, 6949 * or if any keystroke already maps to another focus traversal 6950 * operation for this Component 6951 * @since 1.4 6952 * @beaninfo 6953 * bound: true 6954 */ 6955 public void setFocusTraversalKeys(int id, 6956 Set<? extends AWTKeyStroke> keystrokes) 6957 { 6958 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 6959 throw new IllegalArgumentException("invalid focus traversal key identifier"); 6960 } 6961 6962 setFocusTraversalKeys_NoIDCheck(id, keystrokes); 6963 } 6964 6965 /** 6966 * Returns the Set of focus traversal keys for a given traversal operation 6967 * for this Component. (See 6968 * <code>setFocusTraversalKeys</code> for a full description of each key.) 6969 * <p> 6970 * If a Set of traversal keys has not been explicitly defined for this 6971 * Component, then this Component's parent's Set is returned. If no Set 6972 * has been explicitly defined for any of this Component's ancestors, then 6973 * the current KeyboardFocusManager's default Set is returned. 6974 * 6975 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 6976 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 6977 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 6978 * @return the Set of AWTKeyStrokes for the specified operation. The Set 6979 * will be unmodifiable, and may be empty. null will never be 6980 * returned. 6981 * @see #setFocusTraversalKeys 6982 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 6983 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 6984 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 6985 * @throws IllegalArgumentException if id is not one of 6986 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 6987 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 6988 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 6989 * @since 1.4 6990 */ 6991 public Set<AWTKeyStroke> getFocusTraversalKeys(int id) { 6992 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 6993 throw new IllegalArgumentException("invalid focus traversal key identifier"); 6994 } 6995 6996 return getFocusTraversalKeys_NoIDCheck(id); 6997 } 6998 6999 // We define these methods so that Container does not need to repeat this 7000 // code. Container cannot call super.<method> because Container allows 7001 // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method 7002 // would erroneously generate an IllegalArgumentException for 7003 // DOWN_CYCLE_TRAVERSAL_KEY. 7004 final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) { 7005 Set oldKeys; 7006 7007 synchronized (this) { 7008 if (focusTraversalKeys == null) { 7009 initializeFocusTraversalKeys(); 7010 } 7011 7012 if (keystrokes != null) { 7013 for (Iterator iter = keystrokes.iterator(); iter.hasNext(); ) { 7014 Object obj = iter.next(); 7015 7016 if (obj == null) { 7017 throw new IllegalArgumentException("cannot set null focus traversal key"); 7018 } 7019 7020 // Fix for 6195828: 7021 //According to javadoc this method should throw IAE instead of ClassCastException 7022 if (!(obj instanceof AWTKeyStroke)) { 7023 throw new IllegalArgumentException("object is expected to be AWTKeyStroke"); 7024 } 7025 AWTKeyStroke keystroke = (AWTKeyStroke)obj; 7026 7027 if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { 7028 throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events"); 7029 } 7030 7031 for (int i = 0; i < focusTraversalKeys.length; i++) { 7032 if (i == id) { 7033 continue; 7034 } 7035 7036 if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke)) 7037 { 7038 throw new IllegalArgumentException("focus traversal keys must be unique for a Component"); 7039 } 7040 } 7041 } 7042 } 7043 7044 oldKeys = focusTraversalKeys[id]; 7045 focusTraversalKeys[id] = (keystrokes != null) 7046 ? Collections.unmodifiableSet(new HashSet(keystrokes)) 7047 : null; 7048 } 7049 7050 firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys, 7051 keystrokes); 7052 } 7053 final Set getFocusTraversalKeys_NoIDCheck(int id) { 7054 // Okay to return Set directly because it is an unmodifiable view 7055 Set keystrokes = (focusTraversalKeys != null) 7056 ? focusTraversalKeys[id] 7057 : null; 7058 7059 if (keystrokes != null) { 7060 return keystrokes; 7061 } else { 7062 Container parent = this.parent; 7063 if (parent != null) { 7064 return parent.getFocusTraversalKeys(id); 7065 } else { 7066 return KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7067 getDefaultFocusTraversalKeys(id); 7068 } 7069 } 7070 } 7071 7072 /** 7073 * Returns whether the Set of focus traversal keys for the given focus 7074 * traversal operation has been explicitly defined for this Component. If 7075 * this method returns <code>false</code>, this Component is inheriting the 7076 * Set from an ancestor, or from the current KeyboardFocusManager. 7077 * 7078 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7079 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7080 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7081 * @return <code>true</code> if the the Set of focus traversal keys for the 7082 * given focus traversal operation has been explicitly defined for 7083 * this Component; <code>false</code> otherwise. 7084 * @throws IllegalArgumentException if id is not one of 7085 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7086 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7087 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7088 * @since 1.4 7089 */ 7090 public boolean areFocusTraversalKeysSet(int id) { 7091 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7092 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7093 } 7094 7095 return (focusTraversalKeys != null && focusTraversalKeys[id] != null); 7096 } 7097 7098 /** 7099 * Sets whether focus traversal keys are enabled for this Component. 7100 * Components for which focus traversal keys are disabled receive key 7101 * events for focus traversal keys. Components for which focus traversal 7102 * keys are enabled do not see these events; instead, the events are 7103 * automatically converted to traversal operations. 7104 * 7105 * @param focusTraversalKeysEnabled whether focus traversal keys are 7106 * enabled for this Component 7107 * @see #getFocusTraversalKeysEnabled 7108 * @see #setFocusTraversalKeys 7109 * @see #getFocusTraversalKeys 7110 * @since 1.4 7111 * @beaninfo 7112 * bound: true 7113 */ 7114 public void setFocusTraversalKeysEnabled(boolean 7115 focusTraversalKeysEnabled) { 7116 boolean oldFocusTraversalKeysEnabled; 7117 synchronized (this) { 7118 oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled; 7119 this.focusTraversalKeysEnabled = focusTraversalKeysEnabled; 7120 } 7121 firePropertyChange("focusTraversalKeysEnabled", 7122 oldFocusTraversalKeysEnabled, 7123 focusTraversalKeysEnabled); 7124 } 7125 7126 /** 7127 * Returns whether focus traversal keys are enabled for this Component. 7128 * Components for which focus traversal keys are disabled receive key 7129 * events for focus traversal keys. Components for which focus traversal 7130 * keys are enabled do not see these events; instead, the events are 7131 * automatically converted to traversal operations. 7132 * 7133 * @return whether focus traversal keys are enabled for this Component 7134 * @see #setFocusTraversalKeysEnabled 7135 * @see #setFocusTraversalKeys 7136 * @see #getFocusTraversalKeys 7137 * @since 1.4 7138 */ 7139 public boolean getFocusTraversalKeysEnabled() { 7140 return focusTraversalKeysEnabled; 7141 } 7142 7143 /** 7144 * Requests that this Component get the input focus, and that this 7145 * Component's top-level ancestor become the focused Window. This 7146 * component must be displayable, focusable, visible and all of 7147 * its ancestors (with the exception of the top-level Window) must 7148 * be visible for the request to be granted. Every effort will be 7149 * made to honor the request; however, in some cases it may be 7150 * impossible to do so. Developers must never assume that this 7151 * Component is the focus owner until this Component receives a 7152 * FOCUS_GAINED event. If this request is denied because this 7153 * Component's top-level Window cannot become the focused Window, 7154 * the request will be remembered and will be granted when the 7155 * Window is later focused by the user. 7156 * <p> 7157 * This method cannot be used to set the focus owner to no Component at 7158 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> 7159 * instead. 7160 * <p> 7161 * Because the focus behavior of this method is platform-dependent, 7162 * developers are strongly encouraged to use 7163 * <code>requestFocusInWindow</code> when possible. 7164 * 7165 * <p>Note: Not all focus transfers result from invoking this method. As 7166 * such, a component may receive focus without this or any of the other 7167 * {@code requestFocus} methods of {@code Component} being invoked. 7168 * 7169 * @see #requestFocusInWindow 7170 * @see java.awt.event.FocusEvent 7171 * @see #addFocusListener 7172 * @see #isFocusable 7173 * @see #isDisplayable 7174 * @see KeyboardFocusManager#clearGlobalFocusOwner 7175 * @since JDK1.0 7176 */ 7177 public void requestFocus() { 7178 requestFocusHelper(false, true); 7179 } 7180 7181 boolean requestFocus(CausedFocusEvent.Cause cause) { 7182 return requestFocusHelper(false, true, cause); 7183 } 7184 7185 /** 7186 * Requests that this <code>Component</code> get the input focus, 7187 * and that this <code>Component</code>'s top-level ancestor 7188 * become the focused <code>Window</code>. This component must be 7189 * displayable, focusable, visible and all of its ancestors (with 7190 * the exception of the top-level Window) must be visible for the 7191 * request to be granted. Every effort will be made to honor the 7192 * request; however, in some cases it may be impossible to do 7193 * so. Developers must never assume that this component is the 7194 * focus owner until this component receives a FOCUS_GAINED 7195 * event. If this request is denied because this component's 7196 * top-level window cannot become the focused window, the request 7197 * will be remembered and will be granted when the window is later 7198 * focused by the user. 7199 * <p> 7200 * This method returns a boolean value. If <code>false</code> is returned, 7201 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7202 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7203 * extraordinary event, such as disposal of the component's peer, occurs 7204 * before the request can be granted by the native windowing system. Again, 7205 * while a return value of <code>true</code> indicates that the request is 7206 * likely to succeed, developers must never assume that this component is 7207 * the focus owner until this component receives a FOCUS_GAINED event. 7208 * <p> 7209 * This method cannot be used to set the focus owner to no component at 7210 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> 7211 * instead. 7212 * <p> 7213 * Because the focus behavior of this method is platform-dependent, 7214 * developers are strongly encouraged to use 7215 * <code>requestFocusInWindow</code> when possible. 7216 * <p> 7217 * Every effort will be made to ensure that <code>FocusEvent</code>s 7218 * generated as a 7219 * result of this request will have the specified temporary value. However, 7220 * because specifying an arbitrary temporary state may not be implementable 7221 * on all native windowing systems, correct behavior for this method can be 7222 * guaranteed only for lightweight <code>Component</code>s. 7223 * This method is not intended 7224 * for general use, but exists instead as a hook for lightweight component 7225 * libraries, such as Swing. 7226 * 7227 * <p>Note: Not all focus transfers result from invoking this method. As 7228 * such, a component may receive focus without this or any of the other 7229 * {@code requestFocus} methods of {@code Component} being invoked. 7230 * 7231 * @param temporary true if the focus change is temporary, 7232 * such as when the window loses the focus; for 7233 * more information on temporary focus changes see the 7234 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7235 * @return <code>false</code> if the focus change request is guaranteed to 7236 * fail; <code>true</code> if it is likely to succeed 7237 * @see java.awt.event.FocusEvent 7238 * @see #addFocusListener 7239 * @see #isFocusable 7240 * @see #isDisplayable 7241 * @see KeyboardFocusManager#clearGlobalFocusOwner 7242 * @since 1.4 7243 */ 7244 protected boolean requestFocus(boolean temporary) { 7245 return requestFocusHelper(temporary, true); 7246 } 7247 7248 boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) { 7249 return requestFocusHelper(temporary, true, cause); 7250 } 7251 /** 7252 * Requests that this Component get the input focus, if this 7253 * Component's top-level ancestor is already the focused 7254 * Window. This component must be displayable, focusable, visible 7255 * and all of its ancestors (with the exception of the top-level 7256 * Window) must be visible for the request to be granted. Every 7257 * effort will be made to honor the request; however, in some 7258 * cases it may be impossible to do so. Developers must never 7259 * assume that this Component is the focus owner until this 7260 * Component receives a FOCUS_GAINED event. 7261 * <p> 7262 * This method returns a boolean value. If <code>false</code> is returned, 7263 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7264 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7265 * extraordinary event, such as disposal of the Component's peer, occurs 7266 * before the request can be granted by the native windowing system. Again, 7267 * while a return value of <code>true</code> indicates that the request is 7268 * likely to succeed, developers must never assume that this Component is 7269 * the focus owner until this Component receives a FOCUS_GAINED event. 7270 * <p> 7271 * This method cannot be used to set the focus owner to no Component at 7272 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> 7273 * instead. 7274 * <p> 7275 * The focus behavior of this method can be implemented uniformly across 7276 * platforms, and thus developers are strongly encouraged to use this 7277 * method over <code>requestFocus</code> when possible. Code which relies 7278 * on <code>requestFocus</code> may exhibit different focus behavior on 7279 * different platforms. 7280 * 7281 * <p>Note: Not all focus transfers result from invoking this method. As 7282 * such, a component may receive focus without this or any of the other 7283 * {@code requestFocus} methods of {@code Component} being invoked. 7284 * 7285 * @return <code>false</code> if the focus change request is guaranteed to 7286 * fail; <code>true</code> if it is likely to succeed 7287 * @see #requestFocus 7288 * @see java.awt.event.FocusEvent 7289 * @see #addFocusListener 7290 * @see #isFocusable 7291 * @see #isDisplayable 7292 * @see KeyboardFocusManager#clearGlobalFocusOwner 7293 * @since 1.4 7294 */ 7295 public boolean requestFocusInWindow() { 7296 return requestFocusHelper(false, false); 7297 } 7298 7299 boolean requestFocusInWindow(CausedFocusEvent.Cause cause) { 7300 return requestFocusHelper(false, false, cause); 7301 } 7302 7303 /** 7304 * Requests that this <code>Component</code> get the input focus, 7305 * if this <code>Component</code>'s top-level ancestor is already 7306 * the focused <code>Window</code>. This component must be 7307 * displayable, focusable, visible and all of its ancestors (with 7308 * the exception of the top-level Window) must be visible for the 7309 * request to be granted. Every effort will be made to honor the 7310 * request; however, in some cases it may be impossible to do 7311 * so. Developers must never assume that this component is the 7312 * focus owner until this component receives a FOCUS_GAINED event. 7313 * <p> 7314 * This method returns a boolean value. If <code>false</code> is returned, 7315 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7316 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7317 * extraordinary event, such as disposal of the component's peer, occurs 7318 * before the request can be granted by the native windowing system. Again, 7319 * while a return value of <code>true</code> indicates that the request is 7320 * likely to succeed, developers must never assume that this component is 7321 * the focus owner until this component receives a FOCUS_GAINED event. 7322 * <p> 7323 * This method cannot be used to set the focus owner to no component at 7324 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> 7325 * instead. 7326 * <p> 7327 * The focus behavior of this method can be implemented uniformly across 7328 * platforms, and thus developers are strongly encouraged to use this 7329 * method over <code>requestFocus</code> when possible. Code which relies 7330 * on <code>requestFocus</code> may exhibit different focus behavior on 7331 * different platforms. 7332 * <p> 7333 * Every effort will be made to ensure that <code>FocusEvent</code>s 7334 * generated as a 7335 * result of this request will have the specified temporary value. However, 7336 * because specifying an arbitrary temporary state may not be implementable 7337 * on all native windowing systems, correct behavior for this method can be 7338 * guaranteed only for lightweight components. This method is not intended 7339 * for general use, but exists instead as a hook for lightweight component 7340 * libraries, such as Swing. 7341 * 7342 * <p>Note: Not all focus transfers result from invoking this method. As 7343 * such, a component may receive focus without this or any of the other 7344 * {@code requestFocus} methods of {@code Component} being invoked. 7345 * 7346 * @param temporary true if the focus change is temporary, 7347 * such as when the window loses the focus; for 7348 * more information on temporary focus changes see the 7349 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7350 * @return <code>false</code> if the focus change request is guaranteed to 7351 * fail; <code>true</code> if it is likely to succeed 7352 * @see #requestFocus 7353 * @see java.awt.event.FocusEvent 7354 * @see #addFocusListener 7355 * @see #isFocusable 7356 * @see #isDisplayable 7357 * @see KeyboardFocusManager#clearGlobalFocusOwner 7358 * @since 1.4 7359 */ 7360 protected boolean requestFocusInWindow(boolean temporary) { 7361 return requestFocusHelper(temporary, false); 7362 } 7363 7364 boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) { 7365 return requestFocusHelper(temporary, false, cause); 7366 } 7367 7368 final boolean requestFocusHelper(boolean temporary, 7369 boolean focusedWindowChangeAllowed) { 7370 return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN); 7371 } 7372 7373 final boolean requestFocusHelper(boolean temporary, 7374 boolean focusedWindowChangeAllowed, 7375 CausedFocusEvent.Cause cause) 7376 { 7377 if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) { 7378 if (focusLog.isLoggable(Level.FINEST)) { 7379 focusLog.log(Level.FINEST, "requestFocus is not accepted"); 7380 } 7381 return false; 7382 } 7383 7384 // Update most-recent map 7385 KeyboardFocusManager.setMostRecentFocusOwner(this); 7386 7387 Component window = this; 7388 while ( (window != null) && !(window instanceof Window)) { 7389 if (!window.isVisible()) { 7390 if (focusLog.isLoggable(Level.FINEST)) { 7391 focusLog.log(Level.FINEST, "component is recurively invisible"); 7392 } 7393 return false; 7394 } 7395 window = window.parent; 7396 } 7397 7398 ComponentPeer peer = this.peer; 7399 Component heavyweight = (peer instanceof LightweightPeer) 7400 ? getNativeContainer() : this; 7401 if (heavyweight == null || !heavyweight.isVisible()) { 7402 if (focusLog.isLoggable(Level.FINEST)) { 7403 focusLog.log(Level.FINEST, "Component is not a part of visible hierarchy"); 7404 } 7405 return false; 7406 } 7407 peer = heavyweight.peer; 7408 if (peer == null) { 7409 if (focusLog.isLoggable(Level.FINEST)) { 7410 focusLog.log(Level.FINEST, "Peer is null"); 7411 } 7412 return false; 7413 } 7414 7415 // Focus this Component 7416 long time = EventQueue.getMostRecentEventTime(); 7417 boolean success = peer.requestFocus 7418 (this, temporary, focusedWindowChangeAllowed, time, cause); 7419 if (!success) { 7420 KeyboardFocusManager.getCurrentKeyboardFocusManager 7421 (appContext).dequeueKeyEvents(time, this); 7422 if (focusLog.isLoggable(Level.FINEST)) { 7423 focusLog.log(Level.FINEST, "Peer request failed"); 7424 } 7425 } else { 7426 if (focusLog.isLoggable(Level.FINEST)) { 7427 focusLog.log(Level.FINEST, "Pass for " + this); 7428 } 7429 } 7430 return success; 7431 } 7432 7433 private boolean isRequestFocusAccepted(boolean temporary, 7434 boolean focusedWindowChangeAllowed, 7435 CausedFocusEvent.Cause cause) 7436 { 7437 if (!isFocusable() || !isVisible()) { 7438 if (focusLog.isLoggable(Level.FINEST)) { 7439 focusLog.log(Level.FINEST, "Not focusable or not visible"); 7440 } 7441 return false; 7442 } 7443 7444 ComponentPeer peer = this.peer; 7445 if (peer == null) { 7446 if (focusLog.isLoggable(Level.FINEST)) { 7447 focusLog.log(Level.FINEST, "peer is null"); 7448 } 7449 return false; 7450 } 7451 7452 Window window = getContainingWindow(); 7453 if (window == null || !((Window)window).isFocusableWindow()) { 7454 if (focusLog.isLoggable(Level.FINEST)) { 7455 focusLog.log(Level.FINEST, "Component doesn't have toplevel"); 7456 } 7457 return false; 7458 } 7459 7460 // We have passed all regular checks for focus request, 7461 // now let's call RequestFocusController and see what it says. 7462 Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window); 7463 if (focusOwner == null) { 7464 // sometimes most recent focus owner may be null, but focus owner is not 7465 // e.g. we reset most recent focus owner if user removes focus owner 7466 focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); 7467 if (focusOwner != null && focusOwner.getContainingWindow() != window) { 7468 focusOwner = null; 7469 } 7470 } 7471 7472 if (focusOwner == this || focusOwner == null) { 7473 // Controller is supposed to verify focus transfers and for this it 7474 // should know both from and to components. And it shouldn't verify 7475 // transfers from when these components are equal. 7476 if (focusLog.isLoggable(Level.FINEST)) { 7477 focusLog.log(Level.FINEST, "focus owner is null or this"); 7478 } 7479 return true; 7480 } 7481 7482 if (CausedFocusEvent.Cause.ACTIVATION == cause) { 7483 // we shouldn't call RequestFocusController in case we are 7484 // in activation. We do request focus on component which 7485 // has got temporary focus lost and then on component which is 7486 // most recent focus owner. But most recent focus owner can be 7487 // changed by requestFocsuXXX() call only, so this transfer has 7488 // been already approved. 7489 if (focusLog.isLoggable(Level.FINEST)) { 7490 focusLog.log(Level.FINEST, "cause is activation"); 7491 } 7492 return true; 7493 } 7494 7495 boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner, 7496 this, 7497 temporary, 7498 focusedWindowChangeAllowed, 7499 cause); 7500 if (focusLog.isLoggable(Level.FINEST)) { 7501 focusLog.log(Level.FINEST, "RequestFocusController returns {0}", ret); 7502 } 7503 7504 return ret; 7505 } 7506 7507 private static RequestFocusController requestFocusController = new DummyRequestFocusController(); 7508 7509 // Swing access this method through reflection to implement InputVerifier's functionality. 7510 // Perhaps, we should make this method public (later ;) 7511 private static class DummyRequestFocusController implements RequestFocusController { 7512 public boolean acceptRequestFocus(Component from, Component to, 7513 boolean temporary, boolean focusedWindowChangeAllowed, 7514 CausedFocusEvent.Cause cause) 7515 { 7516 return true; 7517 } 7518 }; 7519 7520 synchronized static void setRequestFocusController(RequestFocusController requestController) 7521 { 7522 if (requestController == null) { 7523 requestFocusController = new DummyRequestFocusController(); 7524 } else { 7525 requestFocusController = requestController; 7526 } 7527 } 7528 7529 /** 7530 * Returns the Container which is the focus cycle root of this Component's 7531 * focus traversal cycle. Each focus traversal cycle has only a single 7532 * focus cycle root and each Component which is not a Container belongs to 7533 * only a single focus traversal cycle. Containers which are focus cycle 7534 * roots belong to two cycles: one rooted at the Container itself, and one 7535 * rooted at the Container's nearest focus-cycle-root ancestor. For such 7536 * Containers, this method will return the Container's nearest focus-cycle- 7537 * root ancestor. 7538 * 7539 * @return this Component's nearest focus-cycle-root ancestor 7540 * @see Container#isFocusCycleRoot() 7541 * @since 1.4 7542 */ 7543 public Container getFocusCycleRootAncestor() { 7544 Container rootAncestor = this.parent; 7545 while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) { 7546 rootAncestor = rootAncestor.parent; 7547 } 7548 return rootAncestor; 7549 } 7550 7551 /** 7552 * Returns whether the specified Container is the focus cycle root of this 7553 * Component's focus traversal cycle. Each focus traversal cycle has only 7554 * a single focus cycle root and each Component which is not a Container 7555 * belongs to only a single focus traversal cycle. 7556 * 7557 * @param container the Container to be tested 7558 * @return <code>true</code> if the specified Container is a focus-cycle- 7559 * root of this Component; <code>false</code> otherwise 7560 * @see Container#isFocusCycleRoot() 7561 * @since 1.4 7562 */ 7563 public boolean isFocusCycleRoot(Container container) { 7564 Container rootAncestor = getFocusCycleRootAncestor(); 7565 return (rootAncestor == container); 7566 } 7567 7568 Container getTraversalRoot() { 7569 return getFocusCycleRootAncestor(); 7570 } 7571 7572 /** 7573 * Transfers the focus to the next component, as though this Component were 7574 * the focus owner. 7575 * @see #requestFocus() 7576 * @since JDK1.1 7577 */ 7578 public void transferFocus() { 7579 nextFocus(); 7580 } 7581 7582 /** 7583 * @deprecated As of JDK version 1.1, 7584 * replaced by transferFocus(). 7585 */ 7586 @Deprecated 7587 public void nextFocus() { 7588 transferFocus(false); 7589 } 7590 7591 boolean transferFocus(boolean clearOnFailure) { 7592 if (focusLog.isLoggable(Level.FINER)) { 7593 focusLog.finer("clearOnFailure = " + clearOnFailure); 7594 } 7595 Component toFocus = getNextFocusCandidate(); 7596 boolean res = false; 7597 if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) { 7598 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD); 7599 } 7600 if (clearOnFailure && !res) { 7601 if (focusLog.isLoggable(Level.FINER)) { 7602 focusLog.finer("clear global focus owner"); 7603 } 7604 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); 7605 } 7606 if (focusLog.isLoggable(Level.FINER)) { 7607 focusLog.finer("returning result: " + res); 7608 } 7609 return res; 7610 } 7611 7612 final Component getNextFocusCandidate() { 7613 Container rootAncestor = getTraversalRoot(); 7614 Component comp = this; 7615 while (rootAncestor != null && 7616 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 7617 { 7618 comp = rootAncestor; 7619 rootAncestor = comp.getFocusCycleRootAncestor(); 7620 } 7621 if (focusLog.isLoggable(Level.FINER)) { 7622 focusLog.finer("comp = " + comp + ", root = " + rootAncestor); 7623 } 7624 Component candidate = null; 7625 if (rootAncestor != null) { 7626 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 7627 Component toFocus = policy.getComponentAfter(rootAncestor, comp); 7628 if (focusLog.isLoggable(Level.FINER)) { 7629 focusLog.finer("component after is " + toFocus); 7630 } 7631 if (toFocus == null) { 7632 toFocus = policy.getDefaultComponent(rootAncestor); 7633 if (focusLog.isLoggable(Level.FINER)) { 7634 focusLog.finer("default component is " + toFocus); 7635 } 7636 } 7637 if (toFocus == null) { 7638 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this); 7639 if (applet != null) { 7640 toFocus = applet; 7641 } 7642 } 7643 candidate = toFocus; 7644 } 7645 if (focusLog.isLoggable(Level.FINER)) { 7646 focusLog.finer("Focus transfer candidate: " + candidate); 7647 } 7648 return candidate; 7649 } 7650 7651 /** 7652 * Transfers the focus to the previous component, as though this Component 7653 * were the focus owner. 7654 * @see #requestFocus() 7655 * @since 1.4 7656 */ 7657 public void transferFocusBackward() { 7658 transferFocusBackward(false); 7659 } 7660 7661 boolean transferFocusBackward(boolean clearOnFailure) { 7662 Container rootAncestor = getTraversalRoot(); 7663 Component comp = this; 7664 while (rootAncestor != null && 7665 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 7666 { 7667 comp = rootAncestor; 7668 rootAncestor = comp.getFocusCycleRootAncestor(); 7669 } 7670 boolean res = false; 7671 if (rootAncestor != null) { 7672 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 7673 Component toFocus = policy.getComponentBefore(rootAncestor, comp); 7674 if (toFocus == null) { 7675 toFocus = policy.getDefaultComponent(rootAncestor); 7676 } 7677 if (toFocus != null) { 7678 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD); 7679 } 7680 } 7681 if (!res) { 7682 if (focusLog.isLoggable(Level.FINER)) { 7683 focusLog.finer("clear global focus owner"); 7684 } 7685 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner(); 7686 } 7687 if (focusLog.isLoggable(Level.FINER)) { 7688 focusLog.finer("returning result: " + res); 7689 } 7690 return res; 7691 } 7692 7693 /** 7694 * Transfers the focus up one focus traversal cycle. Typically, the focus 7695 * owner is set to this Component's focus cycle root, and the current focus 7696 * cycle root is set to the new focus owner's focus cycle root. If, 7697 * however, this Component's focus cycle root is a Window, then the focus 7698 * owner is set to the focus cycle root's default Component to focus, and 7699 * the current focus cycle root is unchanged. 7700 * 7701 * @see #requestFocus() 7702 * @see Container#isFocusCycleRoot() 7703 * @see Container#setFocusCycleRoot(boolean) 7704 * @since 1.4 7705 */ 7706 public void transferFocusUpCycle() { 7707 Container rootAncestor; 7708 for (rootAncestor = getFocusCycleRootAncestor(); 7709 rootAncestor != null && !(rootAncestor.isShowing() && 7710 rootAncestor.isFocusable() && 7711 rootAncestor.isEnabled()); 7712 rootAncestor = rootAncestor.getFocusCycleRootAncestor()) { 7713 } 7714 7715 if (rootAncestor != null) { 7716 Container rootAncestorRootAncestor = 7717 rootAncestor.getFocusCycleRootAncestor(); 7718 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7719 setGlobalCurrentFocusCycleRoot( 7720 (rootAncestorRootAncestor != null) 7721 ? rootAncestorRootAncestor 7722 : rootAncestor); 7723 rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); 7724 } else { 7725 Window window = getContainingWindow(); 7726 7727 if (window != null) { 7728 Component toFocus = window.getFocusTraversalPolicy(). 7729 getDefaultComponent(window); 7730 if (toFocus != null) { 7731 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7732 setGlobalCurrentFocusCycleRoot(window); 7733 toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); 7734 } 7735 } 7736 } 7737 } 7738 7739 /** 7740 * Returns <code>true</code> if this <code>Component</code> is the 7741 * focus owner. This method is obsolete, and has been replaced by 7742 * <code>isFocusOwner()</code>. 7743 * 7744 * @return <code>true</code> if this <code>Component</code> is the 7745 * focus owner; <code>false</code> otherwise 7746 * @since 1.2 7747 */ 7748 public boolean hasFocus() { 7749 return (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7750 getFocusOwner() == this); 7751 } 7752 7753 /** 7754 * Returns <code>true</code> if this <code>Component</code> is the 7755 * focus owner. 7756 * 7757 * @return <code>true</code> if this <code>Component</code> is the 7758 * focus owner; <code>false</code> otherwise 7759 * @since 1.4 7760 */ 7761 public boolean isFocusOwner() { 7762 return hasFocus(); 7763 } 7764 7765 /* 7766 * Used to disallow auto-focus-transfer on disposal of the focus owner 7767 * in the process of disposing its parent container. 7768 */ 7769 private boolean autoFocusTransferOnDisposal = true; 7770 7771 void setAutoFocusTransferOnDisposal(boolean value) { 7772 autoFocusTransferOnDisposal = value; 7773 } 7774 7775 boolean isAutoFocusTransferOnDisposal() { 7776 return autoFocusTransferOnDisposal; 7777 } 7778 7779 /** 7780 * Adds the specified popup menu to the component. 7781 * @param popup the popup menu to be added to the component. 7782 * @see #remove(MenuComponent) 7783 * @exception NullPointerException if {@code popup} is {@code null} 7784 * @since JDK1.1 7785 */ 7786 public void add(PopupMenu popup) { 7787 synchronized (getTreeLock()) { 7788 if (popup.parent != null) { 7789 popup.parent.remove(popup); 7790 } 7791 if (popups == null) { 7792 popups = new Vector(); 7793 } 7794 popups.addElement(popup); 7795 popup.parent = this; 7796 7797 if (peer != null) { 7798 if (popup.peer == null) { 7799 popup.addNotify(); 7800 } 7801 } 7802 } 7803 } 7804 7805 /** 7806 * Removes the specified popup menu from the component. 7807 * @param popup the popup menu to be removed 7808 * @see #add(PopupMenu) 7809 * @since JDK1.1 7810 */ 7811 public void remove(MenuComponent popup) { 7812 synchronized (getTreeLock()) { 7813 if (popups == null) { 7814 return; 7815 } 7816 int index = popups.indexOf(popup); 7817 if (index >= 0) { 7818 PopupMenu pmenu = (PopupMenu)popup; 7819 if (pmenu.peer != null) { 7820 pmenu.removeNotify(); 7821 } 7822 pmenu.parent = null; 7823 popups.removeElementAt(index); 7824 if (popups.size() == 0) { 7825 popups = null; 7826 } 7827 } 7828 } 7829 } 7830 7831 /** 7832 * Returns a string representing the state of this component. This 7833 * method is intended to be used only for debugging purposes, and the 7834 * content and format of the returned string may vary between 7835 * implementations. The returned string may be empty but may not be 7836 * <code>null</code>. 7837 * 7838 * @return a string representation of this component's state 7839 * @since JDK1.0 7840 */ 7841 protected String paramString() { 7842 String thisName = getName(); 7843 String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height; 7844 if (!isValid()) { 7845 str += ",invalid"; 7846 } 7847 if (!visible) { 7848 str += ",hidden"; 7849 } 7850 if (!enabled) { 7851 str += ",disabled"; 7852 } 7853 return str; 7854 } 7855 7856 /** 7857 * Returns a string representation of this component and its values. 7858 * @return a string representation of this component 7859 * @since JDK1.0 7860 */ 7861 public String toString() { 7862 return getClass().getName() + "[" + paramString() + "]"; 7863 } 7864 7865 /** 7866 * Prints a listing of this component to the standard system output 7867 * stream <code>System.out</code>. 7868 * @see java.lang.System#out 7869 * @since JDK1.0 7870 */ 7871 public void list() { 7872 list(System.out, 0); 7873 } 7874 7875 /** 7876 * Prints a listing of this component to the specified output 7877 * stream. 7878 * @param out a print stream 7879 * @since JDK1.0 7880 */ 7881 public void list(PrintStream out) { 7882 list(out, 0); 7883 } 7884 7885 /** 7886 * Prints out a list, starting at the specified indentation, to the 7887 * specified print stream. 7888 * @param out a print stream 7889 * @param indent number of spaces to indent 7890 * @see java.io.PrintStream#println(java.lang.Object) 7891 * @since JDK1.0 7892 */ 7893 public void list(PrintStream out, int indent) { 7894 for (int i = 0 ; i < indent ; i++) { 7895 out.print(" "); 7896 } 7897 out.println(this); 7898 } 7899 7900 /** 7901 * Prints a listing to the specified print writer. 7902 * @param out the print writer to print to 7903 * @since JDK1.1 7904 */ 7905 public void list(PrintWriter out) { 7906 list(out, 0); 7907 } 7908 7909 /** 7910 * Prints out a list, starting at the specified indentation, to 7911 * the specified print writer. 7912 * @param out the print writer to print to 7913 * @param indent the number of spaces to indent 7914 * @see java.io.PrintStream#println(java.lang.Object) 7915 * @since JDK1.1 7916 */ 7917 public void list(PrintWriter out, int indent) { 7918 for (int i = 0 ; i < indent ; i++) { 7919 out.print(" "); 7920 } 7921 out.println(this); 7922 } 7923 7924 /* 7925 * Fetches the native container somewhere higher up in the component 7926 * tree that contains this component. 7927 */ 7928 Container getNativeContainer() { 7929 Container p = parent; 7930 while (p != null && p.peer instanceof LightweightPeer) { 7931 p = p.getParent(); 7932 } 7933 return p; 7934 } 7935 7936 /** 7937 * Adds a PropertyChangeListener to the listener list. The listener is 7938 * registered for all bound properties of this class, including the 7939 * following: 7940 * <ul> 7941 * <li>this Component's font ("font")</li> 7942 * <li>this Component's background color ("background")</li> 7943 * <li>this Component's foreground color ("foreground")</li> 7944 * <li>this Component's focusability ("focusable")</li> 7945 * <li>this Component's focus traversal keys enabled state 7946 * ("focusTraversalKeysEnabled")</li> 7947 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 7948 * ("forwardFocusTraversalKeys")</li> 7949 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 7950 * ("backwardFocusTraversalKeys")</li> 7951 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 7952 * ("upCycleFocusTraversalKeys")</li> 7953 * <li>this Component's preferred size ("preferredSize")</li> 7954 * <li>this Component's minimum size ("minimumSize")</li> 7955 * <li>this Component's maximum size ("maximumSize")</li> 7956 * <li>this Component's name ("name")</li> 7957 * </ul> 7958 * Note that if this <code>Component</code> is inheriting a bound property, then no 7959 * event will be fired in response to a change in the inherited property. 7960 * <p> 7961 * If <code>listener</code> is <code>null</code>, 7962 * no exception is thrown and no action is performed. 7963 * 7964 * @param listener the property change listener to be added 7965 * 7966 * @see #removePropertyChangeListener 7967 * @see #getPropertyChangeListeners 7968 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 7969 */ 7970 public void addPropertyChangeListener( 7971 PropertyChangeListener listener) { 7972 synchronized (getObjectLock()) { 7973 if (listener == null) { 7974 return; 7975 } 7976 if (changeSupport == null) { 7977 changeSupport = new PropertyChangeSupport(this); 7978 } 7979 changeSupport.addPropertyChangeListener(listener); 7980 } 7981 } 7982 7983 /** 7984 * Removes a PropertyChangeListener from the listener list. This method 7985 * should be used to remove PropertyChangeListeners that were registered 7986 * for all bound properties of this class. 7987 * <p> 7988 * If listener is null, no exception is thrown and no action is performed. 7989 * 7990 * @param listener the PropertyChangeListener to be removed 7991 * 7992 * @see #addPropertyChangeListener 7993 * @see #getPropertyChangeListeners 7994 * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener) 7995 */ 7996 public void removePropertyChangeListener( 7997 PropertyChangeListener listener) { 7998 synchronized (getObjectLock()) { 7999 if (listener == null || changeSupport == null) { 8000 return; 8001 } 8002 changeSupport.removePropertyChangeListener(listener); 8003 } 8004 } 8005 8006 /** 8007 * Returns an array of all the property change listeners 8008 * registered on this component. 8009 * 8010 * @return all of this component's <code>PropertyChangeListener</code>s 8011 * or an empty array if no property change 8012 * listeners are currently registered 8013 * 8014 * @see #addPropertyChangeListener 8015 * @see #removePropertyChangeListener 8016 * @see #getPropertyChangeListeners(java.lang.String) 8017 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners 8018 * @since 1.4 8019 */ 8020 public PropertyChangeListener[] getPropertyChangeListeners() { 8021 synchronized (getObjectLock()) { 8022 if (changeSupport == null) { 8023 return new PropertyChangeListener[0]; 8024 } 8025 return changeSupport.getPropertyChangeListeners(); 8026 } 8027 } 8028 8029 /** 8030 * Adds a PropertyChangeListener to the listener list for a specific 8031 * property. The specified property may be user-defined, or one of the 8032 * following: 8033 * <ul> 8034 * <li>this Component's font ("font")</li> 8035 * <li>this Component's background color ("background")</li> 8036 * <li>this Component's foreground color ("foreground")</li> 8037 * <li>this Component's focusability ("focusable")</li> 8038 * <li>this Component's focus traversal keys enabled state 8039 * ("focusTraversalKeysEnabled")</li> 8040 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 8041 * ("forwardFocusTraversalKeys")</li> 8042 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 8043 * ("backwardFocusTraversalKeys")</li> 8044 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 8045 * ("upCycleFocusTraversalKeys")</li> 8046 * </ul> 8047 * Note that if this <code>Component</code> is inheriting a bound property, then no 8048 * event will be fired in response to a change in the inherited property. 8049 * <p> 8050 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, 8051 * no exception is thrown and no action is taken. 8052 * 8053 * @param propertyName one of the property names listed above 8054 * @param listener the property change listener to be added 8055 * 8056 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8057 * @see #getPropertyChangeListeners(java.lang.String) 8058 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8059 */ 8060 public void addPropertyChangeListener( 8061 String propertyName, 8062 PropertyChangeListener listener) { 8063 synchronized (getObjectLock()) { 8064 if (listener == null) { 8065 return; 8066 } 8067 if (changeSupport == null) { 8068 changeSupport = new PropertyChangeSupport(this); 8069 } 8070 changeSupport.addPropertyChangeListener(propertyName, listener); 8071 } 8072 } 8073 8074 /** 8075 * Removes a <code>PropertyChangeListener</code> from the listener 8076 * list for a specific property. This method should be used to remove 8077 * <code>PropertyChangeListener</code>s 8078 * that were registered for a specific bound property. 8079 * <p> 8080 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, 8081 * no exception is thrown and no action is taken. 8082 * 8083 * @param propertyName a valid property name 8084 * @param listener the PropertyChangeListener to be removed 8085 * 8086 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8087 * @see #getPropertyChangeListeners(java.lang.String) 8088 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) 8089 */ 8090 public void removePropertyChangeListener( 8091 String propertyName, 8092 PropertyChangeListener listener) { 8093 synchronized (getObjectLock()) { 8094 if (listener == null || changeSupport == null) { 8095 return; 8096 } 8097 changeSupport.removePropertyChangeListener(propertyName, listener); 8098 } 8099 } 8100 8101 /** 8102 * Returns an array of all the listeners which have been associated 8103 * with the named property. 8104 * 8105 * @return all of the <code>PropertyChangeListener</code>s associated with 8106 * the named property; if no such listeners have been added or 8107 * if <code>propertyName</code> is <code>null</code>, an empty 8108 * array is returned 8109 * 8110 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8111 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8112 * @see #getPropertyChangeListeners 8113 * @since 1.4 8114 */ 8115 public PropertyChangeListener[] getPropertyChangeListeners( 8116 String propertyName) { 8117 synchronized (getObjectLock()) { 8118 if (changeSupport == null) { 8119 return new PropertyChangeListener[0]; 8120 } 8121 return changeSupport.getPropertyChangeListeners(propertyName); 8122 } 8123 } 8124 8125 /** 8126 * Support for reporting bound property changes for Object properties. 8127 * This method can be called when a bound property has changed and it will 8128 * send the appropriate PropertyChangeEvent to any registered 8129 * PropertyChangeListeners. 8130 * 8131 * @param propertyName the property whose value has changed 8132 * @param oldValue the property's previous value 8133 * @param newValue the property's new value 8134 */ 8135 protected void firePropertyChange(String propertyName, 8136 Object oldValue, Object newValue) { 8137 PropertyChangeSupport changeSupport; 8138 synchronized (getObjectLock()) { 8139 changeSupport = this.changeSupport; 8140 } 8141 if (changeSupport == null || 8142 (oldValue != null && newValue != null && oldValue.equals(newValue))) { 8143 return; 8144 } 8145 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8146 } 8147 8148 /** 8149 * Support for reporting bound property changes for boolean properties. 8150 * This method can be called when a bound property has changed and it will 8151 * send the appropriate PropertyChangeEvent to any registered 8152 * PropertyChangeListeners. 8153 * 8154 * @param propertyName the property whose value has changed 8155 * @param oldValue the property's previous value 8156 * @param newValue the property's new value 8157 * @since 1.4 8158 */ 8159 protected void firePropertyChange(String propertyName, 8160 boolean oldValue, boolean newValue) { 8161 PropertyChangeSupport changeSupport = this.changeSupport; 8162 if (changeSupport == null || oldValue == newValue) { 8163 return; 8164 } 8165 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8166 } 8167 8168 /** 8169 * Support for reporting bound property changes for integer properties. 8170 * This method can be called when a bound property has changed and it will 8171 * send the appropriate PropertyChangeEvent to any registered 8172 * PropertyChangeListeners. 8173 * 8174 * @param propertyName the property whose value has changed 8175 * @param oldValue the property's previous value 8176 * @param newValue the property's new value 8177 * @since 1.4 8178 */ 8179 protected void firePropertyChange(String propertyName, 8180 int oldValue, int newValue) { 8181 PropertyChangeSupport changeSupport = this.changeSupport; 8182 if (changeSupport == null || oldValue == newValue) { 8183 return; 8184 } 8185 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8186 } 8187 8188 /** 8189 * Reports a bound property change. 8190 * 8191 * @param propertyName the programmatic name of the property 8192 * that was changed 8193 * @param oldValue the old value of the property (as a byte) 8194 * @param newValue the new value of the property (as a byte) 8195 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8196 * java.lang.Object) 8197 * @since 1.5 8198 */ 8199 public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { 8200 if (changeSupport == null || oldValue == newValue) { 8201 return; 8202 } 8203 firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue)); 8204 } 8205 8206 /** 8207 * Reports a bound property change. 8208 * 8209 * @param propertyName the programmatic name of the property 8210 * that was changed 8211 * @param oldValue the old value of the property (as a char) 8212 * @param newValue the new value of the property (as a char) 8213 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8214 * java.lang.Object) 8215 * @since 1.5 8216 */ 8217 public void firePropertyChange(String propertyName, char oldValue, char newValue) { 8218 if (changeSupport == null || oldValue == newValue) { 8219 return; 8220 } 8221 firePropertyChange(propertyName, new Character(oldValue), new Character(newValue)); 8222 } 8223 8224 /** 8225 * Reports a bound property change. 8226 * 8227 * @param propertyName the programmatic name of the property 8228 * that was changed 8229 * @param oldValue the old value of the property (as a short) 8230 * @param newValue the old value of the property (as a short) 8231 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8232 * java.lang.Object) 8233 * @since 1.5 8234 */ 8235 public void firePropertyChange(String propertyName, short oldValue, short newValue) { 8236 if (changeSupport == null || oldValue == newValue) { 8237 return; 8238 } 8239 firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue)); 8240 } 8241 8242 8243 /** 8244 * Reports a bound property change. 8245 * 8246 * @param propertyName the programmatic name of the property 8247 * that was changed 8248 * @param oldValue the old value of the property (as a long) 8249 * @param newValue the new value of the property (as a long) 8250 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8251 * java.lang.Object) 8252 * @since 1.5 8253 */ 8254 public void firePropertyChange(String propertyName, long oldValue, long newValue) { 8255 if (changeSupport == null || oldValue == newValue) { 8256 return; 8257 } 8258 firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue)); 8259 } 8260 8261 /** 8262 * Reports a bound property change. 8263 * 8264 * @param propertyName the programmatic name of the property 8265 * that was changed 8266 * @param oldValue the old value of the property (as a float) 8267 * @param newValue the new value of the property (as a float) 8268 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8269 * java.lang.Object) 8270 * @since 1.5 8271 */ 8272 public void firePropertyChange(String propertyName, float oldValue, float newValue) { 8273 if (changeSupport == null || oldValue == newValue) { 8274 return; 8275 } 8276 firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue)); 8277 } 8278 8279 /** 8280 * Reports a bound property change. 8281 * 8282 * @param propertyName the programmatic name of the property 8283 * that was changed 8284 * @param oldValue the old value of the property (as a double) 8285 * @param newValue the new value of the property (as a double) 8286 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8287 * java.lang.Object) 8288 * @since 1.5 8289 */ 8290 public void firePropertyChange(String propertyName, double oldValue, double newValue) { 8291 if (changeSupport == null || oldValue == newValue) { 8292 return; 8293 } 8294 firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue)); 8295 } 8296 8297 8298 // Serialization support. 8299 8300 /** 8301 * Component Serialized Data Version. 8302 * 8303 * @serial 8304 */ 8305 private int componentSerializedDataVersion = 4; 8306 8307 /** 8308 * This hack is for Swing serialization. It will invoke 8309 * the Swing package private method <code>compWriteObjectNotify</code>. 8310 */ 8311 private void doSwingSerialization() { 8312 Package swingPackage = Package.getPackage("javax.swing"); 8313 // For Swing serialization to correctly work Swing needs to 8314 // be notified before Component does it's serialization. This 8315 // hack accomodates this. 8316 // 8317 // Swing classes MUST be loaded by the bootstrap class loader, 8318 // otherwise we don't consider them. 8319 for (Class klass = Component.this.getClass(); klass != null; 8320 klass = klass.getSuperclass()) { 8321 if (klass.getPackage() == swingPackage && 8322 klass.getClassLoader() == null) { 8323 final Class swingClass = klass; 8324 // Find the first override of the compWriteObjectNotify method 8325 Method[] methods = (Method[])AccessController.doPrivileged( 8326 new PrivilegedAction() { 8327 public Object run() { 8328 return swingClass.getDeclaredMethods(); 8329 } 8330 }); 8331 for (int counter = methods.length - 1; counter >= 0; 8332 counter--) { 8333 final Method method = methods[counter]; 8334 if (method.getName().equals("compWriteObjectNotify")){ 8335 // We found it, use doPrivileged to make it accessible 8336 // to use. 8337 AccessController.doPrivileged(new PrivilegedAction() { 8338 public Object run() { 8339 method.setAccessible(true); 8340 return null; 8341 } 8342 }); 8343 // Invoke the method 8344 try { 8345 method.invoke(this, (Object[]) null); 8346 } catch (IllegalAccessException iae) { 8347 } catch (InvocationTargetException ite) { 8348 } 8349 // We're done, bail. 8350 return; 8351 } 8352 } 8353 } 8354 } 8355 } 8356 8357 /** 8358 * Writes default serializable fields to stream. Writes 8359 * a variety of serializable listeners as optional data. 8360 * The non-serializable listeners are detected and 8361 * no attempt is made to serialize them. 8362 * 8363 * @param s the <code>ObjectOutputStream</code> to write 8364 * @serialData <code>null</code> terminated sequence of 8365 * 0 or more pairs; the pair consists of a <code>String</code> 8366 * and an <code>Object</code>; the <code>String</code> indicates 8367 * the type of object and is one of the following (as of 1.4): 8368 * <code>componentListenerK</code> indicating an 8369 * <code>ComponentListener</code> object; 8370 * <code>focusListenerK</code> indicating an 8371 * <code>FocusListener</code> object; 8372 * <code>keyListenerK</code> indicating an 8373 * <code>KeyListener</code> object; 8374 * <code>mouseListenerK</code> indicating an 8375 * <code>MouseListener</code> object; 8376 * <code>mouseMotionListenerK</code> indicating an 8377 * <code>MouseMotionListener</code> object; 8378 * <code>inputMethodListenerK</code> indicating an 8379 * <code>InputMethodListener</code> object; 8380 * <code>hierarchyListenerK</code> indicating an 8381 * <code>HierarchyListener</code> object; 8382 * <code>hierarchyBoundsListenerK</code> indicating an 8383 * <code>HierarchyBoundsListener</code> object; 8384 * <code>mouseWheelListenerK</code> indicating an 8385 * <code>MouseWheelListener</code> object 8386 * @serialData an optional <code>ComponentOrientation</code> 8387 * (after <code>inputMethodListener</code>, as of 1.2) 8388 * 8389 * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener) 8390 * @see #componentListenerK 8391 * @see #focusListenerK 8392 * @see #keyListenerK 8393 * @see #mouseListenerK 8394 * @see #mouseMotionListenerK 8395 * @see #inputMethodListenerK 8396 * @see #hierarchyListenerK 8397 * @see #hierarchyBoundsListenerK 8398 * @see #mouseWheelListenerK 8399 * @see #readObject(ObjectInputStream) 8400 */ 8401 private void writeObject(ObjectOutputStream s) 8402 throws IOException 8403 { 8404 doSwingSerialization(); 8405 8406 s.defaultWriteObject(); 8407 8408 AWTEventMulticaster.save(s, componentListenerK, componentListener); 8409 AWTEventMulticaster.save(s, focusListenerK, focusListener); 8410 AWTEventMulticaster.save(s, keyListenerK, keyListener); 8411 AWTEventMulticaster.save(s, mouseListenerK, mouseListener); 8412 AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener); 8413 AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener); 8414 8415 s.writeObject(null); 8416 s.writeObject(componentOrientation); 8417 8418 AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener); 8419 AWTEventMulticaster.save(s, hierarchyBoundsListenerK, 8420 hierarchyBoundsListener); 8421 s.writeObject(null); 8422 8423 AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener); 8424 s.writeObject(null); 8425 8426 } 8427 8428 /** 8429 * Reads the <code>ObjectInputStream</code> and if it isn't 8430 * <code>null</code> adds a listener to receive a variety 8431 * of events fired by the component. 8432 * Unrecognized keys or values will be ignored. 8433 * 8434 * @param s the <code>ObjectInputStream</code> to read 8435 * @see #writeObject(ObjectOutputStream) 8436 */ 8437 private void readObject(ObjectInputStream s) 8438 throws ClassNotFoundException, IOException 8439 { 8440 objectLock = new Object(); 8441 8442 s.defaultReadObject(); 8443 8444 appContext = AppContext.getAppContext(); 8445 coalescingEnabled = checkCoalescing(); 8446 if (componentSerializedDataVersion < 4) { 8447 // These fields are non-transient and rely on default 8448 // serialization. However, the default values are insufficient, 8449 // so we need to set them explicitly for object data streams prior 8450 // to 1.4. 8451 focusable = true; 8452 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; 8453 initializeFocusTraversalKeys(); 8454 focusTraversalKeysEnabled = true; 8455 } 8456 8457 Object keyOrNull; 8458 while(null != (keyOrNull = s.readObject())) { 8459 String key = ((String)keyOrNull).intern(); 8460 8461 if (componentListenerK == key) 8462 addComponentListener((ComponentListener)(s.readObject())); 8463 8464 else if (focusListenerK == key) 8465 addFocusListener((FocusListener)(s.readObject())); 8466 8467 else if (keyListenerK == key) 8468 addKeyListener((KeyListener)(s.readObject())); 8469 8470 else if (mouseListenerK == key) 8471 addMouseListener((MouseListener)(s.readObject())); 8472 8473 else if (mouseMotionListenerK == key) 8474 addMouseMotionListener((MouseMotionListener)(s.readObject())); 8475 8476 else if (inputMethodListenerK == key) 8477 addInputMethodListener((InputMethodListener)(s.readObject())); 8478 8479 else // skip value for unrecognized key 8480 s.readObject(); 8481 8482 } 8483 8484 // Read the component's orientation if it's present 8485 Object orient = null; 8486 8487 try { 8488 orient = s.readObject(); 8489 } catch (java.io.OptionalDataException e) { 8490 // JDK 1.1 instances will not have this optional data. 8491 // e.eof will be true to indicate that there is no more 8492 // data available for this object. 8493 // If e.eof is not true, throw the exception as it 8494 // might have been caused by reasons unrelated to 8495 // componentOrientation. 8496 8497 if (!e.eof) { 8498 throw (e); 8499 } 8500 } 8501 8502 if (orient != null) { 8503 componentOrientation = (ComponentOrientation)orient; 8504 } else { 8505 componentOrientation = ComponentOrientation.UNKNOWN; 8506 } 8507 8508 try { 8509 while(null != (keyOrNull = s.readObject())) { 8510 String key = ((String)keyOrNull).intern(); 8511 8512 if (hierarchyListenerK == key) { 8513 addHierarchyListener((HierarchyListener)(s.readObject())); 8514 } 8515 else if (hierarchyBoundsListenerK == key) { 8516 addHierarchyBoundsListener((HierarchyBoundsListener) 8517 (s.readObject())); 8518 } 8519 else { 8520 // skip value for unrecognized key 8521 s.readObject(); 8522 } 8523 } 8524 } catch (java.io.OptionalDataException e) { 8525 // JDK 1.1/1.2 instances will not have this optional data. 8526 // e.eof will be true to indicate that there is no more 8527 // data available for this object. 8528 // If e.eof is not true, throw the exception as it 8529 // might have been caused by reasons unrelated to 8530 // hierarchy and hierarchyBounds listeners. 8531 8532 if (!e.eof) { 8533 throw (e); 8534 } 8535 } 8536 8537 try { 8538 while (null != (keyOrNull = s.readObject())) { 8539 String key = ((String)keyOrNull).intern(); 8540 8541 if (mouseWheelListenerK == key) { 8542 addMouseWheelListener((MouseWheelListener)(s.readObject())); 8543 } 8544 else { 8545 // skip value for unrecognized key 8546 s.readObject(); 8547 } 8548 } 8549 } catch (java.io.OptionalDataException e) { 8550 // pre-1.3 instances will not have this optional data. 8551 // e.eof will be true to indicate that there is no more 8552 // data available for this object. 8553 // If e.eof is not true, throw the exception as it 8554 // might have been caused by reasons unrelated to 8555 // mouse wheel listeners 8556 8557 if (!e.eof) { 8558 throw (e); 8559 } 8560 } 8561 8562 if (popups != null) { 8563 int npopups = popups.size(); 8564 for (int i = 0 ; i < npopups ; i++) { 8565 PopupMenu popup = (PopupMenu)popups.elementAt(i); 8566 popup.parent = this; 8567 } 8568 } 8569 } 8570 8571 /** 8572 * Sets the language-sensitive orientation that is to be used to order 8573 * the elements or text within this component. Language-sensitive 8574 * <code>LayoutManager</code> and <code>Component</code> 8575 * subclasses will use this property to 8576 * determine how to lay out and draw components. 8577 * <p> 8578 * At construction time, a component's orientation is set to 8579 * <code>ComponentOrientation.UNKNOWN</code>, 8580 * indicating that it has not been specified 8581 * explicitly. The UNKNOWN orientation behaves the same as 8582 * <code>ComponentOrientation.LEFT_TO_RIGHT</code>. 8583 * <p> 8584 * To set the orientation of a single component, use this method. 8585 * To set the orientation of an entire component 8586 * hierarchy, use 8587 * {@link #applyComponentOrientation applyComponentOrientation}. 8588 * 8589 * @see ComponentOrientation 8590 * 8591 * @author Laura Werner, IBM 8592 * @beaninfo 8593 * bound: true 8594 */ 8595 public void setComponentOrientation(ComponentOrientation o) { 8596 ComponentOrientation oldValue = componentOrientation; 8597 componentOrientation = o; 8598 8599 // This is a bound property, so report the change to 8600 // any registered listeners. (Cheap if there are none.) 8601 firePropertyChange("componentOrientation", oldValue, o); 8602 8603 // This could change the preferred size of the Component. 8604 invalidateIfValid(); 8605 } 8606 8607 /** 8608 * Retrieves the language-sensitive orientation that is to be used to order 8609 * the elements or text within this component. <code>LayoutManager</code> 8610 * and <code>Component</code> 8611 * subclasses that wish to respect orientation should call this method to 8612 * get the component's orientation before performing layout or drawing. 8613 * 8614 * @see ComponentOrientation 8615 * 8616 * @author Laura Werner, IBM 8617 */ 8618 public ComponentOrientation getComponentOrientation() { 8619 return componentOrientation; 8620 } 8621 8622 /** 8623 * Sets the <code>ComponentOrientation</code> property of this component 8624 * and all components contained within it. 8625 * 8626 * @param orientation the new component orientation of this component and 8627 * the components contained within it. 8628 * @exception NullPointerException if <code>orientation</code> is null. 8629 * @see #setComponentOrientation 8630 * @see #getComponentOrientation 8631 * @since 1.4 8632 */ 8633 public void applyComponentOrientation(ComponentOrientation orientation) { 8634 if (orientation == null) { 8635 throw new NullPointerException(); 8636 } 8637 setComponentOrientation(orientation); 8638 } 8639 8640 final boolean canBeFocusOwner() { 8641 // It is enabled, visible, focusable. 8642 if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) { 8643 return true; 8644 } 8645 return false; 8646 } 8647 8648 /** 8649 * Checks that this component meets the prerequesites to be focus owner: 8650 * - it is enabled, visible, focusable 8651 * - it's parents are all enabled and showing 8652 * - top-level window is focusable 8653 * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts 8654 * this component as focus owner 8655 * @since 1.5 8656 */ 8657 final boolean canBeFocusOwnerRecursively() { 8658 // - it is enabled, visible, focusable 8659 if (!canBeFocusOwner()) { 8660 return false; 8661 } 8662 8663 // - it's parents are all enabled and showing 8664 synchronized(getTreeLock()) { 8665 if (parent != null) { 8666 return parent.canContainFocusOwner(this); 8667 } 8668 } 8669 return true; 8670 } 8671 8672 /** 8673 * Fix the location of the HW component in a LW container hierarchy. 8674 */ 8675 final void relocateComponent() { 8676 synchronized (getTreeLock()) { 8677 if (peer == null) { 8678 return; 8679 } 8680 int nativeX = x; 8681 int nativeY = y; 8682 for (Component cont = getContainer(); 8683 cont != null && cont.isLightweight(); 8684 cont = cont.getContainer()) 8685 { 8686 nativeX += cont.x; 8687 nativeY += cont.y; 8688 } 8689 peer.setBounds(nativeX, nativeY, width, height, 8690 ComponentPeer.SET_LOCATION); 8691 } 8692 } 8693 8694 /** 8695 * Returns the <code>Window</code> ancestor of the component. 8696 * @return Window ancestor of the component or component by itself if it is Window; 8697 * null, if component is not a part of window hierarchy 8698 */ 8699 Window getContainingWindow() { 8700 return SunToolkit.getContainingWindow(this); 8701 } 8702 8703 /** 8704 * Initialize JNI field and method IDs 8705 */ 8706 private static native void initIDs(); 8707 8708 /* 8709 * --- Accessibility Support --- 8710 * 8711 * Component will contain all of the methods in interface Accessible, 8712 * though it won't actually implement the interface - that will be up 8713 * to the individual objects which extend Component. 8714 */ 8715 8716 AccessibleContext accessibleContext = null; 8717 8718 /** 8719 * Gets the <code>AccessibleContext</code> associated 8720 * with this <code>Component</code>. 8721 * The method implemented by this base 8722 * class returns null. Classes that extend <code>Component</code> 8723 * should implement this method to return the 8724 * <code>AccessibleContext</code> associated with the subclass. 8725 * 8726 * 8727 * @return the <code>AccessibleContext</code> of this 8728 * <code>Component</code> 8729 * @since 1.3 8730 */ 8731 public AccessibleContext getAccessibleContext() { 8732 return accessibleContext; 8733 } 8734 8735 /** 8736 * Inner class of Component used to provide default support for 8737 * accessibility. This class is not meant to be used directly by 8738 * application developers, but is instead meant only to be 8739 * subclassed by component developers. 8740 * <p> 8741 * The class used to obtain the accessible role for this object. 8742 * @since 1.3 8743 */ 8744 protected abstract class AccessibleAWTComponent extends AccessibleContext 8745 implements Serializable, AccessibleComponent { 8746 8747 private static final long serialVersionUID = 642321655757800191L; 8748 8749 /** 8750 * Though the class is abstract, this should be called by 8751 * all sub-classes. 8752 */ 8753 protected AccessibleAWTComponent() { 8754 } 8755 8756 protected ComponentListener accessibleAWTComponentHandler = null; 8757 protected FocusListener accessibleAWTFocusHandler = null; 8758 8759 /** 8760 * Fire PropertyChange listener, if one is registered, 8761 * when shown/hidden.. 8762 * @since 1.3 8763 */ 8764 protected class AccessibleAWTComponentHandler implements ComponentListener { 8765 public void componentHidden(ComponentEvent e) { 8766 if (accessibleContext != null) { 8767 accessibleContext.firePropertyChange( 8768 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 8769 AccessibleState.VISIBLE, null); 8770 } 8771 } 8772 8773 public void componentShown(ComponentEvent e) { 8774 if (accessibleContext != null) { 8775 accessibleContext.firePropertyChange( 8776 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 8777 null, AccessibleState.VISIBLE); 8778 } 8779 } 8780 8781 public void componentMoved(ComponentEvent e) { 8782 } 8783 8784 public void componentResized(ComponentEvent e) { 8785 } 8786 } // inner class AccessibleAWTComponentHandler 8787 8788 8789 /** 8790 * Fire PropertyChange listener, if one is registered, 8791 * when focus events happen 8792 * @since 1.3 8793 */ 8794 protected class AccessibleAWTFocusHandler implements FocusListener { 8795 public void focusGained(FocusEvent event) { 8796 if (accessibleContext != null) { 8797 accessibleContext.firePropertyChange( 8798 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 8799 null, AccessibleState.FOCUSED); 8800 } 8801 } 8802 public void focusLost(FocusEvent event) { 8803 if (accessibleContext != null) { 8804 accessibleContext.firePropertyChange( 8805 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 8806 AccessibleState.FOCUSED, null); 8807 } 8808 } 8809 } // inner class AccessibleAWTFocusHandler 8810 8811 8812 /** 8813 * Adds a <code>PropertyChangeListener</code> to the listener list. 8814 * 8815 * @param listener the property change listener to be added 8816 */ 8817 public void addPropertyChangeListener(PropertyChangeListener listener) { 8818 if (accessibleAWTComponentHandler == null) { 8819 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler(); 8820 Component.this.addComponentListener(accessibleAWTComponentHandler); 8821 } 8822 if (accessibleAWTFocusHandler == null) { 8823 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler(); 8824 Component.this.addFocusListener(accessibleAWTFocusHandler); 8825 } 8826 super.addPropertyChangeListener(listener); 8827 } 8828 8829 /** 8830 * Remove a PropertyChangeListener from the listener list. 8831 * This removes a PropertyChangeListener that was registered 8832 * for all properties. 8833 * 8834 * @param listener The PropertyChangeListener to be removed 8835 */ 8836 public void removePropertyChangeListener(PropertyChangeListener listener) { 8837 if (accessibleAWTComponentHandler != null) { 8838 Component.this.removeComponentListener(accessibleAWTComponentHandler); 8839 accessibleAWTComponentHandler = null; 8840 } 8841 if (accessibleAWTFocusHandler != null) { 8842 Component.this.removeFocusListener(accessibleAWTFocusHandler); 8843 accessibleAWTFocusHandler = null; 8844 } 8845 super.removePropertyChangeListener(listener); 8846 } 8847 8848 // AccessibleContext methods 8849 // 8850 /** 8851 * Gets the accessible name of this object. This should almost never 8852 * return <code>java.awt.Component.getName()</code>, 8853 * as that generally isn't a localized name, 8854 * and doesn't have meaning for the user. If the 8855 * object is fundamentally a text object (e.g. a menu item), the 8856 * accessible name should be the text of the object (e.g. "save"). 8857 * If the object has a tooltip, the tooltip text may also be an 8858 * appropriate String to return. 8859 * 8860 * @return the localized name of the object -- can be 8861 * <code>null</code> if this 8862 * object does not have a name 8863 * @see javax.accessibility.AccessibleContext#setAccessibleName 8864 */ 8865 public String getAccessibleName() { 8866 return accessibleName; 8867 } 8868 8869 /** 8870 * Gets the accessible description of this object. This should be 8871 * a concise, localized description of what this object is - what 8872 * is its meaning to the user. If the object has a tooltip, the 8873 * tooltip text may be an appropriate string to return, assuming 8874 * it contains a concise description of the object (instead of just 8875 * the name of the object - e.g. a "Save" icon on a toolbar that 8876 * had "save" as the tooltip text shouldn't return the tooltip 8877 * text as the description, but something like "Saves the current 8878 * text document" instead). 8879 * 8880 * @return the localized description of the object -- can be 8881 * <code>null</code> if this object does not have a description 8882 * @see javax.accessibility.AccessibleContext#setAccessibleDescription 8883 */ 8884 public String getAccessibleDescription() { 8885 return accessibleDescription; 8886 } 8887 8888 /** 8889 * Gets the role of this object. 8890 * 8891 * @return an instance of <code>AccessibleRole</code> 8892 * describing the role of the object 8893 * @see javax.accessibility.AccessibleRole 8894 */ 8895 public AccessibleRole getAccessibleRole() { 8896 return AccessibleRole.AWT_COMPONENT; 8897 } 8898 8899 /** 8900 * Gets the state of this object. 8901 * 8902 * @return an instance of <code>AccessibleStateSet</code> 8903 * containing the current state set of the object 8904 * @see javax.accessibility.AccessibleState 8905 */ 8906 public AccessibleStateSet getAccessibleStateSet() { 8907 return Component.this.getAccessibleStateSet(); 8908 } 8909 8910 /** 8911 * Gets the <code>Accessible</code> parent of this object. 8912 * If the parent of this object implements <code>Accessible</code>, 8913 * this method should simply return <code>getParent</code>. 8914 * 8915 * @return the <code>Accessible</code> parent of this 8916 * object -- can be <code>null</code> if this 8917 * object does not have an <code>Accessible</code> parent 8918 */ 8919 public Accessible getAccessibleParent() { 8920 if (accessibleParent != null) { 8921 return accessibleParent; 8922 } else { 8923 Container parent = getParent(); 8924 if (parent instanceof Accessible) { 8925 return (Accessible) parent; 8926 } 8927 } 8928 return null; 8929 } 8930 8931 /** 8932 * Gets the index of this object in its accessible parent. 8933 * 8934 * @return the index of this object in its parent; or -1 if this 8935 * object does not have an accessible parent 8936 * @see #getAccessibleParent 8937 */ 8938 public int getAccessibleIndexInParent() { 8939 return Component.this.getAccessibleIndexInParent(); 8940 } 8941 8942 /** 8943 * Returns the number of accessible children in the object. If all 8944 * of the children of this object implement <code>Accessible</code>, 8945 * then this method should return the number of children of this object. 8946 * 8947 * @return the number of accessible children in the object 8948 */ 8949 public int getAccessibleChildrenCount() { 8950 return 0; // Components don't have children 8951 } 8952 8953 /** 8954 * Returns the nth <code>Accessible</code> child of the object. 8955 * 8956 * @param i zero-based index of child 8957 * @return the nth <code>Accessible</code> child of the object 8958 */ 8959 public Accessible getAccessibleChild(int i) { 8960 return null; // Components don't have children 8961 } 8962 8963 /** 8964 * Returns the locale of this object. 8965 * 8966 * @return the locale of this object 8967 */ 8968 public Locale getLocale() { 8969 return Component.this.getLocale(); 8970 } 8971 8972 /** 8973 * Gets the <code>AccessibleComponent</code> associated 8974 * with this object if one exists. 8975 * Otherwise return <code>null</code>. 8976 * 8977 * @return the component 8978 */ 8979 public AccessibleComponent getAccessibleComponent() { 8980 return this; 8981 } 8982 8983 8984 // AccessibleComponent methods 8985 // 8986 /** 8987 * Gets the background color of this object. 8988 * 8989 * @return the background color, if supported, of the object; 8990 * otherwise, <code>null</code> 8991 */ 8992 public Color getBackground() { 8993 return Component.this.getBackground(); 8994 } 8995 8996 /** 8997 * Sets the background color of this object. 8998 * (For transparency, see <code>isOpaque</code>.) 8999 * 9000 * @param c the new <code>Color</code> for the background 9001 * @see Component#isOpaque 9002 */ 9003 public void setBackground(Color c) { 9004 Component.this.setBackground(c); 9005 } 9006 9007 /** 9008 * Gets the foreground color of this object. 9009 * 9010 * @return the foreground color, if supported, of the object; 9011 * otherwise, <code>null</code> 9012 */ 9013 public Color getForeground() { 9014 return Component.this.getForeground(); 9015 } 9016 9017 /** 9018 * Sets the foreground color of this object. 9019 * 9020 * @param c the new <code>Color</code> for the foreground 9021 */ 9022 public void setForeground(Color c) { 9023 Component.this.setForeground(c); 9024 } 9025 9026 /** 9027 * Gets the <code>Cursor</code> of this object. 9028 * 9029 * @return the <code>Cursor</code>, if supported, 9030 * of the object; otherwise, <code>null</code> 9031 */ 9032 public Cursor getCursor() { 9033 return Component.this.getCursor(); 9034 } 9035 9036 /** 9037 * Sets the <code>Cursor</code> of this object. 9038 * <p> 9039 * The method may have no visual effect if the Java platform 9040 * implementation and/or the native system do not support 9041 * changing the mouse cursor shape. 9042 * @param cursor the new <code>Cursor</code> for the object 9043 */ 9044 public void setCursor(Cursor cursor) { 9045 Component.this.setCursor(cursor); 9046 } 9047 9048 /** 9049 * Gets the <code>Font</code> of this object. 9050 * 9051 * @return the <code>Font</code>, if supported, 9052 * for the object; otherwise, <code>null</code> 9053 */ 9054 public Font getFont() { 9055 return Component.this.getFont(); 9056 } 9057 9058 /** 9059 * Sets the <code>Font</code> of this object. 9060 * 9061 * @param f the new <code>Font</code> for the object 9062 */ 9063 public void setFont(Font f) { 9064 Component.this.setFont(f); 9065 } 9066 9067 /** 9068 * Gets the <code>FontMetrics</code> of this object. 9069 * 9070 * @param f the <code>Font</code> 9071 * @return the <code>FontMetrics</code>, if supported, 9072 * the object; otherwise, <code>null</code> 9073 * @see #getFont 9074 */ 9075 public FontMetrics getFontMetrics(Font f) { 9076 if (f == null) { 9077 return null; 9078 } else { 9079 return Component.this.getFontMetrics(f); 9080 } 9081 } 9082 9083 /** 9084 * Determines if the object is enabled. 9085 * 9086 * @return true if object is enabled; otherwise, false 9087 */ 9088 public boolean isEnabled() { 9089 return Component.this.isEnabled(); 9090 } 9091 9092 /** 9093 * Sets the enabled state of the object. 9094 * 9095 * @param b if true, enables this object; otherwise, disables it 9096 */ 9097 public void setEnabled(boolean b) { 9098 boolean old = Component.this.isEnabled(); 9099 Component.this.setEnabled(b); 9100 if (b != old) { 9101 if (accessibleContext != null) { 9102 if (b) { 9103 accessibleContext.firePropertyChange( 9104 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9105 null, AccessibleState.ENABLED); 9106 } else { 9107 accessibleContext.firePropertyChange( 9108 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9109 AccessibleState.ENABLED, null); 9110 } 9111 } 9112 } 9113 } 9114 9115 /** 9116 * Determines if the object is visible. Note: this means that the 9117 * object intends to be visible; however, it may not in fact be 9118 * showing on the screen because one of the objects that this object 9119 * is contained by is not visible. To determine if an object is 9120 * showing on the screen, use <code>isShowing</code>. 9121 * 9122 * @return true if object is visible; otherwise, false 9123 */ 9124 public boolean isVisible() { 9125 return Component.this.isVisible(); 9126 } 9127 9128 /** 9129 * Sets the visible state of the object. 9130 * 9131 * @param b if true, shows this object; otherwise, hides it 9132 */ 9133 public void setVisible(boolean b) { 9134 boolean old = Component.this.isVisible(); 9135 Component.this.setVisible(b); 9136 if (b != old) { 9137 if (accessibleContext != null) { 9138 if (b) { 9139 accessibleContext.firePropertyChange( 9140 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9141 null, AccessibleState.VISIBLE); 9142 } else { 9143 accessibleContext.firePropertyChange( 9144 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9145 AccessibleState.VISIBLE, null); 9146 } 9147 } 9148 } 9149 } 9150 9151 /** 9152 * Determines if the object is showing. This is determined by checking 9153 * the visibility of the object and ancestors of the object. Note: 9154 * this will return true even if the object is obscured by another 9155 * (for example, it happens to be underneath a menu that was pulled 9156 * down). 9157 * 9158 * @return true if object is showing; otherwise, false 9159 */ 9160 public boolean isShowing() { 9161 return Component.this.isShowing(); 9162 } 9163 9164 /** 9165 * Checks whether the specified point is within this object's bounds, 9166 * where the point's x and y coordinates are defined to be relative to 9167 * the coordinate system of the object. 9168 * 9169 * @param p the <code>Point</code> relative to the 9170 * coordinate system of the object 9171 * @return true if object contains <code>Point</code>; otherwise false 9172 */ 9173 public boolean contains(Point p) { 9174 return Component.this.contains(p); 9175 } 9176 9177 /** 9178 * Returns the location of the object on the screen. 9179 * 9180 * @return location of object on screen -- can be 9181 * <code>null</code> if this object is not on the screen 9182 */ 9183 public Point getLocationOnScreen() { 9184 synchronized (Component.this.getTreeLock()) { 9185 if (Component.this.isShowing()) { 9186 return Component.this.getLocationOnScreen(); 9187 } else { 9188 return null; 9189 } 9190 } 9191 } 9192 9193 /** 9194 * Gets the location of the object relative to the parent in the form 9195 * of a point specifying the object's top-left corner in the screen's 9196 * coordinate space. 9197 * 9198 * @return an instance of Point representing the top-left corner of 9199 * the object's bounds in the coordinate space of the screen; 9200 * <code>null</code> if this object or its parent are not on the screen 9201 */ 9202 public Point getLocation() { 9203 return Component.this.getLocation(); 9204 } 9205 9206 /** 9207 * Sets the location of the object relative to the parent. 9208 * @param p the coordinates of the object 9209 */ 9210 public void setLocation(Point p) { 9211 Component.this.setLocation(p); 9212 } 9213 9214 /** 9215 * Gets the bounds of this object in the form of a Rectangle object. 9216 * The bounds specify this object's width, height, and location 9217 * relative to its parent. 9218 * 9219 * @return a rectangle indicating this component's bounds; 9220 * <code>null</code> if this object is not on the screen 9221 */ 9222 public Rectangle getBounds() { 9223 return Component.this.getBounds(); 9224 } 9225 9226 /** 9227 * Sets the bounds of this object in the form of a 9228 * <code>Rectangle</code> object. 9229 * The bounds specify this object's width, height, and location 9230 * relative to its parent. 9231 * 9232 * @param r a rectangle indicating this component's bounds 9233 */ 9234 public void setBounds(Rectangle r) { 9235 Component.this.setBounds(r); 9236 } 9237 9238 /** 9239 * Returns the size of this object in the form of a 9240 * <code>Dimension</code> object. The height field of the 9241 * <code>Dimension</code> object contains this objects's 9242 * height, and the width field of the <code>Dimension</code> 9243 * object contains this object's width. 9244 * 9245 * @return a <code>Dimension</code> object that indicates 9246 * the size of this component; <code>null</code> if 9247 * this object is not on the screen 9248 */ 9249 public Dimension getSize() { 9250 return Component.this.getSize(); 9251 } 9252 9253 /** 9254 * Resizes this object so that it has width and height. 9255 * 9256 * @param d - the dimension specifying the new size of the object 9257 */ 9258 public void setSize(Dimension d) { 9259 Component.this.setSize(d); 9260 } 9261 9262 /** 9263 * Returns the <code>Accessible</code> child, 9264 * if one exists, contained at the local 9265 * coordinate <code>Point</code>. Otherwise returns 9266 * <code>null</code>. 9267 * 9268 * @param p the point defining the top-left corner of 9269 * the <code>Accessible</code>, given in the 9270 * coordinate space of the object's parent 9271 * @return the <code>Accessible</code>, if it exists, 9272 * at the specified location; else <code>null</code> 9273 */ 9274 public Accessible getAccessibleAt(Point p) { 9275 return null; // Components don't have children 9276 } 9277 9278 /** 9279 * Returns whether this object can accept focus or not. 9280 * 9281 * @return true if object can accept focus; otherwise false 9282 */ 9283 public boolean isFocusTraversable() { 9284 return Component.this.isFocusTraversable(); 9285 } 9286 9287 /** 9288 * Requests focus for this object. 9289 */ 9290 public void requestFocus() { 9291 Component.this.requestFocus(); 9292 } 9293 9294 /** 9295 * Adds the specified focus listener to receive focus events from this 9296 * component. 9297 * 9298 * @param l the focus listener 9299 */ 9300 public void addFocusListener(FocusListener l) { 9301 Component.this.addFocusListener(l); 9302 } 9303 9304 /** 9305 * Removes the specified focus listener so it no longer receives focus 9306 * events from this component. 9307 * 9308 * @param l the focus listener 9309 */ 9310 public void removeFocusListener(FocusListener l) { 9311 Component.this.removeFocusListener(l); 9312 } 9313 9314 } // inner class AccessibleAWTComponent 9315 9316 9317 /** 9318 * Gets the index of this object in its accessible parent. 9319 * If this object does not have an accessible parent, returns 9320 * -1. 9321 * 9322 * @return the index of this object in its accessible parent 9323 */ 9324 int getAccessibleIndexInParent() { 9325 synchronized (getTreeLock()) { 9326 int index = -1; 9327 Container parent = this.getParent(); 9328 if (parent != null && parent instanceof Accessible) { 9329 Component ca[] = parent.getComponents(); 9330 for (int i = 0; i < ca.length; i++) { 9331 if (ca[i] instanceof Accessible) { 9332 index++; 9333 } 9334 if (this.equals(ca[i])) { 9335 return index; 9336 } 9337 } 9338 } 9339 return -1; 9340 } 9341 } 9342 9343 /** 9344 * Gets the current state set of this object. 9345 * 9346 * @return an instance of <code>AccessibleStateSet</code> 9347 * containing the current state set of the object 9348 * @see AccessibleState 9349 */ 9350 AccessibleStateSet getAccessibleStateSet() { 9351 synchronized (getTreeLock()) { 9352 AccessibleStateSet states = new AccessibleStateSet(); 9353 if (this.isEnabled()) { 9354 states.add(AccessibleState.ENABLED); 9355 } 9356 if (this.isFocusTraversable()) { 9357 states.add(AccessibleState.FOCUSABLE); 9358 } 9359 if (this.isVisible()) { 9360 states.add(AccessibleState.VISIBLE); 9361 } 9362 if (this.isShowing()) { 9363 states.add(AccessibleState.SHOWING); 9364 } 9365 if (this.isFocusOwner()) { 9366 states.add(AccessibleState.FOCUSED); 9367 } 9368 if (this instanceof Accessible) { 9369 AccessibleContext ac = ((Accessible) this).getAccessibleContext(); 9370 if (ac != null) { 9371 Accessible ap = ac.getAccessibleParent(); 9372 if (ap != null) { 9373 AccessibleContext pac = ap.getAccessibleContext(); 9374 if (pac != null) { 9375 AccessibleSelection as = pac.getAccessibleSelection(); 9376 if (as != null) { 9377 states.add(AccessibleState.SELECTABLE); 9378 int i = ac.getAccessibleIndexInParent(); 9379 if (i >= 0) { 9380 if (as.isAccessibleChildSelected(i)) { 9381 states.add(AccessibleState.SELECTED); 9382 } 9383 } 9384 } 9385 } 9386 } 9387 } 9388 } 9389 if (Component.isInstanceOf(this, "javax.swing.JComponent")) { 9390 if (((javax.swing.JComponent) this).isOpaque()) { 9391 states.add(AccessibleState.OPAQUE); 9392 } 9393 } 9394 return states; 9395 } 9396 } 9397 9398 /** 9399 * Checks that the given object is instance of the given class. 9400 * @param obj Object to be checked 9401 * @param className The name of the class. Must be fully-qualified class name. 9402 * @return true, if this object is instanceof given class, 9403 * false, otherwise, or if obj or className is null 9404 */ 9405 static boolean isInstanceOf(Object obj, String className) { 9406 if (obj == null) return false; 9407 if (className == null) return false; 9408 9409 Class cls = obj.getClass(); 9410 while (cls != null) { 9411 if (cls.getName().equals(className)) { 9412 return true; 9413 } 9414 cls = cls.getSuperclass(); 9415 } 9416 return false; 9417 } 9418 9419 9420 // ************************** MIXING CODE ******************************* 9421 9422 /** 9423 * Check whether we can trust the current bounds of the component. 9424 * The return value of false indicates that the container of the 9425 * component is invalid, and therefore needs to be layed out, which would 9426 * probably mean changing the bounds of its children. 9427 * Null-layout of the container or absence of the container mean 9428 * the bounds of the component are final and can be trusted. 9429 */ 9430 final boolean areBoundsValid() { 9431 Container cont = getContainer(); 9432 return cont == null || cont.isValid() || cont.getLayout() == null; 9433 } 9434 9435 /** 9436 * Applies the shape to the component 9437 * @param shape Shape to be applied to the component 9438 */ 9439 void applyCompoundShape(Region shape) { 9440 checkTreeLock(); 9441 9442 if (!areBoundsValid()) { 9443 if (mixingLog.isLoggable(Level.FINE)) { 9444 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 9445 } 9446 return; 9447 } 9448 9449 if (!isLightweight()) { 9450 ComponentPeer peer = getPeer(); 9451 if (peer != null) { 9452 // The Region class has some optimizations. That's why 9453 // we should manually check whether it's empty and 9454 // substitute the object ourselves. Otherwise we end up 9455 // with some incorrect Region object with loX being 9456 // greater than the hiX for instance. 9457 if (shape.isEmpty()) { 9458 shape = Region.EMPTY_REGION; 9459 } 9460 9461 9462 // Note: the shape is not really copied/cloned. We create 9463 // the Region object ourselves, so there's no any possibility 9464 // to modify the object outside of the mixing code. 9465 // Nullifying compoundShape means that the component has normal shape 9466 // (or has no shape at all). 9467 if (shape.equals(getNormalShape())) { 9468 if (this.compoundShape == null) { 9469 return; 9470 } 9471 this.compoundShape = null; 9472 peer.applyShape(null); 9473 } else { 9474 if (shape.equals(getAppliedShape())) { 9475 return; 9476 } 9477 this.compoundShape = shape; 9478 Point compAbsolute = getLocationOnWindow(); 9479 if (mixingLog.isLoggable(Level.FINER)) { 9480 mixingLog.fine("this = " + this + 9481 "; compAbsolute=" + compAbsolute + "; shape=" + shape); 9482 } 9483 peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y)); 9484 } 9485 } 9486 } 9487 } 9488 9489 /** 9490 * Returns the shape previously set with applyCompoundShape(). 9491 * If the component is LW or no shape was applied yet, 9492 * the method returns the normal shape. 9493 */ 9494 private Region getAppliedShape() { 9495 checkTreeLock(); 9496 //XXX: if we allow LW components to have a shape, this must be changed 9497 return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape; 9498 } 9499 9500 Point getLocationOnWindow() { 9501 checkTreeLock(); 9502 Point curLocation = getLocation(); 9503 9504 for (Container parent = getContainer(); 9505 parent != null && !(parent instanceof Window); 9506 parent = parent.getContainer()) 9507 { 9508 curLocation.x += parent.getX(); 9509 curLocation.y += parent.getY(); 9510 } 9511 9512 return curLocation; 9513 } 9514 9515 /** 9516 * Returns the full shape of the component located in window coordinates 9517 */ 9518 final Region getNormalShape() { 9519 checkTreeLock(); 9520 //XXX: we may take into account a user-specified shape for this component 9521 Point compAbsolute = getLocationOnWindow(); 9522 return 9523 Region.getInstanceXYWH( 9524 compAbsolute.x, 9525 compAbsolute.y, 9526 getWidth(), 9527 getHeight() 9528 ); 9529 } 9530 9531 /** 9532 * Returns the "opaque shape" of the component. 9533 * 9534 * The opaque shape of a lightweight components is the actual shape that 9535 * needs to be cut off of the heavyweight components in order to mix this 9536 * lightweight component correctly with them. 9537 * 9538 * The method is overriden in the java.awt.Container to handle non-opaque 9539 * containers containing opaque children. 9540 * 9541 * See 6637655 for details. 9542 */ 9543 Region getOpaqueShape() { 9544 checkTreeLock(); 9545 if (mixingCutoutRegion != null) { 9546 return mixingCutoutRegion; 9547 } else { 9548 return getNormalShape(); 9549 } 9550 } 9551 9552 final int getSiblingIndexAbove() { 9553 checkTreeLock(); 9554 Container parent = getContainer(); 9555 if (parent == null) { 9556 return -1; 9557 } 9558 9559 int nextAbove = parent.getComponentZOrder(this) - 1; 9560 9561 return nextAbove < 0 ? -1 : nextAbove; 9562 } 9563 9564 final ComponentPeer getHWPeerAboveMe() { 9565 checkTreeLock(); 9566 9567 Container cont = getContainer(); 9568 int indexAbove = getSiblingIndexAbove(); 9569 9570 while (cont != null) { 9571 for (int i = indexAbove; i > -1; i--) { 9572 Component comp = cont.getComponent(i); 9573 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) { 9574 return comp.getPeer(); 9575 } 9576 } 9577 9578 indexAbove = cont.getSiblingIndexAbove(); 9579 cont = cont.getContainer(); 9580 } 9581 9582 return null; 9583 } 9584 9585 final int getSiblingIndexBelow() { 9586 checkTreeLock(); 9587 Container parent = getContainer(); 9588 if (parent == null) { 9589 return -1; 9590 } 9591 9592 int nextBelow = parent.getComponentZOrder(this) + 1; 9593 9594 return nextBelow >= parent.getComponentCount() ? -1 : nextBelow; 9595 } 9596 9597 final boolean isNonOpaqueForMixing() { 9598 return mixingCutoutRegion != null && 9599 mixingCutoutRegion.isEmpty(); 9600 } 9601 9602 private Region calculateCurrentShape() { 9603 checkTreeLock(); 9604 Region s = getNormalShape(); 9605 9606 if (mixingLog.isLoggable(Level.FINE)) { 9607 mixingLog.fine("this = " + this + "; normalShape=" + s); 9608 } 9609 9610 if (getContainer() != null) { 9611 Component comp = this; 9612 Container cont = comp.getContainer(); 9613 9614 while (cont != null) { 9615 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) { 9616 /* It is assumed that: 9617 * 9618 * getComponent(getContainer().getComponentZOrder(comp)) == comp 9619 * 9620 * The assumption has been made according to the current 9621 * implementation of the Container class. 9622 */ 9623 Component c = cont.getComponent(index); 9624 if (c.isLightweight() && c.isShowing()) { 9625 s = s.getDifference(c.getOpaqueShape()); 9626 } 9627 } 9628 9629 if (cont.isLightweight()) { 9630 s = s.getIntersection(cont.getNormalShape()); 9631 } else { 9632 break; 9633 } 9634 9635 comp = cont; 9636 cont = cont.getContainer(); 9637 } 9638 } 9639 9640 if (mixingLog.isLoggable(Level.FINE)) { 9641 mixingLog.fine("currentShape=" + s); 9642 } 9643 9644 return s; 9645 } 9646 9647 void applyCurrentShape() { 9648 checkTreeLock(); 9649 if (!areBoundsValid()) { 9650 if (mixingLog.isLoggable(Level.FINE)) { 9651 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 9652 } 9653 return; // Because applyCompoundShape() ignores such components anyway 9654 } 9655 if (mixingLog.isLoggable(Level.FINE)) { 9656 mixingLog.fine("this = " + this); 9657 } 9658 applyCompoundShape(calculateCurrentShape()); 9659 } 9660 9661 final void subtractAndApplyShape(Region s) { 9662 checkTreeLock(); 9663 9664 if (mixingLog.isLoggable(Level.FINE)) { 9665 mixingLog.fine("this = " + this + "; s=" + s); 9666 } 9667 9668 applyCompoundShape(getAppliedShape().getDifference(s)); 9669 } 9670 9671 private final void applyCurrentShapeBelowMe() { 9672 checkTreeLock(); 9673 Container parent = getContainer(); 9674 if (parent != null && parent.isShowing()) { 9675 // First, reapply shapes of my siblings 9676 parent.recursiveApplyCurrentShape(getSiblingIndexBelow()); 9677 9678 // Second, if my container is non-opaque, reapply shapes of siblings of my container 9679 Container parent2 = parent.getContainer(); 9680 while (!parent.isOpaque() && parent2 != null) { 9681 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow()); 9682 9683 parent = parent2; 9684 parent2 = parent.getContainer(); 9685 } 9686 } 9687 } 9688 9689 final void subtractAndApplyShapeBelowMe() { 9690 checkTreeLock(); 9691 Container parent = getContainer(); 9692 if (parent != null && isShowing()) { 9693 Region opaqueShape = getOpaqueShape(); 9694 9695 // First, cut my siblings 9696 parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow()); 9697 9698 // Second, if my container is non-opaque, cut siblings of my container 9699 Container parent2 = parent.getContainer(); 9700 while (!parent.isOpaque() && parent2 != null) { 9701 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow()); 9702 9703 parent = parent2; 9704 parent2 = parent.getContainer(); 9705 } 9706 } 9707 } 9708 9709 void mixOnShowing() { 9710 synchronized (getTreeLock()) { 9711 if (mixingLog.isLoggable(Level.FINE)) { 9712 mixingLog.fine("this = " + this); 9713 } 9714 if (!isMixingNeeded()) { 9715 return; 9716 } 9717 if (isLightweight()) { 9718 subtractAndApplyShapeBelowMe(); 9719 } else { 9720 applyCurrentShape(); 9721 } 9722 } 9723 } 9724 9725 void mixOnHiding(boolean isLightweight) { 9726 // We cannot be sure that the peer exists at this point, so we need the argument 9727 // to find out whether the hiding component is (well, actually was) a LW or a HW. 9728 synchronized (getTreeLock()) { 9729 if (mixingLog.isLoggable(Level.FINE)) { 9730 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight); 9731 } 9732 if (!isMixingNeeded()) { 9733 return; 9734 } 9735 if (isLightweight) { 9736 applyCurrentShapeBelowMe(); 9737 } 9738 } 9739 } 9740 9741 void mixOnReshaping() { 9742 synchronized (getTreeLock()) { 9743 if (mixingLog.isLoggable(Level.FINE)) { 9744 mixingLog.fine("this = " + this); 9745 } 9746 if (!isMixingNeeded()) { 9747 return; 9748 } 9749 if (isLightweight()) { 9750 applyCurrentShapeBelowMe(); 9751 } else { 9752 applyCurrentShape(); 9753 } 9754 } 9755 } 9756 9757 void mixOnZOrderChanging(int oldZorder, int newZorder) { 9758 synchronized (getTreeLock()) { 9759 boolean becameHigher = newZorder < oldZorder; 9760 Container parent = getContainer(); 9761 9762 if (mixingLog.isLoggable(Level.FINE)) { 9763 mixingLog.fine("this = " + this + 9764 "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent); 9765 } 9766 if (!isMixingNeeded()) { 9767 return; 9768 } 9769 if (isLightweight()) { 9770 if (becameHigher) { 9771 if (parent != null && isShowing()) { 9772 parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder); 9773 } 9774 } else { 9775 if (parent != null) { 9776 parent.recursiveApplyCurrentShape(oldZorder, newZorder); 9777 } 9778 } 9779 } else { 9780 if (becameHigher) { 9781 applyCurrentShape(); 9782 } else { 9783 if (parent != null) { 9784 Region shape = getAppliedShape(); 9785 9786 for (int index = oldZorder; index < newZorder; index++) { 9787 Component c = parent.getComponent(index); 9788 if (c.isLightweight() && c.isShowing()) { 9789 shape = shape.getDifference(c.getOpaqueShape()); 9790 } 9791 } 9792 applyCompoundShape(shape); 9793 } 9794 } 9795 } 9796 } 9797 } 9798 9799 void mixOnValidating() { 9800 // This method gets overriden in the Container. Obviously, a plain 9801 // non-container components don't need to handle validation. 9802 } 9803 9804 final boolean isMixingNeeded() { 9805 if (SunToolkit.getSunAwtDisableMixing()) { 9806 if (mixingLog.isLoggable(Level.FINEST)) { 9807 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing"); 9808 } 9809 return false; 9810 } 9811 if (!areBoundsValid()) { 9812 if (mixingLog.isLoggable(Level.FINE)) { 9813 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 9814 } 9815 return false; 9816 } 9817 Window window = getContainingWindow(); 9818 if (window != null) { 9819 if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants()) { 9820 if (mixingLog.isLoggable(Level.FINE)) { 9821 mixingLog.fine("containing window = " + window + 9822 "; has h/w descendants = " + window.hasHeavyweightDescendants() + 9823 "; has l/w descendants = " + window.hasLightweightDescendants()); 9824 } 9825 return false; 9826 } 9827 } else { 9828 if (mixingLog.isLoggable(Level.FINE)) { 9829 mixingLog.finest("this = " + this + "; containing window is null"); 9830 } 9831 return false; 9832 } 9833 return true; 9834 } 9835 9836 // ****************** END OF MIXING CODE ******************************** 9837 9838 // Note that the method is overriden in the Window class, 9839 // a window doesn't need to be updated in the Z-order. 9840 void updateZOrder() { 9841 peer.setZOrder(getHWPeerAboveMe()); 9842 } 9843 9844 }