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