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