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 Set<AWTKeyStroke>[] focusTraversalKeys; 473 474 private static final String[] focusTraversalKeyPropertyNames = { 475 "forwardFocusTraversalKeys", 476 "backwardFocusTraversalKeys", 477 "upCycleFocusTraversalKeys", 478 "downCycleFocusTraversalKeys" 479 }; 480 481 /** 482 * Indicates whether focus traversal keys are enabled for this Component. 483 * Components for which focus traversal keys are disabled receive key 484 * events for focus traversal keys. Components for which focus traversal 485 * keys are enabled do not see these events; instead, the events are 486 * automatically converted to traversal operations. 487 * 488 * @serial 489 * @see #setFocusTraversalKeysEnabled 490 * @see #getFocusTraversalKeysEnabled 491 * @since 1.4 492 */ 493 private boolean focusTraversalKeysEnabled = true; 494 495 /** 496 * The locking object for AWT component-tree and layout operations. 497 * 498 * @see #getTreeLock 499 */ 500 static final Object LOCK = new AWTTreeLock(); 501 static class AWTTreeLock {} 502 503 /* 504 * The component's AccessControlContext. 505 */ 506 private transient volatile AccessControlContext acc = 507 AccessController.getContext(); 508 509 /** 510 * Minimum size. 511 * (This field perhaps should have been transient). 512 * 513 * @serial 514 */ 515 Dimension minSize; 516 517 /** 518 * Whether or not setMinimumSize has been invoked with a non-null value. 519 */ 520 boolean minSizeSet; 521 522 /** 523 * Preferred size. 524 * (This field perhaps should have been transient). 525 * 526 * @serial 527 */ 528 Dimension prefSize; 529 530 /** 531 * Whether or not setPreferredSize has been invoked with a non-null value. 532 */ 533 boolean prefSizeSet; 534 535 /** 536 * Maximum size 537 * 538 * @serial 539 */ 540 Dimension maxSize; 541 542 /** 543 * Whether or not setMaximumSize has been invoked with a non-null value. 544 */ 545 boolean maxSizeSet; 546 547 /** 548 * The orientation for this component. 549 * @see #getComponentOrientation 550 * @see #setComponentOrientation 551 */ 552 transient ComponentOrientation componentOrientation 553 = ComponentOrientation.UNKNOWN; 554 555 /** 556 * {@code newEventsOnly} will be true if the event is 557 * one of the event types enabled for the component. 558 * It will then allow for normal processing to 559 * continue. If it is false the event is passed 560 * to the component's parent and up the ancestor 561 * tree until the event has been consumed. 562 * 563 * @serial 564 * @see #dispatchEvent 565 */ 566 boolean newEventsOnly = false; 567 transient ComponentListener componentListener; 568 transient FocusListener focusListener; 569 transient HierarchyListener hierarchyListener; 570 transient HierarchyBoundsListener hierarchyBoundsListener; 571 transient KeyListener keyListener; 572 transient MouseListener mouseListener; 573 transient MouseMotionListener mouseMotionListener; 574 transient MouseWheelListener mouseWheelListener; 575 transient InputMethodListener inputMethodListener; 576 577 /** Internal, constants for serialization */ 578 static final String actionListenerK = "actionL"; 579 static final String adjustmentListenerK = "adjustmentL"; 580 static final String componentListenerK = "componentL"; 581 static final String containerListenerK = "containerL"; 582 static final String focusListenerK = "focusL"; 583 static final String itemListenerK = "itemL"; 584 static final String keyListenerK = "keyL"; 585 static final String mouseListenerK = "mouseL"; 586 static final String mouseMotionListenerK = "mouseMotionL"; 587 static final String mouseWheelListenerK = "mouseWheelL"; 588 static final String textListenerK = "textL"; 589 static final String ownedWindowK = "ownedL"; 590 static final String windowListenerK = "windowL"; 591 static final String inputMethodListenerK = "inputMethodL"; 592 static final String hierarchyListenerK = "hierarchyL"; 593 static final String hierarchyBoundsListenerK = "hierarchyBoundsL"; 594 static final String windowStateListenerK = "windowStateL"; 595 static final String windowFocusListenerK = "windowFocusL"; 596 597 /** 598 * The {@code eventMask} is ONLY set by subclasses via 599 * {@code enableEvents}. 600 * The mask should NOT be set when listeners are registered 601 * so that we can distinguish the difference between when 602 * listeners request events and subclasses request them. 603 * One bit is used to indicate whether input methods are 604 * enabled; this bit is set by {@code enableInputMethods} and is 605 * on by default. 606 * 607 * @serial 608 * @see #enableInputMethods 609 * @see AWTEvent 610 */ 611 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK; 612 613 /** 614 * Static properties for incremental drawing. 615 * @see #imageUpdate 616 */ 617 static boolean isInc; 618 static int incRate; 619 static { 620 /* ensure that the necessary native libraries are loaded */ 621 Toolkit.loadLibraries(); 622 /* initialize JNI field and method ids */ 623 if (!GraphicsEnvironment.isHeadless()) { 624 initIDs(); 625 } 626 627 String s = java.security.AccessController.doPrivileged( 628 new GetPropertyAction("awt.image.incrementaldraw")); 629 isInc = (s == null || s.equals("true")); 630 631 s = java.security.AccessController.doPrivileged( 632 new GetPropertyAction("awt.image.redrawrate")); 633 incRate = (s != null) ? Integer.parseInt(s) : 100; 634 } 635 636 /** 637 * Ease-of-use constant for {@code getAlignmentY()}. 638 * Specifies an alignment to the top of the component. 639 * @see #getAlignmentY 640 */ 641 public static final float TOP_ALIGNMENT = 0.0f; 642 643 /** 644 * Ease-of-use constant for {@code getAlignmentY} and 645 * {@code getAlignmentX}. Specifies an alignment to 646 * the center of the component 647 * @see #getAlignmentX 648 * @see #getAlignmentY 649 */ 650 public static final float CENTER_ALIGNMENT = 0.5f; 651 652 /** 653 * Ease-of-use constant for {@code getAlignmentY}. 654 * Specifies an alignment to the bottom of the component. 655 * @see #getAlignmentY 656 */ 657 public static final float BOTTOM_ALIGNMENT = 1.0f; 658 659 /** 660 * Ease-of-use constant for {@code getAlignmentX}. 661 * Specifies an alignment to the left side of the component. 662 * @see #getAlignmentX 663 */ 664 public static final float LEFT_ALIGNMENT = 0.0f; 665 666 /** 667 * Ease-of-use constant for {@code getAlignmentX}. 668 * Specifies an alignment to the right side of the component. 669 * @see #getAlignmentX 670 */ 671 public static final float RIGHT_ALIGNMENT = 1.0f; 672 673 /* 674 * JDK 1.1 serialVersionUID 675 */ 676 private static final long serialVersionUID = -7644114512714619750L; 677 678 /** 679 * If any {@code PropertyChangeListeners} have been registered, 680 * the {@code changeSupport} field describes them. 681 * 682 * @serial 683 * @since 1.2 684 * @see #addPropertyChangeListener 685 * @see #removePropertyChangeListener 686 * @see #firePropertyChange 687 */ 688 private PropertyChangeSupport changeSupport; 689 690 /* 691 * In some cases using "this" as an object to synchronize by 692 * can lead to a deadlock if client code also uses synchronization 693 * by a component object. For every such situation revealed we should 694 * consider possibility of replacing "this" with the package private 695 * objectLock object introduced below. So far there are 3 issues known: 696 * - CR 6708322 (the getName/setName methods); 697 * - CR 6608764 (the PropertyChangeListener machinery); 698 * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods). 699 * 700 * Note: this field is considered final, though readObject() prohibits 701 * initializing final fields. 702 */ 703 private transient Object objectLock = new Object(); 704 Object getObjectLock() { 705 return objectLock; 706 } 707 708 /* 709 * Returns the acc this component was constructed with. 710 */ 711 final AccessControlContext getAccessControlContext() { 712 if (acc == null) { 713 throw new SecurityException("Component is missing AccessControlContext"); 714 } 715 return acc; 716 } 717 718 boolean isPacked = false; 719 720 /** 721 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize 722 * to signal setBounds what's changing. Should be used under TreeLock. 723 * This is only needed due to the inability to change the cross-calling 724 * order of public and deprecated methods. 725 */ 726 private int boundsOp = ComponentPeer.DEFAULT_OPERATION; 727 728 /** 729 * Enumeration of the common ways the baseline of a component can 730 * change as the size changes. The baseline resize behavior is 731 * primarily for layout managers that need to know how the 732 * position of the baseline changes as the component size changes. 733 * In general the baseline resize behavior will be valid for sizes 734 * greater than or equal to the minimum size (the actual minimum 735 * size; not a developer specified minimum size). For sizes 736 * smaller than the minimum size the baseline may change in a way 737 * other than the baseline resize behavior indicates. Similarly, 738 * as the size approaches {@code Integer.MAX_VALUE} and/or 739 * {@code Short.MAX_VALUE} the baseline may change in a way 740 * other than the baseline resize behavior indicates. 741 * 742 * @see #getBaselineResizeBehavior 743 * @see #getBaseline(int,int) 744 * @since 1.6 745 */ 746 public enum BaselineResizeBehavior { 747 /** 748 * Indicates the baseline remains fixed relative to the 749 * y-origin. That is, {@code getBaseline} returns 750 * the same value regardless of the height or width. For example, a 751 * {@code JLabel} containing non-empty text with a 752 * vertical alignment of {@code TOP} should have a 753 * baseline type of {@code CONSTANT_ASCENT}. 754 */ 755 CONSTANT_ASCENT, 756 757 /** 758 * Indicates the baseline remains fixed relative to the height 759 * and does not change as the width is varied. That is, for 760 * any height H the difference between H and 761 * {@code getBaseline(w, H)} is the same. For example, a 762 * {@code JLabel} containing non-empty text with a 763 * vertical alignment of {@code BOTTOM} should have a 764 * baseline type of {@code CONSTANT_DESCENT}. 765 */ 766 CONSTANT_DESCENT, 767 768 /** 769 * Indicates the baseline remains a fixed distance from 770 * the center of the component. That is, for any height H the 771 * difference between {@code getBaseline(w, H)} and 772 * {@code H / 2} is the same (plus or minus one depending upon 773 * rounding error). 774 * <p> 775 * Because of possible rounding errors it is recommended 776 * you ask for the baseline with two consecutive heights and use 777 * the return value to determine if you need to pad calculations 778 * by 1. The following shows how to calculate the baseline for 779 * any height: 780 * <pre> 781 * Dimension preferredSize = component.getPreferredSize(); 782 * int baseline = getBaseline(preferredSize.width, 783 * preferredSize.height); 784 * int nextBaseline = getBaseline(preferredSize.width, 785 * preferredSize.height + 1); 786 * // Amount to add to height when calculating where baseline 787 * // lands for a particular height: 788 * int padding = 0; 789 * // Where the baseline is relative to the mid point 790 * int baselineOffset = baseline - height / 2; 791 * if (preferredSize.height % 2 == 0 && 792 * baseline != nextBaseline) { 793 * padding = 1; 794 * } 795 * else if (preferredSize.height % 2 == 1 && 796 * baseline == nextBaseline) { 797 * baselineOffset--; 798 * padding = 1; 799 * } 800 * // The following calculates where the baseline lands for 801 * // the height z: 802 * int calculatedBaseline = (z + padding) / 2 + baselineOffset; 803 * </pre> 804 */ 805 CENTER_OFFSET, 806 807 /** 808 * Indicates the baseline resize behavior can not be expressed using 809 * any of the other constants. This may also indicate the baseline 810 * varies with the width of the component. This is also returned 811 * by components that do not have a baseline. 812 */ 813 OTHER 814 } 815 816 /* 817 * The shape set with the applyCompoundShape() method. It includes the result 818 * of the HW/LW mixing related shape computation. It may also include 819 * the user-specified shape of the component. 820 * The 'null' value means the component has normal shape (or has no shape at all) 821 * and applyCompoundShape() will skip the following shape identical to normal. 822 */ 823 private transient Region compoundShape = null; 824 825 /* 826 * Represents the shape of this lightweight component to be cut out from 827 * heavyweight components should they intersect. Possible values: 828 * 1. null - consider the shape rectangular 829 * 2. EMPTY_REGION - nothing gets cut out (children still get cut out) 830 * 3. non-empty - this shape gets cut out. 831 */ 832 private transient Region mixingCutoutRegion = null; 833 834 /* 835 * Indicates whether addNotify() is complete 836 * (i.e. the peer is created). 837 */ 838 private transient boolean isAddNotifyComplete = false; 839 840 /** 841 * Should only be used in subclass getBounds to check that part of bounds 842 * is actually changing 843 */ 844 int getBoundsOp() { 845 assert Thread.holdsLock(getTreeLock()); 846 return boundsOp; 847 } 848 849 void setBoundsOp(int op) { 850 assert Thread.holdsLock(getTreeLock()); 851 if (op == ComponentPeer.RESET_OPERATION) { 852 boundsOp = ComponentPeer.DEFAULT_OPERATION; 853 } else 854 if (boundsOp == ComponentPeer.DEFAULT_OPERATION) { 855 boundsOp = op; 856 } 857 } 858 859 // Whether this Component has had the background erase flag 860 // specified via SunToolkit.disableBackgroundErase(). This is 861 // needed in order to make this function work on X11 platforms, 862 // where currently there is no chance to interpose on the creation 863 // of the peer and therefore the call to XSetBackground. 864 transient boolean backgroundEraseDisabled; 865 866 static { 867 AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() { 868 public void setBackgroundEraseDisabled(Component comp, boolean disabled) { 869 comp.backgroundEraseDisabled = disabled; 870 } 871 public boolean getBackgroundEraseDisabled(Component comp) { 872 return comp.backgroundEraseDisabled; 873 } 874 public Rectangle getBounds(Component comp) { 875 return new Rectangle(comp.x, comp.y, comp.width, comp.height); 876 } 877 public void setGraphicsConfiguration(Component comp, 878 GraphicsConfiguration gc) 879 { 880 comp.setGraphicsConfiguration(gc); 881 } 882 public void requestFocus(Component comp, FocusEvent.Cause cause) { 883 comp.requestFocus(cause); 884 } 885 public boolean canBeFocusOwner(Component comp) { 886 return comp.canBeFocusOwner(); 887 } 888 889 public boolean isVisible(Component comp) { 890 return comp.isVisible_NoClientCode(); 891 } 892 public void setRequestFocusController 893 (RequestFocusController requestController) 894 { 895 Component.setRequestFocusController(requestController); 896 } 897 public AppContext getAppContext(Component comp) { 898 return comp.appContext; 899 } 900 public void setAppContext(Component comp, AppContext appContext) { 901 comp.appContext = appContext; 902 } 903 public Container getParent(Component comp) { 904 return comp.getParent_NoClientCode(); 905 } 906 public void setParent(Component comp, Container parent) { 907 comp.parent = parent; 908 } 909 public void setSize(Component comp, int width, int height) { 910 comp.width = width; 911 comp.height = height; 912 } 913 public Point getLocation(Component comp) { 914 return comp.location_NoClientCode(); 915 } 916 public void setLocation(Component comp, int x, int y) { 917 comp.x = x; 918 comp.y = y; 919 } 920 public boolean isEnabled(Component comp) { 921 return comp.isEnabledImpl(); 922 } 923 public boolean isDisplayable(Component comp) { 924 return comp.peer != null; 925 } 926 public Cursor getCursor(Component comp) { 927 return comp.getCursor_NoClientCode(); 928 } 929 @SuppressWarnings("unchecked") 930 public <T extends ComponentPeer> T getPeer(Component comp) { 931 return (T) comp.peer; 932 } 933 public void setPeer(Component comp, ComponentPeer peer) { 934 comp.peer = peer; 935 } 936 public boolean isLightweight(Component comp) { 937 return (comp.peer instanceof LightweightPeer); 938 } 939 public boolean getIgnoreRepaint(Component comp) { 940 return comp.ignoreRepaint; 941 } 942 public int getWidth(Component comp) { 943 return comp.width; 944 } 945 public int getHeight(Component comp) { 946 return comp.height; 947 } 948 public int getX(Component comp) { 949 return comp.x; 950 } 951 public int getY(Component comp) { 952 return comp.y; 953 } 954 public Color getForeground(Component comp) { 955 return comp.foreground; 956 } 957 public Color getBackground(Component comp) { 958 return comp.background; 959 } 960 public void setBackground(Component comp, Color background) { 961 comp.background = background; 962 } 963 public Font getFont(Component comp) { 964 return comp.getFont_NoClientCode(); 965 } 966 public void processEvent(Component comp, AWTEvent e) { 967 comp.processEvent(e); 968 } 969 970 public AccessControlContext getAccessControlContext(Component comp) { 971 return comp.getAccessControlContext(); 972 } 973 974 public void revalidateSynchronously(Component comp) { 975 comp.revalidateSynchronously(); 976 } 977 978 @Override 979 public void createBufferStrategy(Component comp, int numBuffers, 980 BufferCapabilities caps) throws AWTException { 981 comp.createBufferStrategy(numBuffers, caps); 982 } 983 984 @Override 985 public BufferStrategy getBufferStrategy(Component comp) { 986 return comp.getBufferStrategy(); 987 } 988 }); 989 } 990 991 /** 992 * Constructs a new component. Class {@code Component} can be 993 * extended directly to create a lightweight component that does not 994 * utilize an opaque native window. A lightweight component must be 995 * hosted by a native container somewhere higher up in the component 996 * tree (for example, by a {@code Frame} object). 997 */ 998 protected Component() { 999 appContext = AppContext.getAppContext(); 1000 } 1001 1002 @SuppressWarnings({"rawtypes", "unchecked"}) 1003 void initializeFocusTraversalKeys() { 1004 focusTraversalKeys = new Set[3]; 1005 } 1006 1007 /** 1008 * Constructs a name for this component. Called by {@code getName} 1009 * when the name is {@code null}. 1010 */ 1011 String constructComponentName() { 1012 return null; // For strict compliance with prior platform versions, a Component 1013 // that doesn't set its name should return null from 1014 // getName() 1015 } 1016 1017 /** 1018 * Gets the name of the component. 1019 * @return this component's name 1020 * @see #setName 1021 * @since 1.1 1022 */ 1023 public String getName() { 1024 if (name == null && !nameExplicitlySet) { 1025 synchronized(getObjectLock()) { 1026 if (name == null && !nameExplicitlySet) 1027 name = constructComponentName(); 1028 } 1029 } 1030 return name; 1031 } 1032 1033 /** 1034 * Sets the name of the component to the specified string. 1035 * @param name the string that is to be this 1036 * component's name 1037 * @see #getName 1038 * @since 1.1 1039 */ 1040 public void setName(String name) { 1041 String oldName; 1042 synchronized(getObjectLock()) { 1043 oldName = this.name; 1044 this.name = name; 1045 nameExplicitlySet = true; 1046 } 1047 firePropertyChange("name", oldName, name); 1048 } 1049 1050 /** 1051 * Gets the parent of this component. 1052 * @return the parent container of this component 1053 * @since 1.0 1054 */ 1055 public Container getParent() { 1056 return getParent_NoClientCode(); 1057 } 1058 1059 // NOTE: This method may be called by privileged threads. 1060 // This functionality is implemented in a package-private method 1061 // to insure that it cannot be overridden by client subclasses. 1062 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 1063 final Container getParent_NoClientCode() { 1064 return parent; 1065 } 1066 1067 // This method is overridden in the Window class to return null, 1068 // because the parent field of the Window object contains 1069 // the owner of the window, not its parent. 1070 Container getContainer() { 1071 return getParent_NoClientCode(); 1072 } 1073 1074 /** 1075 * Associate a {@code DropTarget} with this component. 1076 * The {@code Component} will receive drops only if it 1077 * is enabled. 1078 * 1079 * @see #isEnabled 1080 * @param dt The DropTarget 1081 */ 1082 1083 public synchronized void setDropTarget(DropTarget dt) { 1084 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt))) 1085 return; 1086 1087 DropTarget old; 1088 1089 if ((old = dropTarget) != null) { 1090 dropTarget.removeNotify(); 1091 1092 DropTarget t = dropTarget; 1093 1094 dropTarget = null; 1095 1096 try { 1097 t.setComponent(null); 1098 } catch (IllegalArgumentException iae) { 1099 // ignore it. 1100 } 1101 } 1102 1103 // if we have a new one, and we have a peer, add it! 1104 1105 if ((dropTarget = dt) != null) { 1106 try { 1107 dropTarget.setComponent(this); 1108 dropTarget.addNotify(); 1109 } catch (IllegalArgumentException iae) { 1110 if (old != null) { 1111 try { 1112 old.setComponent(this); 1113 dropTarget.addNotify(); 1114 } catch (IllegalArgumentException iae1) { 1115 // ignore it! 1116 } 1117 } 1118 } 1119 } 1120 } 1121 1122 /** 1123 * Gets the {@code DropTarget} associated with this 1124 * {@code Component}. 1125 * 1126 * @return the drop target 1127 */ 1128 1129 public synchronized DropTarget getDropTarget() { return dropTarget; } 1130 1131 /** 1132 * Gets the {@code GraphicsConfiguration} associated with this 1133 * {@code Component}. 1134 * If the {@code Component} has not been assigned a specific 1135 * {@code GraphicsConfiguration}, 1136 * the {@code GraphicsConfiguration} of the 1137 * {@code Component} object's top-level container is 1138 * returned. 1139 * If the {@code Component} has been created, but not yet added 1140 * to a {@code Container}, this method returns {@code null}. 1141 * 1142 * @return the {@code GraphicsConfiguration} used by this 1143 * {@code Component} or {@code null} 1144 * @since 1.3 1145 */ 1146 public GraphicsConfiguration getGraphicsConfiguration() { 1147 return getGraphicsConfiguration_NoClientCode(); 1148 } 1149 1150 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() { 1151 return graphicsConfig; 1152 } 1153 1154 void setGraphicsConfiguration(GraphicsConfiguration gc) { 1155 synchronized(getTreeLock()) { 1156 if (updateGraphicsData(gc)) { 1157 removeNotify(); 1158 addNotify(); 1159 } 1160 } 1161 } 1162 1163 final boolean updateGraphicsData(GraphicsConfiguration gc) { 1164 GraphicsConfiguration oldConfig = graphicsConfig; 1165 // First, update own graphics configuration 1166 boolean ret = updateSelfGraphicsData(gc); 1167 // Second, update children graphics configurations 1168 ret |= updateChildGraphicsData(gc); 1169 // Third, fire PropertyChange if needed 1170 if (oldConfig != gc) { 1171 /* 1172 * If component is moved from one screen to another screen or shown 1173 * for the first time graphicsConfiguration property is fired to 1174 * enable the component to recalculate any rendering data, if needed 1175 */ 1176 firePropertyChange("graphicsConfiguration", oldConfig, gc); 1177 } 1178 return ret; 1179 } 1180 1181 private boolean updateSelfGraphicsData(GraphicsConfiguration gc) { 1182 checkTreeLock(); 1183 if (graphicsConfig == gc) { 1184 return false; 1185 } 1186 graphicsConfig = gc; 1187 1188 ComponentPeer peer = this.peer; 1189 if (peer != null) { 1190 return peer.updateGraphicsData(gc); 1191 } 1192 return false; 1193 } 1194 1195 boolean updateChildGraphicsData(GraphicsConfiguration gc) { 1196 return false; 1197 } 1198 1199 /** 1200 * Checks that this component's {@code GraphicsDevice} 1201 * {@code idString} matches the string argument. 1202 */ 1203 void checkGD(String stringID) { 1204 if (graphicsConfig != null) { 1205 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) { 1206 throw new IllegalArgumentException( 1207 "adding a container to a container on a different GraphicsDevice"); 1208 } 1209 } 1210 } 1211 1212 /** 1213 * Gets this component's locking object (the object that owns the thread 1214 * synchronization monitor) for AWT component-tree and layout 1215 * operations. 1216 * @return this component's locking object 1217 */ 1218 public final Object getTreeLock() { 1219 return LOCK; 1220 } 1221 1222 final void checkTreeLock() { 1223 if (!Thread.holdsLock(getTreeLock())) { 1224 throw new IllegalStateException("This function should be called while holding treeLock"); 1225 } 1226 } 1227 1228 /** 1229 * Gets the toolkit of this component. Note that 1230 * the frame that contains a component controls which 1231 * toolkit is used by that component. Therefore if the component 1232 * is moved from one frame to another, the toolkit it uses may change. 1233 * @return the toolkit of this component 1234 * @since 1.0 1235 */ 1236 public Toolkit getToolkit() { 1237 return getToolkitImpl(); 1238 } 1239 1240 /* 1241 * This is called by the native code, so client code can't 1242 * be called on the toolkit thread. 1243 */ 1244 final Toolkit getToolkitImpl() { 1245 Container parent = this.parent; 1246 if (parent != null) { 1247 return parent.getToolkitImpl(); 1248 } 1249 return Toolkit.getDefaultToolkit(); 1250 } 1251 1252 final ComponentFactory getComponentFactory() { 1253 final Toolkit toolkit = getToolkit(); 1254 if (toolkit instanceof ComponentFactory) { 1255 return (ComponentFactory) toolkit; 1256 } 1257 throw new AWTError("UI components are unsupported by: " + toolkit); 1258 } 1259 1260 /** 1261 * Determines whether this component is valid. A component is valid 1262 * when it is correctly sized and positioned within its parent 1263 * container and all its children are also valid. 1264 * In order to account for peers' size requirements, components are invalidated 1265 * before they are first shown on the screen. By the time the parent container 1266 * is fully realized, all its components will be valid. 1267 * @return {@code true} if the component is valid, {@code false} 1268 * otherwise 1269 * @see #validate 1270 * @see #invalidate 1271 * @since 1.0 1272 */ 1273 public boolean isValid() { 1274 return (peer != null) && valid; 1275 } 1276 1277 /** 1278 * Determines whether this component is displayable. A component is 1279 * displayable when it is connected to a native screen resource. 1280 * <p> 1281 * A component is made displayable either when it is added to 1282 * a displayable containment hierarchy or when its containment 1283 * hierarchy is made displayable. 1284 * A containment hierarchy is made displayable when its ancestor 1285 * window is either packed or made visible. 1286 * <p> 1287 * A component is made undisplayable either when it is removed from 1288 * a displayable containment hierarchy or when its containment hierarchy 1289 * is made undisplayable. A containment hierarchy is made 1290 * undisplayable when its ancestor window is disposed. 1291 * 1292 * @return {@code true} if the component is displayable, 1293 * {@code false} otherwise 1294 * @see Container#add(Component) 1295 * @see Window#pack 1296 * @see Window#show 1297 * @see Container#remove(Component) 1298 * @see Window#dispose 1299 * @since 1.2 1300 */ 1301 public boolean isDisplayable() { 1302 return peer != null; 1303 } 1304 1305 /** 1306 * Determines whether this component should be visible when its 1307 * parent is visible. Components are 1308 * initially visible, with the exception of top level components such 1309 * as {@code Frame} objects. 1310 * @return {@code true} if the component is visible, 1311 * {@code false} otherwise 1312 * @see #setVisible 1313 * @since 1.0 1314 */ 1315 @Transient 1316 public boolean isVisible() { 1317 return isVisible_NoClientCode(); 1318 } 1319 final boolean isVisible_NoClientCode() { 1320 return visible; 1321 } 1322 1323 /** 1324 * Determines whether this component will be displayed on the screen. 1325 * @return {@code true} if the component and all of its ancestors 1326 * until a toplevel window or null parent are visible, 1327 * {@code false} otherwise 1328 */ 1329 boolean isRecursivelyVisible() { 1330 return visible && (parent == null || parent.isRecursivelyVisible()); 1331 } 1332 1333 /** 1334 * Determines the bounds of a visible part of the component relative to its 1335 * parent. 1336 * 1337 * @return the visible part of bounds 1338 */ 1339 private Rectangle getRecursivelyVisibleBounds() { 1340 final Component container = getContainer(); 1341 final Rectangle bounds = getBounds(); 1342 if (container == null) { 1343 // we are top level window or haven't a container, return our bounds 1344 return bounds; 1345 } 1346 // translate the container's bounds to our coordinate space 1347 final Rectangle parentsBounds = container.getRecursivelyVisibleBounds(); 1348 parentsBounds.setLocation(0, 0); 1349 return parentsBounds.intersection(bounds); 1350 } 1351 1352 /** 1353 * Translates absolute coordinates into coordinates in the coordinate 1354 * space of this component. 1355 */ 1356 Point pointRelativeToComponent(Point absolute) { 1357 Point compCoords = getLocationOnScreen(); 1358 return new Point(absolute.x - compCoords.x, 1359 absolute.y - compCoords.y); 1360 } 1361 1362 /** 1363 * Assuming that mouse location is stored in PointerInfo passed 1364 * to this method, it finds a Component that is in the same 1365 * Window as this Component and is located under the mouse pointer. 1366 * If no such Component exists, null is returned. 1367 * NOTE: this method should be called under the protection of 1368 * tree lock, as it is done in Component.getMousePosition() and 1369 * Container.getMousePosition(boolean). 1370 */ 1371 Component findUnderMouseInWindow(PointerInfo pi) { 1372 if (!isShowing()) { 1373 return null; 1374 } 1375 Window win = getContainingWindow(); 1376 Toolkit toolkit = Toolkit.getDefaultToolkit(); 1377 if (!(toolkit instanceof ComponentFactory)) { 1378 return null; 1379 } 1380 if (!((ComponentFactory) toolkit).getMouseInfoPeer().isWindowUnderMouse(win)) { 1381 return null; 1382 } 1383 final boolean INCLUDE_DISABLED = true; 1384 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation()); 1385 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x, 1386 relativeToWindow.y, 1387 INCLUDE_DISABLED); 1388 return inTheSameWindow; 1389 } 1390 1391 /** 1392 * Returns the position of the mouse pointer in this {@code Component}'s 1393 * coordinate space if the {@code Component} is directly under the mouse 1394 * pointer, otherwise returns {@code null}. 1395 * If the {@code Component} is not showing on the screen, this method 1396 * returns {@code null} even if the mouse pointer is above the area 1397 * where the {@code Component} would be displayed. 1398 * If the {@code Component} is partially or fully obscured by other 1399 * {@code Component}s or native windows, this method returns a non-null 1400 * value only if the mouse pointer is located above the unobscured part of the 1401 * {@code Component}. 1402 * <p> 1403 * For {@code Container}s it returns a non-null value if the mouse is 1404 * above the {@code Container} itself or above any of its descendants. 1405 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children. 1406 * <p> 1407 * Sometimes the exact mouse coordinates are not important, and the only thing 1408 * that matters is whether a specific {@code Component} is under the mouse 1409 * pointer. If the return value of this method is {@code null}, mouse 1410 * pointer is not directly above the {@code Component}. 1411 * 1412 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true 1413 * @see #isShowing 1414 * @see Container#getMousePosition 1415 * @return mouse coordinates relative to this {@code Component}, or null 1416 * @since 1.5 1417 */ 1418 public Point getMousePosition() throws HeadlessException { 1419 if (GraphicsEnvironment.isHeadless()) { 1420 throw new HeadlessException(); 1421 } 1422 1423 PointerInfo pi = java.security.AccessController.doPrivileged( 1424 new java.security.PrivilegedAction<PointerInfo>() { 1425 public PointerInfo run() { 1426 return MouseInfo.getPointerInfo(); 1427 } 1428 } 1429 ); 1430 1431 synchronized (getTreeLock()) { 1432 Component inTheSameWindow = findUnderMouseInWindow(pi); 1433 if (!isSameOrAncestorOf(inTheSameWindow, true)) { 1434 return null; 1435 } 1436 return pointRelativeToComponent(pi.getLocation()); 1437 } 1438 } 1439 1440 /** 1441 * Overridden in Container. Must be called under TreeLock. 1442 */ 1443 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) { 1444 return comp == this; 1445 } 1446 1447 /** 1448 * Determines whether this component is showing on screen. This means 1449 * that the component must be visible, and it must be in a container 1450 * that is visible and showing. 1451 * <p> 1452 * <strong>Note:</strong> sometimes there is no way to detect whether the 1453 * {@code Component} is actually visible to the user. This can happen when: 1454 * <ul> 1455 * <li>the component has been added to a visible {@code ScrollPane} but 1456 * the {@code Component} is not currently in the scroll pane's view port. 1457 * <li>the {@code Component} is obscured by another {@code Component} or 1458 * {@code Container}. 1459 * </ul> 1460 * @return {@code true} if the component is showing, 1461 * {@code false} otherwise 1462 * @see #setVisible 1463 * @since 1.0 1464 */ 1465 public boolean isShowing() { 1466 if (visible && (peer != null)) { 1467 Container parent = this.parent; 1468 return (parent == null) || parent.isShowing(); 1469 } 1470 return false; 1471 } 1472 1473 /** 1474 * Determines whether this component is enabled. An enabled component 1475 * can respond to user input and generate events. Components are 1476 * enabled initially by default. A component may be enabled or disabled by 1477 * calling its {@code setEnabled} method. 1478 * @return {@code true} if the component is enabled, 1479 * {@code false} otherwise 1480 * @see #setEnabled 1481 * @since 1.0 1482 */ 1483 public boolean isEnabled() { 1484 return isEnabledImpl(); 1485 } 1486 1487 /* 1488 * This is called by the native code, so client code can't 1489 * be called on the toolkit thread. 1490 */ 1491 final boolean isEnabledImpl() { 1492 return enabled; 1493 } 1494 1495 /** 1496 * Enables or disables this component, depending on the value of the 1497 * parameter {@code b}. An enabled component can respond to user 1498 * input and generate events. Components are enabled initially by default. 1499 * 1500 * <p>Note: Disabling a lightweight component does not prevent it from 1501 * receiving MouseEvents. 1502 * <p>Note: Disabling a heavyweight container prevents all components 1503 * in this container from receiving any input events. But disabling a 1504 * lightweight container affects only this container. 1505 * 1506 * @param b If {@code true}, this component is 1507 * enabled; otherwise this component is disabled 1508 * @see #isEnabled 1509 * @see #isLightweight 1510 * @since 1.1 1511 */ 1512 public void setEnabled(boolean b) { 1513 enable(b); 1514 } 1515 1516 /** 1517 * @deprecated As of JDK version 1.1, 1518 * replaced by {@code setEnabled(boolean)}. 1519 */ 1520 @Deprecated 1521 public void enable() { 1522 if (!enabled) { 1523 synchronized (getTreeLock()) { 1524 enabled = true; 1525 ComponentPeer peer = this.peer; 1526 if (peer != null) { 1527 peer.setEnabled(true); 1528 if (visible && !getRecursivelyVisibleBounds().isEmpty()) { 1529 updateCursorImmediately(); 1530 } 1531 } 1532 } 1533 if (accessibleContext != null) { 1534 accessibleContext.firePropertyChange( 1535 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1536 null, AccessibleState.ENABLED); 1537 } 1538 } 1539 } 1540 1541 /** 1542 * Enables or disables this component. 1543 * 1544 * @param b {@code true} to enable this component; 1545 * otherwise {@code false} 1546 * 1547 * @deprecated As of JDK version 1.1, 1548 * replaced by {@code setEnabled(boolean)}. 1549 */ 1550 @Deprecated 1551 public void enable(boolean b) { 1552 if (b) { 1553 enable(); 1554 } else { 1555 disable(); 1556 } 1557 } 1558 1559 /** 1560 * @deprecated As of JDK version 1.1, 1561 * replaced by {@code setEnabled(boolean)}. 1562 */ 1563 @Deprecated 1564 public void disable() { 1565 if (enabled) { 1566 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1567 synchronized (getTreeLock()) { 1568 enabled = false; 1569 // A disabled lw container is allowed to contain a focus owner. 1570 if ((isFocusOwner() || (containsFocus() && !isLightweight())) && 1571 KeyboardFocusManager.isAutoFocusTransferEnabled()) 1572 { 1573 // Don't clear the global focus owner. If transferFocus 1574 // fails, we want the focus to stay on the disabled 1575 // Component so that keyboard traversal, et. al. still 1576 // makes sense to the user. 1577 transferFocus(false); 1578 } 1579 ComponentPeer peer = this.peer; 1580 if (peer != null) { 1581 peer.setEnabled(false); 1582 if (visible && !getRecursivelyVisibleBounds().isEmpty()) { 1583 updateCursorImmediately(); 1584 } 1585 } 1586 } 1587 if (accessibleContext != null) { 1588 accessibleContext.firePropertyChange( 1589 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1590 null, AccessibleState.ENABLED); 1591 } 1592 } 1593 } 1594 1595 /** 1596 * Returns true if this component is painted to an offscreen image 1597 * ("buffer") that's copied to the screen later. Component 1598 * subclasses that support double buffering should override this 1599 * method to return true if double buffering is enabled. 1600 * 1601 * @return false by default 1602 */ 1603 public boolean isDoubleBuffered() { 1604 return false; 1605 } 1606 1607 /** 1608 * Enables or disables input method support for this component. If input 1609 * method support is enabled and the component also processes key events, 1610 * incoming events are offered to 1611 * the current input method and will only be processed by the component or 1612 * dispatched to its listeners if the input method does not consume them. 1613 * By default, input method support is enabled. 1614 * 1615 * @param enable true to enable, false to disable 1616 * @see #processKeyEvent 1617 * @since 1.2 1618 */ 1619 public void enableInputMethods(boolean enable) { 1620 if (enable) { 1621 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) 1622 return; 1623 1624 // If this component already has focus, then activate the 1625 // input method by dispatching a synthesized focus gained 1626 // event. 1627 if (isFocusOwner()) { 1628 InputContext inputContext = getInputContext(); 1629 if (inputContext != null) { 1630 FocusEvent focusGainedEvent = 1631 new FocusEvent(this, FocusEvent.FOCUS_GAINED); 1632 inputContext.dispatchEvent(focusGainedEvent); 1633 } 1634 } 1635 1636 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK; 1637 } else { 1638 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { 1639 InputContext inputContext = getInputContext(); 1640 if (inputContext != null) { 1641 inputContext.endComposition(); 1642 inputContext.removeNotify(this); 1643 } 1644 } 1645 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK; 1646 } 1647 } 1648 1649 /** 1650 * Shows or hides this component depending on the value of parameter 1651 * {@code b}. 1652 * <p> 1653 * This method changes layout-related information, and therefore, 1654 * invalidates the component hierarchy. 1655 * 1656 * @param b if {@code true}, shows this component; 1657 * otherwise, hides this component 1658 * @see #isVisible 1659 * @see #invalidate 1660 * @since 1.1 1661 */ 1662 public void setVisible(boolean b) { 1663 show(b); 1664 } 1665 1666 /** 1667 * @deprecated As of JDK version 1.1, 1668 * replaced by {@code setVisible(boolean)}. 1669 */ 1670 @Deprecated 1671 public void show() { 1672 if (!visible) { 1673 synchronized (getTreeLock()) { 1674 visible = true; 1675 mixOnShowing(); 1676 ComponentPeer peer = this.peer; 1677 if (peer != null) { 1678 peer.setVisible(true); 1679 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1680 this, parent, 1681 HierarchyEvent.SHOWING_CHANGED, 1682 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1683 if (peer instanceof LightweightPeer) { 1684 repaint(); 1685 } 1686 updateCursorImmediately(); 1687 } 1688 1689 if (componentListener != null || 1690 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1691 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1692 ComponentEvent e = new ComponentEvent(this, 1693 ComponentEvent.COMPONENT_SHOWN); 1694 Toolkit.getEventQueue().postEvent(e); 1695 } 1696 } 1697 Container parent = this.parent; 1698 if (parent != null) { 1699 parent.invalidate(); 1700 } 1701 } 1702 } 1703 1704 /** 1705 * Makes this component visible or invisible. 1706 * 1707 * @param b {@code true} to make this component visible; 1708 * otherwise {@code false} 1709 * 1710 * @deprecated As of JDK version 1.1, 1711 * replaced by {@code setVisible(boolean)}. 1712 */ 1713 @Deprecated 1714 public void show(boolean b) { 1715 if (b) { 1716 show(); 1717 } else { 1718 hide(); 1719 } 1720 } 1721 1722 boolean containsFocus() { 1723 return isFocusOwner(); 1724 } 1725 1726 void clearMostRecentFocusOwnerOnHide() { 1727 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1728 } 1729 1730 void clearCurrentFocusCycleRootOnHide() { 1731 /* do nothing */ 1732 } 1733 1734 /** 1735 * @deprecated As of JDK version 1.1, 1736 * replaced by {@code setVisible(boolean)}. 1737 */ 1738 @Deprecated 1739 public void hide() { 1740 isPacked = false; 1741 1742 if (visible) { 1743 clearCurrentFocusCycleRootOnHide(); 1744 clearMostRecentFocusOwnerOnHide(); 1745 synchronized (getTreeLock()) { 1746 visible = false; 1747 mixOnHiding(isLightweight()); 1748 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) { 1749 transferFocus(true); 1750 } 1751 ComponentPeer peer = this.peer; 1752 if (peer != null) { 1753 peer.setVisible(false); 1754 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1755 this, parent, 1756 HierarchyEvent.SHOWING_CHANGED, 1757 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1758 if (peer instanceof LightweightPeer) { 1759 repaint(); 1760 } 1761 updateCursorImmediately(); 1762 } 1763 if (componentListener != null || 1764 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1765 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1766 ComponentEvent e = new ComponentEvent(this, 1767 ComponentEvent.COMPONENT_HIDDEN); 1768 Toolkit.getEventQueue().postEvent(e); 1769 } 1770 } 1771 Container parent = this.parent; 1772 if (parent != null) { 1773 parent.invalidate(); 1774 } 1775 } 1776 } 1777 1778 /** 1779 * Gets the foreground color of this component. 1780 * @return this component's foreground color; if this component does 1781 * not have a foreground color, the foreground color of its parent 1782 * is returned 1783 * @see #setForeground 1784 * @since 1.0 1785 */ 1786 @Transient 1787 public Color getForeground() { 1788 Color foreground = this.foreground; 1789 if (foreground != null) { 1790 return foreground; 1791 } 1792 Container parent = this.parent; 1793 return (parent != null) ? parent.getForeground() : null; 1794 } 1795 1796 /** 1797 * Sets the foreground color of this component. 1798 * @param c the color to become this component's 1799 * foreground color; if this parameter is {@code null} 1800 * then this component will inherit 1801 * the foreground color of its parent 1802 * @see #getForeground 1803 * @since 1.0 1804 */ 1805 public void setForeground(Color c) { 1806 Color oldColor = foreground; 1807 ComponentPeer peer = this.peer; 1808 foreground = c; 1809 if (peer != null) { 1810 c = getForeground(); 1811 if (c != null) { 1812 peer.setForeground(c); 1813 } 1814 } 1815 // This is a bound property, so report the change to 1816 // any registered listeners. (Cheap if there are none.) 1817 firePropertyChange("foreground", oldColor, c); 1818 } 1819 1820 /** 1821 * Returns whether the foreground color has been explicitly set for this 1822 * Component. If this method returns {@code false}, this Component is 1823 * inheriting its foreground color from an ancestor. 1824 * 1825 * @return {@code true} if the foreground color has been explicitly 1826 * set for this Component; {@code false} otherwise. 1827 * @since 1.4 1828 */ 1829 public boolean isForegroundSet() { 1830 return (foreground != null); 1831 } 1832 1833 /** 1834 * Gets the background color of this component. 1835 * @return this component's background color; if this component does 1836 * not have a background color, 1837 * the background color of its parent is returned 1838 * @see #setBackground 1839 * @since 1.0 1840 */ 1841 @Transient 1842 public Color getBackground() { 1843 Color background = this.background; 1844 if (background != null) { 1845 return background; 1846 } 1847 Container parent = this.parent; 1848 return (parent != null) ? parent.getBackground() : null; 1849 } 1850 1851 /** 1852 * Sets the background color of this component. 1853 * <p> 1854 * The background color affects each component differently and the 1855 * parts of the component that are affected by the background color 1856 * may differ between operating systems. 1857 * 1858 * @param c the color to become this component's color; 1859 * if this parameter is {@code null}, then this 1860 * component will inherit the background color of its parent 1861 * @see #getBackground 1862 * @since 1.0 1863 */ 1864 public void setBackground(Color c) { 1865 Color oldColor = background; 1866 ComponentPeer peer = this.peer; 1867 background = c; 1868 if (peer != null) { 1869 c = getBackground(); 1870 if (c != null) { 1871 peer.setBackground(c); 1872 } 1873 } 1874 // This is a bound property, so report the change to 1875 // any registered listeners. (Cheap if there are none.) 1876 firePropertyChange("background", oldColor, c); 1877 } 1878 1879 /** 1880 * Returns whether the background color has been explicitly set for this 1881 * Component. If this method returns {@code false}, this Component is 1882 * inheriting its background color from an ancestor. 1883 * 1884 * @return {@code true} if the background color has been explicitly 1885 * set for this Component; {@code false} otherwise. 1886 * @since 1.4 1887 */ 1888 public boolean isBackgroundSet() { 1889 return (background != null); 1890 } 1891 1892 /** 1893 * Gets the font of this component. 1894 * @return this component's font; if a font has not been set 1895 * for this component, the font of its parent is returned 1896 * @see #setFont 1897 * @since 1.0 1898 */ 1899 @Transient 1900 public Font getFont() { 1901 return getFont_NoClientCode(); 1902 } 1903 1904 // NOTE: This method may be called by privileged threads. 1905 // This functionality is implemented in a package-private method 1906 // to insure that it cannot be overridden by client subclasses. 1907 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 1908 final Font getFont_NoClientCode() { 1909 Font font = this.font; 1910 if (font != null) { 1911 return font; 1912 } 1913 Container parent = this.parent; 1914 return (parent != null) ? parent.getFont_NoClientCode() : null; 1915 } 1916 1917 /** 1918 * Sets the font of this component. 1919 * <p> 1920 * This method changes layout-related information, and therefore, 1921 * invalidates the component hierarchy. 1922 * 1923 * @param f the font to become this component's font; 1924 * if this parameter is {@code null} then this 1925 * component will inherit the font of its parent 1926 * @see #getFont 1927 * @see #invalidate 1928 * @since 1.0 1929 */ 1930 public void setFont(Font f) { 1931 Font oldFont, newFont; 1932 synchronized(getTreeLock()) { 1933 oldFont = font; 1934 newFont = font = f; 1935 ComponentPeer peer = this.peer; 1936 if (peer != null) { 1937 f = getFont(); 1938 if (f != null) { 1939 peer.setFont(f); 1940 peerFont = f; 1941 } 1942 } 1943 } 1944 // This is a bound property, so report the change to 1945 // any registered listeners. (Cheap if there are none.) 1946 firePropertyChange("font", oldFont, newFont); 1947 1948 // This could change the preferred size of the Component. 1949 // Fix for 6213660. Should compare old and new fonts and do not 1950 // call invalidate() if they are equal. 1951 if (f != oldFont && (oldFont == null || 1952 !oldFont.equals(f))) { 1953 invalidateIfValid(); 1954 } 1955 } 1956 1957 /** 1958 * Returns whether the font has been explicitly set for this Component. If 1959 * this method returns {@code false}, this Component is inheriting its 1960 * font from an ancestor. 1961 * 1962 * @return {@code true} if the font has been explicitly set for this 1963 * Component; {@code false} otherwise. 1964 * @since 1.4 1965 */ 1966 public boolean isFontSet() { 1967 return (font != null); 1968 } 1969 1970 /** 1971 * Gets the locale of this component. 1972 * @return this component's locale; if this component does not 1973 * have a locale, the locale of its parent is returned 1974 * @see #setLocale 1975 * @exception IllegalComponentStateException if the {@code Component} 1976 * does not have its own locale and has not yet been added to 1977 * a containment hierarchy such that the locale can be determined 1978 * from the containing parent 1979 * @since 1.1 1980 */ 1981 public Locale getLocale() { 1982 Locale locale = this.locale; 1983 if (locale != null) { 1984 return locale; 1985 } 1986 Container parent = this.parent; 1987 1988 if (parent == null) { 1989 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale"); 1990 } else { 1991 return parent.getLocale(); 1992 } 1993 } 1994 1995 /** 1996 * Sets the locale of this component. This is a bound property. 1997 * <p> 1998 * This method changes layout-related information, and therefore, 1999 * invalidates the component hierarchy. 2000 * 2001 * @param l the locale to become this component's locale 2002 * @see #getLocale 2003 * @see #invalidate 2004 * @since 1.1 2005 */ 2006 public void setLocale(Locale l) { 2007 Locale oldValue = locale; 2008 locale = l; 2009 2010 // This is a bound property, so report the change to 2011 // any registered listeners. (Cheap if there are none.) 2012 firePropertyChange("locale", oldValue, l); 2013 2014 // This could change the preferred size of the Component. 2015 invalidateIfValid(); 2016 } 2017 2018 /** 2019 * Gets the instance of {@code ColorModel} used to display 2020 * the component on the output device. 2021 * @return the color model used by this component 2022 * @see java.awt.image.ColorModel 2023 * @see java.awt.peer.ComponentPeer#getColorModel() 2024 * @see Toolkit#getColorModel() 2025 * @since 1.0 2026 */ 2027 public ColorModel getColorModel() { 2028 ComponentPeer peer = this.peer; 2029 if ((peer != null) && ! (peer instanceof LightweightPeer)) { 2030 return peer.getColorModel(); 2031 } else if (GraphicsEnvironment.isHeadless()) { 2032 return ColorModel.getRGBdefault(); 2033 } // else 2034 return getToolkit().getColorModel(); 2035 } 2036 2037 /** 2038 * Gets the location of this component in the form of a 2039 * point specifying the component's top-left corner. 2040 * The location will be relative to the parent's coordinate space. 2041 * <p> 2042 * Due to the asynchronous nature of native event handling, this 2043 * method can return outdated values (for instance, after several calls 2044 * of {@code setLocation()} in rapid succession). For this 2045 * reason, the recommended method of obtaining a component's position is 2046 * within {@code java.awt.event.ComponentListener.componentMoved()}, 2047 * which is called after the operating system has finished moving the 2048 * component. 2049 * </p> 2050 * @return an instance of {@code Point} representing 2051 * the top-left corner of the component's bounds in 2052 * the coordinate space of the component's parent 2053 * @see #setLocation 2054 * @see #getLocationOnScreen 2055 * @since 1.1 2056 */ 2057 public Point getLocation() { 2058 return location(); 2059 } 2060 2061 /** 2062 * Gets the location of this component in the form of a point 2063 * specifying the component's top-left corner in the screen's 2064 * coordinate space. 2065 * @return an instance of {@code Point} representing 2066 * the top-left corner of the component's bounds in the 2067 * coordinate space of the screen 2068 * @throws IllegalComponentStateException if the 2069 * component is not showing on the screen 2070 * @see #setLocation 2071 * @see #getLocation 2072 */ 2073 public Point getLocationOnScreen() { 2074 synchronized (getTreeLock()) { 2075 return getLocationOnScreen_NoTreeLock(); 2076 } 2077 } 2078 2079 /* 2080 * a package private version of getLocationOnScreen 2081 * used by GlobalCursormanager to update cursor 2082 */ 2083 final Point getLocationOnScreen_NoTreeLock() { 2084 ComponentPeer peer = this.peer; 2085 if (peer != null && isShowing()) { 2086 if (peer instanceof LightweightPeer) { 2087 // lightweight component location needs to be translated 2088 // relative to a native component. 2089 Container host = getNativeContainer(); 2090 Point pt = host.peer.getLocationOnScreen(); 2091 for(Component c = this; c != host; c = c.getContainer()) { 2092 pt.x += c.x; 2093 pt.y += c.y; 2094 } 2095 return pt; 2096 } else { 2097 Point pt = peer.getLocationOnScreen(); 2098 return pt; 2099 } 2100 } else { 2101 throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); 2102 } 2103 } 2104 2105 2106 /** 2107 * Returns the location of this component's top left corner. 2108 * 2109 * @return the location of this component's top left corner 2110 * @deprecated As of JDK version 1.1, 2111 * replaced by {@code getLocation()}. 2112 */ 2113 @Deprecated 2114 public Point location() { 2115 return location_NoClientCode(); 2116 } 2117 2118 private Point location_NoClientCode() { 2119 return new Point(x, y); 2120 } 2121 2122 /** 2123 * Moves this component to a new location. The top-left corner of 2124 * the new location is specified by the {@code x} and {@code y} 2125 * parameters in the coordinate space of this component's parent. 2126 * <p> 2127 * This method changes layout-related information, and therefore, 2128 * invalidates the component hierarchy. 2129 * 2130 * @param x the <i>x</i>-coordinate of the new location's 2131 * top-left corner in the parent's coordinate space 2132 * @param y the <i>y</i>-coordinate of the new location's 2133 * top-left corner in the parent's coordinate space 2134 * @see #getLocation 2135 * @see #setBounds 2136 * @see #invalidate 2137 * @since 1.1 2138 */ 2139 public void setLocation(int x, int y) { 2140 move(x, y); 2141 } 2142 2143 /** 2144 * Moves this component to a new location. 2145 * 2146 * @param x the <i>x</i>-coordinate of the new location's 2147 * top-left corner in the parent's coordinate space 2148 * @param y the <i>y</i>-coordinate of the new location's 2149 * top-left corner in the parent's coordinate space 2150 * 2151 * @deprecated As of JDK version 1.1, 2152 * replaced by {@code setLocation(int, int)}. 2153 */ 2154 @Deprecated 2155 public void move(int x, int y) { 2156 synchronized(getTreeLock()) { 2157 setBoundsOp(ComponentPeer.SET_LOCATION); 2158 setBounds(x, y, width, height); 2159 } 2160 } 2161 2162 /** 2163 * Moves this component to a new location. The top-left corner of 2164 * the new location is specified by point {@code p}. Point 2165 * {@code p} is given in the parent's coordinate space. 2166 * <p> 2167 * This method changes layout-related information, and therefore, 2168 * invalidates the component hierarchy. 2169 * 2170 * @param p the point defining the top-left corner 2171 * of the new location, given in the coordinate space of this 2172 * component's parent 2173 * @see #getLocation 2174 * @see #setBounds 2175 * @see #invalidate 2176 * @since 1.1 2177 */ 2178 public void setLocation(Point p) { 2179 setLocation(p.x, p.y); 2180 } 2181 2182 /** 2183 * Returns the size of this component in the form of a 2184 * {@code Dimension} object. The {@code height} 2185 * field of the {@code Dimension} object contains 2186 * this component's height, and the {@code width} 2187 * field of the {@code Dimension} object contains 2188 * this component's width. 2189 * @return a {@code Dimension} object that indicates the 2190 * size of this component 2191 * @see #setSize 2192 * @since 1.1 2193 */ 2194 public Dimension getSize() { 2195 return size(); 2196 } 2197 2198 /** 2199 * Returns the size of this component in the form of a 2200 * {@code Dimension} object. 2201 * 2202 * @return the {@code Dimension} object that indicates the 2203 * size of this component 2204 * @deprecated As of JDK version 1.1, 2205 * replaced by {@code getSize()}. 2206 */ 2207 @Deprecated 2208 public Dimension size() { 2209 return new Dimension(width, height); 2210 } 2211 2212 /** 2213 * Resizes this component so that it has width {@code width} 2214 * and height {@code height}. 2215 * <p> 2216 * This method changes layout-related information, and therefore, 2217 * invalidates the component hierarchy. 2218 * 2219 * @param width the new width of this component in pixels 2220 * @param height the new height of this component in pixels 2221 * @see #getSize 2222 * @see #setBounds 2223 * @see #invalidate 2224 * @since 1.1 2225 */ 2226 public void setSize(int width, int height) { 2227 resize(width, height); 2228 } 2229 2230 /** 2231 * Resizes this component. 2232 * 2233 * @param width the new width of the component 2234 * @param height the new height of the component 2235 * @deprecated As of JDK version 1.1, 2236 * replaced by {@code setSize(int, int)}. 2237 */ 2238 @Deprecated 2239 public void resize(int width, int height) { 2240 synchronized(getTreeLock()) { 2241 setBoundsOp(ComponentPeer.SET_SIZE); 2242 setBounds(x, y, width, height); 2243 } 2244 } 2245 2246 /** 2247 * Resizes this component so that it has width {@code d.width} 2248 * and height {@code d.height}. 2249 * <p> 2250 * This method changes layout-related information, and therefore, 2251 * invalidates the component hierarchy. 2252 * 2253 * @param d the dimension specifying the new size 2254 * of this component 2255 * @throws NullPointerException if {@code d} is {@code null} 2256 * @see #setSize 2257 * @see #setBounds 2258 * @see #invalidate 2259 * @since 1.1 2260 */ 2261 public void setSize(Dimension d) { 2262 resize(d); 2263 } 2264 2265 /** 2266 * Resizes this component so that it has width {@code d.width} 2267 * and height {@code d.height}. 2268 * 2269 * @param d the new size of this component 2270 * @deprecated As of JDK version 1.1, 2271 * replaced by {@code setSize(Dimension)}. 2272 */ 2273 @Deprecated 2274 public void resize(Dimension d) { 2275 setSize(d.width, d.height); 2276 } 2277 2278 /** 2279 * Gets the bounds of this component in the form of a 2280 * {@code Rectangle} object. The bounds specify this 2281 * component's width, height, and location relative to 2282 * its parent. 2283 * @return a rectangle indicating this component's bounds 2284 * @see #setBounds 2285 * @see #getLocation 2286 * @see #getSize 2287 */ 2288 public Rectangle getBounds() { 2289 return bounds(); 2290 } 2291 2292 /** 2293 * Returns the bounding rectangle of this component. 2294 * 2295 * @return the bounding rectangle for this component 2296 * @deprecated As of JDK version 1.1, 2297 * replaced by {@code getBounds()}. 2298 */ 2299 @Deprecated 2300 public Rectangle bounds() { 2301 return new Rectangle(x, y, width, height); 2302 } 2303 2304 /** 2305 * Moves and resizes this component. The new location of the top-left 2306 * corner is specified by {@code x} and {@code y}, and the 2307 * new size is specified by {@code width} and {@code height}. 2308 * <p> 2309 * This method changes layout-related information, and therefore, 2310 * invalidates the component hierarchy. 2311 * 2312 * @param x the new <i>x</i>-coordinate of this component 2313 * @param y the new <i>y</i>-coordinate of this component 2314 * @param width the new {@code width} of this component 2315 * @param height the new {@code height} of this 2316 * component 2317 * @see #getBounds 2318 * @see #setLocation(int, int) 2319 * @see #setLocation(Point) 2320 * @see #setSize(int, int) 2321 * @see #setSize(Dimension) 2322 * @see #invalidate 2323 * @since 1.1 2324 */ 2325 public void setBounds(int x, int y, int width, int height) { 2326 reshape(x, y, width, height); 2327 } 2328 2329 /** 2330 * Reshapes the bounding rectangle for this component. 2331 * 2332 * @param x the <i>x</i> coordinate of the upper left corner of the rectangle 2333 * @param y the <i>y</i> coordinate of the upper left corner of the rectangle 2334 * @param width the width of the rectangle 2335 * @param height the height of the rectangle 2336 * 2337 * @deprecated As of JDK version 1.1, 2338 * replaced by {@code setBounds(int, int, int, int)}. 2339 */ 2340 @Deprecated 2341 public void reshape(int x, int y, int width, int height) { 2342 synchronized (getTreeLock()) { 2343 try { 2344 setBoundsOp(ComponentPeer.SET_BOUNDS); 2345 boolean resized = (this.width != width) || (this.height != height); 2346 boolean moved = (this.x != x) || (this.y != y); 2347 if (!resized && !moved) { 2348 return; 2349 } 2350 int oldX = this.x; 2351 int oldY = this.y; 2352 int oldWidth = this.width; 2353 int oldHeight = this.height; 2354 this.x = x; 2355 this.y = y; 2356 this.width = width; 2357 this.height = height; 2358 2359 if (resized) { 2360 isPacked = false; 2361 } 2362 2363 boolean needNotify = true; 2364 mixOnReshaping(); 2365 if (peer != null) { 2366 // LightweightPeer is an empty stub so can skip peer.reshape 2367 if (!(peer instanceof LightweightPeer)) { 2368 reshapeNativePeer(x, y, width, height, getBoundsOp()); 2369 // Check peer actually changed coordinates 2370 resized = (oldWidth != this.width) || (oldHeight != this.height); 2371 moved = (oldX != this.x) || (oldY != this.y); 2372 // fix for 5025858: do not send ComponentEvents for toplevel 2373 // windows here as it is done from peer or native code when 2374 // the window is really resized or moved, otherwise some 2375 // events may be sent twice 2376 if (this instanceof Window) { 2377 needNotify = false; 2378 } 2379 } 2380 if (resized) { 2381 invalidate(); 2382 } 2383 if (parent != null) { 2384 parent.invalidateIfValid(); 2385 } 2386 } 2387 if (needNotify) { 2388 notifyNewBounds(resized, moved); 2389 } 2390 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight); 2391 } finally { 2392 setBoundsOp(ComponentPeer.RESET_OPERATION); 2393 } 2394 } 2395 } 2396 2397 private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth, 2398 int oldHeight) 2399 { 2400 if (parent != null && peer instanceof LightweightPeer && isShowing()) { 2401 // Have the parent redraw the area this component occupied. 2402 parent.repaint(oldX, oldY, oldWidth, oldHeight); 2403 // Have the parent redraw the area this component *now* occupies. 2404 repaint(); 2405 } 2406 } 2407 2408 private void reshapeNativePeer(int x, int y, int width, int height, int op) { 2409 // native peer might be offset by more than direct 2410 // parent since parent might be lightweight. 2411 int nativeX = x; 2412 int nativeY = y; 2413 for (Component c = parent; 2414 (c != null) && (c.peer instanceof LightweightPeer); 2415 c = c.parent) 2416 { 2417 nativeX += c.x; 2418 nativeY += c.y; 2419 } 2420 peer.setBounds(nativeX, nativeY, width, height, op); 2421 } 2422 2423 @SuppressWarnings("deprecation") 2424 private void notifyNewBounds(boolean resized, boolean moved) { 2425 if (componentListener != null 2426 || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 2427 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) 2428 { 2429 if (resized) { 2430 ComponentEvent e = new ComponentEvent(this, 2431 ComponentEvent.COMPONENT_RESIZED); 2432 Toolkit.getEventQueue().postEvent(e); 2433 } 2434 if (moved) { 2435 ComponentEvent e = new ComponentEvent(this, 2436 ComponentEvent.COMPONENT_MOVED); 2437 Toolkit.getEventQueue().postEvent(e); 2438 } 2439 } else { 2440 if (this instanceof Container && ((Container)this).countComponents() > 0) { 2441 boolean enabledOnToolkit = 2442 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); 2443 if (resized) { 2444 2445 ((Container)this).createChildHierarchyEvents( 2446 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit); 2447 } 2448 if (moved) { 2449 ((Container)this).createChildHierarchyEvents( 2450 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit); 2451 } 2452 } 2453 } 2454 } 2455 2456 /** 2457 * Moves and resizes this component to conform to the new 2458 * bounding rectangle {@code r}. This component's new 2459 * position is specified by {@code r.x} and {@code r.y}, 2460 * and its new size is specified by {@code r.width} and 2461 * {@code r.height} 2462 * <p> 2463 * This method changes layout-related information, and therefore, 2464 * invalidates the component hierarchy. 2465 * 2466 * @param r the new bounding rectangle for this component 2467 * @throws NullPointerException if {@code r} is {@code null} 2468 * @see #getBounds 2469 * @see #setLocation(int, int) 2470 * @see #setLocation(Point) 2471 * @see #setSize(int, int) 2472 * @see #setSize(Dimension) 2473 * @see #invalidate 2474 * @since 1.1 2475 */ 2476 public void setBounds(Rectangle r) { 2477 setBounds(r.x, r.y, r.width, r.height); 2478 } 2479 2480 2481 /** 2482 * Returns the current x coordinate of the components origin. 2483 * This method is preferable to writing 2484 * {@code component.getBounds().x}, 2485 * or {@code component.getLocation().x} because it doesn't 2486 * cause any heap allocations. 2487 * 2488 * @return the current x coordinate of the components origin 2489 * @since 1.2 2490 */ 2491 public int getX() { 2492 return x; 2493 } 2494 2495 2496 /** 2497 * Returns the current y coordinate of the components origin. 2498 * This method is preferable to writing 2499 * {@code component.getBounds().y}, 2500 * or {@code component.getLocation().y} because it 2501 * doesn't cause any heap allocations. 2502 * 2503 * @return the current y coordinate of the components origin 2504 * @since 1.2 2505 */ 2506 public int getY() { 2507 return y; 2508 } 2509 2510 2511 /** 2512 * Returns the current width of this component. 2513 * This method is preferable to writing 2514 * {@code component.getBounds().width}, 2515 * or {@code component.getSize().width} because it 2516 * doesn't cause any heap allocations. 2517 * 2518 * @return the current width of this component 2519 * @since 1.2 2520 */ 2521 public int getWidth() { 2522 return width; 2523 } 2524 2525 2526 /** 2527 * Returns the current height of this component. 2528 * This method is preferable to writing 2529 * {@code component.getBounds().height}, 2530 * or {@code component.getSize().height} because it 2531 * doesn't cause any heap allocations. 2532 * 2533 * @return the current height of this component 2534 * @since 1.2 2535 */ 2536 public int getHeight() { 2537 return height; 2538 } 2539 2540 /** 2541 * Stores the bounds of this component into "return value" <b>rv</b> and 2542 * return <b>rv</b>. If rv is {@code null} a new 2543 * {@code Rectangle} is allocated. 2544 * This version of {@code getBounds} is useful if the caller 2545 * wants to avoid allocating a new {@code Rectangle} object 2546 * on the heap. 2547 * 2548 * @param rv the return value, modified to the components bounds 2549 * @return rv 2550 */ 2551 public Rectangle getBounds(Rectangle rv) { 2552 if (rv == null) { 2553 return new Rectangle(getX(), getY(), getWidth(), getHeight()); 2554 } 2555 else { 2556 rv.setBounds(getX(), getY(), getWidth(), getHeight()); 2557 return rv; 2558 } 2559 } 2560 2561 /** 2562 * Stores the width/height of this component into "return value" <b>rv</b> 2563 * and return <b>rv</b>. If rv is {@code null} a new 2564 * {@code Dimension} object is allocated. This version of 2565 * {@code getSize} is useful if the caller wants to avoid 2566 * allocating a new {@code Dimension} object on the heap. 2567 * 2568 * @param rv the return value, modified to the components size 2569 * @return rv 2570 */ 2571 public Dimension getSize(Dimension rv) { 2572 if (rv == null) { 2573 return new Dimension(getWidth(), getHeight()); 2574 } 2575 else { 2576 rv.setSize(getWidth(), getHeight()); 2577 return rv; 2578 } 2579 } 2580 2581 /** 2582 * Stores the x,y origin of this component into "return value" <b>rv</b> 2583 * and return <b>rv</b>. If rv is {@code null} a new 2584 * {@code Point} is allocated. 2585 * This version of {@code getLocation} is useful if the 2586 * caller wants to avoid allocating a new {@code Point} 2587 * object on the heap. 2588 * 2589 * @param rv the return value, modified to the components location 2590 * @return rv 2591 */ 2592 public Point getLocation(Point rv) { 2593 if (rv == null) { 2594 return new Point(getX(), getY()); 2595 } 2596 else { 2597 rv.setLocation(getX(), getY()); 2598 return rv; 2599 } 2600 } 2601 2602 /** 2603 * Returns true if this component is completely opaque, returns 2604 * false by default. 2605 * <p> 2606 * An opaque component paints every pixel within its 2607 * rectangular region. A non-opaque component paints only some of 2608 * its pixels, allowing the pixels underneath it to "show through". 2609 * A component that does not fully paint its pixels therefore 2610 * provides a degree of transparency. 2611 * <p> 2612 * Subclasses that guarantee to always completely paint their 2613 * contents should override this method and return true. 2614 * 2615 * @return true if this component is completely opaque 2616 * @see #isLightweight 2617 * @since 1.2 2618 */ 2619 public boolean isOpaque() { 2620 if (peer == null) { 2621 return false; 2622 } 2623 else { 2624 return !isLightweight(); 2625 } 2626 } 2627 2628 2629 /** 2630 * A lightweight component doesn't have a native toolkit peer. 2631 * Subclasses of {@code Component} and {@code Container}, 2632 * other than the ones defined in this package like {@code Button} 2633 * or {@code Scrollbar}, are lightweight. 2634 * All of the Swing components are lightweights. 2635 * <p> 2636 * This method will always return {@code false} if this component 2637 * is not displayable because it is impossible to determine the 2638 * weight of an undisplayable component. 2639 * 2640 * @return true if this component has a lightweight peer; false if 2641 * it has a native peer or no peer 2642 * @see #isDisplayable 2643 * @since 1.2 2644 */ 2645 public boolean isLightweight() { 2646 return peer instanceof LightweightPeer; 2647 } 2648 2649 2650 /** 2651 * Sets the preferred size of this component to a constant 2652 * value. Subsequent calls to {@code getPreferredSize} will always 2653 * return this value. Setting the preferred size to {@code null} 2654 * restores the default behavior. 2655 * 2656 * @param preferredSize The new preferred size, or null 2657 * @see #getPreferredSize 2658 * @see #isPreferredSizeSet 2659 * @since 1.5 2660 */ 2661 public void setPreferredSize(Dimension preferredSize) { 2662 Dimension old; 2663 // If the preferred size was set, use it as the old value, otherwise 2664 // use null to indicate we didn't previously have a set preferred 2665 // size. 2666 if (prefSizeSet) { 2667 old = this.prefSize; 2668 } 2669 else { 2670 old = null; 2671 } 2672 this.prefSize = preferredSize; 2673 prefSizeSet = (preferredSize != null); 2674 firePropertyChange("preferredSize", old, preferredSize); 2675 } 2676 2677 2678 /** 2679 * Returns true if the preferred size has been set to a 2680 * non-{@code null} value otherwise returns false. 2681 * 2682 * @return true if {@code setPreferredSize} has been invoked 2683 * with a non-null value. 2684 * @since 1.5 2685 */ 2686 public boolean isPreferredSizeSet() { 2687 return prefSizeSet; 2688 } 2689 2690 2691 /** 2692 * Gets the preferred size of this component. 2693 * @return a dimension object indicating this component's preferred size 2694 * @see #getMinimumSize 2695 * @see LayoutManager 2696 */ 2697 public Dimension getPreferredSize() { 2698 return preferredSize(); 2699 } 2700 2701 2702 /** 2703 * Returns the component's preferred size. 2704 * 2705 * @return the component's preferred size 2706 * @deprecated As of JDK version 1.1, 2707 * replaced by {@code getPreferredSize()}. 2708 */ 2709 @Deprecated 2710 public Dimension preferredSize() { 2711 /* Avoid grabbing the lock if a reasonable cached size value 2712 * is available. 2713 */ 2714 Dimension dim = prefSize; 2715 if (dim == null || !(isPreferredSizeSet() || isValid())) { 2716 synchronized (getTreeLock()) { 2717 prefSize = (peer != null) ? 2718 peer.getPreferredSize() : 2719 getMinimumSize(); 2720 dim = prefSize; 2721 } 2722 } 2723 return new Dimension(dim); 2724 } 2725 2726 /** 2727 * Sets the minimum size of this component to a constant 2728 * value. Subsequent calls to {@code getMinimumSize} will always 2729 * return this value. Setting the minimum size to {@code null} 2730 * restores the default behavior. 2731 * 2732 * @param minimumSize the new minimum size of this component 2733 * @see #getMinimumSize 2734 * @see #isMinimumSizeSet 2735 * @since 1.5 2736 */ 2737 public void setMinimumSize(Dimension minimumSize) { 2738 Dimension old; 2739 // If the minimum size was set, use it as the old value, otherwise 2740 // use null to indicate we didn't previously have a set minimum 2741 // size. 2742 if (minSizeSet) { 2743 old = this.minSize; 2744 } 2745 else { 2746 old = null; 2747 } 2748 this.minSize = minimumSize; 2749 minSizeSet = (minimumSize != null); 2750 firePropertyChange("minimumSize", old, minimumSize); 2751 } 2752 2753 /** 2754 * Returns whether or not {@code setMinimumSize} has been 2755 * invoked with a non-null value. 2756 * 2757 * @return true if {@code setMinimumSize} has been invoked with a 2758 * non-null value. 2759 * @since 1.5 2760 */ 2761 public boolean isMinimumSizeSet() { 2762 return minSizeSet; 2763 } 2764 2765 /** 2766 * Gets the minimum size of this component. 2767 * @return a dimension object indicating this component's minimum size 2768 * @see #getPreferredSize 2769 * @see LayoutManager 2770 */ 2771 public Dimension getMinimumSize() { 2772 return minimumSize(); 2773 } 2774 2775 /** 2776 * Returns the minimum size of this component. 2777 * 2778 * @return the minimum size of this component 2779 * @deprecated As of JDK version 1.1, 2780 * replaced by {@code getMinimumSize()}. 2781 */ 2782 @Deprecated 2783 public Dimension minimumSize() { 2784 /* Avoid grabbing the lock if a reasonable cached size value 2785 * is available. 2786 */ 2787 Dimension dim = minSize; 2788 if (dim == null || !(isMinimumSizeSet() || isValid())) { 2789 synchronized (getTreeLock()) { 2790 minSize = (peer != null) ? 2791 peer.getMinimumSize() : 2792 size(); 2793 dim = minSize; 2794 } 2795 } 2796 return new Dimension(dim); 2797 } 2798 2799 /** 2800 * Sets the maximum size of this component to a constant 2801 * value. Subsequent calls to {@code getMaximumSize} will always 2802 * return this value. Setting the maximum size to {@code null} 2803 * restores the default behavior. 2804 * 2805 * @param maximumSize a {@code Dimension} containing the 2806 * desired maximum allowable size 2807 * @see #getMaximumSize 2808 * @see #isMaximumSizeSet 2809 * @since 1.5 2810 */ 2811 public void setMaximumSize(Dimension maximumSize) { 2812 // If the maximum size was set, use it as the old value, otherwise 2813 // use null to indicate we didn't previously have a set maximum 2814 // size. 2815 Dimension old; 2816 if (maxSizeSet) { 2817 old = this.maxSize; 2818 } 2819 else { 2820 old = null; 2821 } 2822 this.maxSize = maximumSize; 2823 maxSizeSet = (maximumSize != null); 2824 firePropertyChange("maximumSize", old, maximumSize); 2825 } 2826 2827 /** 2828 * Returns true if the maximum size has been set to a non-{@code null} 2829 * value otherwise returns false. 2830 * 2831 * @return true if {@code maximumSize} is non-{@code null}, 2832 * false otherwise 2833 * @since 1.5 2834 */ 2835 public boolean isMaximumSizeSet() { 2836 return maxSizeSet; 2837 } 2838 2839 /** 2840 * Gets the maximum size of this component. 2841 * @return a dimension object indicating this component's maximum size 2842 * @see #getMinimumSize 2843 * @see #getPreferredSize 2844 * @see LayoutManager 2845 */ 2846 public Dimension getMaximumSize() { 2847 if (isMaximumSizeSet()) { 2848 return new Dimension(maxSize); 2849 } 2850 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); 2851 } 2852 2853 /** 2854 * Returns the alignment along the x axis. This specifies how 2855 * the component would like to be aligned relative to other 2856 * components. The value should be a number between 0 and 1 2857 * where 0 represents alignment along the origin, 1 is aligned 2858 * the furthest away from the origin, 0.5 is centered, etc. 2859 * 2860 * @return the horizontal alignment of this component 2861 */ 2862 public float getAlignmentX() { 2863 return CENTER_ALIGNMENT; 2864 } 2865 2866 /** 2867 * Returns the alignment along the y axis. This specifies how 2868 * the component would like to be aligned relative to other 2869 * components. The value should be a number between 0 and 1 2870 * where 0 represents alignment along the origin, 1 is aligned 2871 * the furthest away from the origin, 0.5 is centered, etc. 2872 * 2873 * @return the vertical alignment of this component 2874 */ 2875 public float getAlignmentY() { 2876 return CENTER_ALIGNMENT; 2877 } 2878 2879 /** 2880 * Returns the baseline. The baseline is measured from the top of 2881 * the component. This method is primarily meant for 2882 * {@code LayoutManager}s to align components along their 2883 * baseline. A return value less than 0 indicates this component 2884 * does not have a reasonable baseline and that 2885 * {@code LayoutManager}s should not align this component on 2886 * its baseline. 2887 * <p> 2888 * The default implementation returns -1. Subclasses that support 2889 * baseline should override appropriately. If a value >= 0 is 2890 * returned, then the component has a valid baseline for any 2891 * size >= the minimum size and {@code getBaselineResizeBehavior} 2892 * can be used to determine how the baseline changes with size. 2893 * 2894 * @param width the width to get the baseline for 2895 * @param height the height to get the baseline for 2896 * @return the baseline or < 0 indicating there is no reasonable 2897 * baseline 2898 * @throws IllegalArgumentException if width or height is < 0 2899 * @see #getBaselineResizeBehavior 2900 * @see java.awt.FontMetrics 2901 * @since 1.6 2902 */ 2903 public int getBaseline(int width, int height) { 2904 if (width < 0 || height < 0) { 2905 throw new IllegalArgumentException( 2906 "Width and height must be >= 0"); 2907 } 2908 return -1; 2909 } 2910 2911 /** 2912 * Returns an enum indicating how the baseline of the component 2913 * changes as the size changes. This method is primarily meant for 2914 * layout managers and GUI builders. 2915 * <p> 2916 * The default implementation returns 2917 * {@code BaselineResizeBehavior.OTHER}. Subclasses that have a 2918 * baseline should override appropriately. Subclasses should 2919 * never return {@code null}; if the baseline can not be 2920 * calculated return {@code BaselineResizeBehavior.OTHER}. Callers 2921 * should first ask for the baseline using 2922 * {@code getBaseline} and if a value >= 0 is returned use 2923 * this method. It is acceptable for this method to return a 2924 * value other than {@code BaselineResizeBehavior.OTHER} even if 2925 * {@code getBaseline} returns a value less than 0. 2926 * 2927 * @return an enum indicating how the baseline changes as the component 2928 * size changes 2929 * @see #getBaseline(int, int) 2930 * @since 1.6 2931 */ 2932 public BaselineResizeBehavior getBaselineResizeBehavior() { 2933 return BaselineResizeBehavior.OTHER; 2934 } 2935 2936 /** 2937 * Prompts the layout manager to lay out this component. This is 2938 * usually called when the component (more specifically, container) 2939 * is validated. 2940 * @see #validate 2941 * @see LayoutManager 2942 */ 2943 public void doLayout() { 2944 layout(); 2945 } 2946 2947 /** 2948 * @deprecated As of JDK version 1.1, 2949 * replaced by {@code doLayout()}. 2950 */ 2951 @Deprecated 2952 public void layout() { 2953 } 2954 2955 /** 2956 * Validates this component. 2957 * <p> 2958 * The meaning of the term <i>validating</i> is defined by the ancestors of 2959 * this class. See {@link Container#validate} for more details. 2960 * 2961 * @see #invalidate 2962 * @see #doLayout() 2963 * @see LayoutManager 2964 * @see Container#validate 2965 * @since 1.0 2966 */ 2967 public void validate() { 2968 synchronized (getTreeLock()) { 2969 ComponentPeer peer = this.peer; 2970 boolean wasValid = isValid(); 2971 if (!wasValid && peer != null) { 2972 Font newfont = getFont(); 2973 Font oldfont = peerFont; 2974 if (newfont != oldfont && (oldfont == null 2975 || !oldfont.equals(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 protected AccessibleContext accessibleContext = null; 9297 9298 /** 9299 * Gets the {@code AccessibleContext} associated 9300 * with this {@code Component}. 9301 * The method implemented by this base 9302 * class returns null. Classes that extend {@code Component} 9303 * should implement this method to return the 9304 * {@code AccessibleContext} associated with the subclass. 9305 * 9306 * 9307 * @return the {@code AccessibleContext} of this 9308 * {@code Component} 9309 * @since 1.3 9310 */ 9311 public AccessibleContext getAccessibleContext() { 9312 return accessibleContext; 9313 } 9314 9315 /** 9316 * Inner class of Component used to provide default support for 9317 * accessibility. This class is not meant to be used directly by 9318 * application developers, but is instead meant only to be 9319 * subclassed by component developers. 9320 * <p> 9321 * The class used to obtain the accessible role for this object. 9322 * @since 1.3 9323 */ 9324 protected abstract class AccessibleAWTComponent extends AccessibleContext 9325 implements Serializable, AccessibleComponent { 9326 9327 private static final long serialVersionUID = 642321655757800191L; 9328 9329 /** 9330 * Though the class is abstract, this should be called by 9331 * all sub-classes. 9332 */ 9333 protected AccessibleAWTComponent() { 9334 } 9335 9336 /** 9337 * Number of PropertyChangeListener objects registered. It's used 9338 * to add/remove ComponentListener and FocusListener to track 9339 * target Component's state. 9340 */ 9341 private transient volatile int propertyListenersCount = 0; 9342 9343 /** 9344 * A component listener to track show/hide/resize events 9345 * and convert them to PropertyChange events. 9346 */ 9347 protected ComponentListener accessibleAWTComponentHandler = null; 9348 9349 /** 9350 * A listener to track focus events 9351 * and convert them to PropertyChange events. 9352 */ 9353 protected FocusListener accessibleAWTFocusHandler = null; 9354 9355 /** 9356 * Fire PropertyChange listener, if one is registered, 9357 * when shown/hidden.. 9358 * @since 1.3 9359 */ 9360 protected class AccessibleAWTComponentHandler implements ComponentListener, Serializable { 9361 private static final long serialVersionUID = -1009684107426231869L; 9362 9363 public void componentHidden(ComponentEvent e) { 9364 if (accessibleContext != null) { 9365 accessibleContext.firePropertyChange( 9366 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9367 AccessibleState.VISIBLE, null); 9368 } 9369 } 9370 9371 public void componentShown(ComponentEvent e) { 9372 if (accessibleContext != null) { 9373 accessibleContext.firePropertyChange( 9374 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9375 null, AccessibleState.VISIBLE); 9376 } 9377 } 9378 9379 public void componentMoved(ComponentEvent e) { 9380 } 9381 9382 public void componentResized(ComponentEvent e) { 9383 } 9384 } // inner class AccessibleAWTComponentHandler 9385 9386 9387 /** 9388 * Fire PropertyChange listener, if one is registered, 9389 * when focus events happen 9390 * @since 1.3 9391 */ 9392 protected class AccessibleAWTFocusHandler implements FocusListener, Serializable { 9393 private static final long serialVersionUID = 3150908257351582233L; 9394 9395 public void focusGained(FocusEvent event) { 9396 if (accessibleContext != null) { 9397 accessibleContext.firePropertyChange( 9398 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9399 null, AccessibleState.FOCUSED); 9400 } 9401 } 9402 public void focusLost(FocusEvent event) { 9403 if (accessibleContext != null) { 9404 accessibleContext.firePropertyChange( 9405 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9406 AccessibleState.FOCUSED, null); 9407 } 9408 } 9409 } // inner class AccessibleAWTFocusHandler 9410 9411 9412 /** 9413 * Adds a {@code PropertyChangeListener} to the listener list. 9414 * 9415 * @param listener the property change listener to be added 9416 */ 9417 public void addPropertyChangeListener(PropertyChangeListener listener) { 9418 if (accessibleAWTComponentHandler == null) { 9419 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler(); 9420 } 9421 if (accessibleAWTFocusHandler == null) { 9422 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler(); 9423 } 9424 if (propertyListenersCount++ == 0) { 9425 Component.this.addComponentListener(accessibleAWTComponentHandler); 9426 Component.this.addFocusListener(accessibleAWTFocusHandler); 9427 } 9428 super.addPropertyChangeListener(listener); 9429 } 9430 9431 /** 9432 * Remove a PropertyChangeListener from the listener list. 9433 * This removes a PropertyChangeListener that was registered 9434 * for all properties. 9435 * 9436 * @param listener The PropertyChangeListener to be removed 9437 */ 9438 public void removePropertyChangeListener(PropertyChangeListener listener) { 9439 if (--propertyListenersCount == 0) { 9440 Component.this.removeComponentListener(accessibleAWTComponentHandler); 9441 Component.this.removeFocusListener(accessibleAWTFocusHandler); 9442 } 9443 super.removePropertyChangeListener(listener); 9444 } 9445 9446 // AccessibleContext methods 9447 // 9448 /** 9449 * Gets the accessible name of this object. This should almost never 9450 * return {@code java.awt.Component.getName()}, 9451 * as that generally isn't a localized name, 9452 * and doesn't have meaning for the user. If the 9453 * object is fundamentally a text object (e.g. a menu item), the 9454 * accessible name should be the text of the object (e.g. "save"). 9455 * If the object has a tooltip, the tooltip text may also be an 9456 * appropriate String to return. 9457 * 9458 * @return the localized name of the object -- can be 9459 * {@code null} if this 9460 * object does not have a name 9461 * @see javax.accessibility.AccessibleContext#setAccessibleName 9462 */ 9463 public String getAccessibleName() { 9464 return accessibleName; 9465 } 9466 9467 /** 9468 * Gets the accessible description of this object. This should be 9469 * a concise, localized description of what this object is - what 9470 * is its meaning to the user. If the object has a tooltip, the 9471 * tooltip text may be an appropriate string to return, assuming 9472 * it contains a concise description of the object (instead of just 9473 * the name of the object - e.g. a "Save" icon on a toolbar that 9474 * had "save" as the tooltip text shouldn't return the tooltip 9475 * text as the description, but something like "Saves the current 9476 * text document" instead). 9477 * 9478 * @return the localized description of the object -- can be 9479 * {@code null} if this object does not have a description 9480 * @see javax.accessibility.AccessibleContext#setAccessibleDescription 9481 */ 9482 public String getAccessibleDescription() { 9483 return accessibleDescription; 9484 } 9485 9486 /** 9487 * Gets the role of this object. 9488 * 9489 * @return an instance of {@code AccessibleRole} 9490 * describing the role of the object 9491 * @see javax.accessibility.AccessibleRole 9492 */ 9493 public AccessibleRole getAccessibleRole() { 9494 return AccessibleRole.AWT_COMPONENT; 9495 } 9496 9497 /** 9498 * Gets the state of this object. 9499 * 9500 * @return an instance of {@code AccessibleStateSet} 9501 * containing the current state set of the object 9502 * @see javax.accessibility.AccessibleState 9503 */ 9504 public AccessibleStateSet getAccessibleStateSet() { 9505 return Component.this.getAccessibleStateSet(); 9506 } 9507 9508 /** 9509 * Gets the {@code Accessible} parent of this object. 9510 * If the parent of this object implements {@code Accessible}, 9511 * this method should simply return {@code getParent}. 9512 * 9513 * @return the {@code Accessible} parent of this 9514 * object -- can be {@code null} if this 9515 * object does not have an {@code Accessible} parent 9516 */ 9517 public Accessible getAccessibleParent() { 9518 if (accessibleParent != null) { 9519 return accessibleParent; 9520 } else { 9521 Container parent = getParent(); 9522 if (parent instanceof Accessible) { 9523 return (Accessible) parent; 9524 } 9525 } 9526 return null; 9527 } 9528 9529 /** 9530 * Gets the index of this object in its accessible parent. 9531 * 9532 * @return the index of this object in its parent; or -1 if this 9533 * object does not have an accessible parent 9534 * @see #getAccessibleParent 9535 */ 9536 public int getAccessibleIndexInParent() { 9537 return Component.this.getAccessibleIndexInParent(); 9538 } 9539 9540 /** 9541 * Returns the number of accessible children in the object. If all 9542 * of the children of this object implement {@code Accessible}, 9543 * then this method should return the number of children of this object. 9544 * 9545 * @return the number of accessible children in the object 9546 */ 9547 public int getAccessibleChildrenCount() { 9548 return 0; // Components don't have children 9549 } 9550 9551 /** 9552 * Returns the nth {@code Accessible} child of the object. 9553 * 9554 * @param i zero-based index of child 9555 * @return the nth {@code Accessible} child of the object 9556 */ 9557 public Accessible getAccessibleChild(int i) { 9558 return null; // Components don't have children 9559 } 9560 9561 /** 9562 * Returns the locale of this object. 9563 * 9564 * @return the locale of this object 9565 */ 9566 public Locale getLocale() { 9567 return Component.this.getLocale(); 9568 } 9569 9570 /** 9571 * Gets the {@code AccessibleComponent} associated 9572 * with this object if one exists. 9573 * Otherwise return {@code null}. 9574 * 9575 * @return the component 9576 */ 9577 public AccessibleComponent getAccessibleComponent() { 9578 return this; 9579 } 9580 9581 9582 // AccessibleComponent methods 9583 // 9584 /** 9585 * Gets the background color of this object. 9586 * 9587 * @return the background color, if supported, of the object; 9588 * otherwise, {@code null} 9589 */ 9590 public Color getBackground() { 9591 return Component.this.getBackground(); 9592 } 9593 9594 /** 9595 * Sets the background color of this object. 9596 * (For transparency, see {@code isOpaque}.) 9597 * 9598 * @param c the new {@code Color} for the background 9599 * @see Component#isOpaque 9600 */ 9601 public void setBackground(Color c) { 9602 Component.this.setBackground(c); 9603 } 9604 9605 /** 9606 * Gets the foreground color of this object. 9607 * 9608 * @return the foreground color, if supported, of the object; 9609 * otherwise, {@code null} 9610 */ 9611 public Color getForeground() { 9612 return Component.this.getForeground(); 9613 } 9614 9615 /** 9616 * Sets the foreground color of this object. 9617 * 9618 * @param c the new {@code Color} for the foreground 9619 */ 9620 public void setForeground(Color c) { 9621 Component.this.setForeground(c); 9622 } 9623 9624 /** 9625 * Gets the {@code Cursor} of this object. 9626 * 9627 * @return the {@code Cursor}, if supported, 9628 * of the object; otherwise, {@code null} 9629 */ 9630 public Cursor getCursor() { 9631 return Component.this.getCursor(); 9632 } 9633 9634 /** 9635 * Sets the {@code Cursor} of this object. 9636 * <p> 9637 * The method may have no visual effect if the Java platform 9638 * implementation and/or the native system do not support 9639 * changing the mouse cursor shape. 9640 * @param cursor the new {@code Cursor} for the object 9641 */ 9642 public void setCursor(Cursor cursor) { 9643 Component.this.setCursor(cursor); 9644 } 9645 9646 /** 9647 * Gets the {@code Font} of this object. 9648 * 9649 * @return the {@code Font}, if supported, 9650 * for the object; otherwise, {@code null} 9651 */ 9652 public Font getFont() { 9653 return Component.this.getFont(); 9654 } 9655 9656 /** 9657 * Sets the {@code Font} of this object. 9658 * 9659 * @param f the new {@code Font} for the object 9660 */ 9661 public void setFont(Font f) { 9662 Component.this.setFont(f); 9663 } 9664 9665 /** 9666 * Gets the {@code FontMetrics} of this object. 9667 * 9668 * @param f the {@code Font} 9669 * @return the {@code FontMetrics}, if supported, 9670 * the object; otherwise, {@code null} 9671 * @see #getFont 9672 */ 9673 public FontMetrics getFontMetrics(Font f) { 9674 if (f == null) { 9675 return null; 9676 } else { 9677 return Component.this.getFontMetrics(f); 9678 } 9679 } 9680 9681 /** 9682 * Determines if the object is enabled. 9683 * 9684 * @return true if object is enabled; otherwise, false 9685 */ 9686 public boolean isEnabled() { 9687 return Component.this.isEnabled(); 9688 } 9689 9690 /** 9691 * Sets the enabled state of the object. 9692 * 9693 * @param b if true, enables this object; otherwise, disables it 9694 */ 9695 public void setEnabled(boolean b) { 9696 boolean old = Component.this.isEnabled(); 9697 Component.this.setEnabled(b); 9698 if (b != old) { 9699 if (accessibleContext != null) { 9700 if (b) { 9701 accessibleContext.firePropertyChange( 9702 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9703 null, AccessibleState.ENABLED); 9704 } else { 9705 accessibleContext.firePropertyChange( 9706 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9707 AccessibleState.ENABLED, null); 9708 } 9709 } 9710 } 9711 } 9712 9713 /** 9714 * Determines if the object is visible. Note: this means that the 9715 * object intends to be visible; however, it may not in fact be 9716 * showing on the screen because one of the objects that this object 9717 * is contained by is not visible. To determine if an object is 9718 * showing on the screen, use {@code isShowing}. 9719 * 9720 * @return true if object is visible; otherwise, false 9721 */ 9722 public boolean isVisible() { 9723 return Component.this.isVisible(); 9724 } 9725 9726 /** 9727 * Sets the visible state of the object. 9728 * 9729 * @param b if true, shows this object; otherwise, hides it 9730 */ 9731 public void setVisible(boolean b) { 9732 boolean old = Component.this.isVisible(); 9733 Component.this.setVisible(b); 9734 if (b != old) { 9735 if (accessibleContext != null) { 9736 if (b) { 9737 accessibleContext.firePropertyChange( 9738 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9739 null, AccessibleState.VISIBLE); 9740 } else { 9741 accessibleContext.firePropertyChange( 9742 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9743 AccessibleState.VISIBLE, null); 9744 } 9745 } 9746 } 9747 } 9748 9749 /** 9750 * Determines if the object is showing. This is determined by checking 9751 * the visibility of the object and ancestors of the object. Note: 9752 * this will return true even if the object is obscured by another 9753 * (for example, it happens to be underneath a menu that was pulled 9754 * down). 9755 * 9756 * @return true if object is showing; otherwise, false 9757 */ 9758 public boolean isShowing() { 9759 return Component.this.isShowing(); 9760 } 9761 9762 /** 9763 * Checks whether the specified point is within this object's bounds, 9764 * where the point's x and y coordinates are defined to be relative to 9765 * the coordinate system of the object. 9766 * 9767 * @param p the {@code Point} relative to the 9768 * coordinate system of the object 9769 * @return true if object contains {@code Point}; otherwise false 9770 */ 9771 public boolean contains(Point p) { 9772 return Component.this.contains(p); 9773 } 9774 9775 /** 9776 * Returns the location of the object on the screen. 9777 * 9778 * @return location of object on screen -- can be 9779 * {@code null} if this object is not on the screen 9780 */ 9781 public Point getLocationOnScreen() { 9782 synchronized (Component.this.getTreeLock()) { 9783 if (Component.this.isShowing()) { 9784 return Component.this.getLocationOnScreen(); 9785 } else { 9786 return null; 9787 } 9788 } 9789 } 9790 9791 /** 9792 * Gets the location of the object relative to the parent in the form 9793 * of a point specifying the object's top-left corner in the screen's 9794 * coordinate space. 9795 * 9796 * @return an instance of Point representing the top-left corner of 9797 * the object's bounds in the coordinate space of the screen; 9798 * {@code null} if this object or its parent are not on the screen 9799 */ 9800 public Point getLocation() { 9801 return Component.this.getLocation(); 9802 } 9803 9804 /** 9805 * Sets the location of the object relative to the parent. 9806 * @param p the coordinates of the object 9807 */ 9808 public void setLocation(Point p) { 9809 Component.this.setLocation(p); 9810 } 9811 9812 /** 9813 * Gets the bounds of this object in the form of a Rectangle object. 9814 * The bounds specify this object's width, height, and location 9815 * relative to its parent. 9816 * 9817 * @return a rectangle indicating this component's bounds; 9818 * {@code null} if this object is not on the screen 9819 */ 9820 public Rectangle getBounds() { 9821 return Component.this.getBounds(); 9822 } 9823 9824 /** 9825 * Sets the bounds of this object in the form of a 9826 * {@code Rectangle} object. 9827 * The bounds specify this object's width, height, and location 9828 * relative to its parent. 9829 * 9830 * @param r a rectangle indicating this component's bounds 9831 */ 9832 public void setBounds(Rectangle r) { 9833 Component.this.setBounds(r); 9834 } 9835 9836 /** 9837 * Returns the size of this object in the form of a 9838 * {@code Dimension} object. The height field of the 9839 * {@code Dimension} object contains this object's 9840 * height, and the width field of the {@code Dimension} 9841 * object contains this object's width. 9842 * 9843 * @return a {@code Dimension} object that indicates 9844 * the size of this component; {@code null} if 9845 * this object is not on the screen 9846 */ 9847 public Dimension getSize() { 9848 return Component.this.getSize(); 9849 } 9850 9851 /** 9852 * Resizes this object so that it has width and height. 9853 * 9854 * @param d the dimension specifying the new size of the object 9855 */ 9856 public void setSize(Dimension d) { 9857 Component.this.setSize(d); 9858 } 9859 9860 /** 9861 * Returns the {@code Accessible} child, 9862 * if one exists, contained at the local 9863 * coordinate {@code Point}. Otherwise returns 9864 * {@code null}. 9865 * 9866 * @param p the point defining the top-left corner of 9867 * the {@code Accessible}, given in the 9868 * coordinate space of the object's parent 9869 * @return the {@code Accessible}, if it exists, 9870 * at the specified location; else {@code null} 9871 */ 9872 public Accessible getAccessibleAt(Point p) { 9873 return null; // Components don't have children 9874 } 9875 9876 /** 9877 * Returns whether this object can accept focus or not. 9878 * 9879 * @return true if object can accept focus; otherwise false 9880 */ 9881 public boolean isFocusTraversable() { 9882 return Component.this.isFocusTraversable(); 9883 } 9884 9885 /** 9886 * Requests focus for this object. 9887 */ 9888 public void requestFocus() { 9889 Component.this.requestFocus(); 9890 } 9891 9892 /** 9893 * Adds the specified focus listener to receive focus events from this 9894 * component. 9895 * 9896 * @param l the focus listener 9897 */ 9898 public void addFocusListener(FocusListener l) { 9899 Component.this.addFocusListener(l); 9900 } 9901 9902 /** 9903 * Removes the specified focus listener so it no longer receives focus 9904 * events from this component. 9905 * 9906 * @param l the focus listener 9907 */ 9908 public void removeFocusListener(FocusListener l) { 9909 Component.this.removeFocusListener(l); 9910 } 9911 9912 } // inner class AccessibleAWTComponent 9913 9914 9915 /** 9916 * Gets the index of this object in its accessible parent. 9917 * If this object does not have an accessible parent, returns 9918 * -1. 9919 * 9920 * @return the index of this object in its accessible parent 9921 */ 9922 int getAccessibleIndexInParent() { 9923 synchronized (getTreeLock()) { 9924 9925 AccessibleContext accContext = getAccessibleContext(); 9926 if (accContext == null) { 9927 return -1; 9928 } 9929 9930 Accessible parent = accContext.getAccessibleParent(); 9931 if (parent == null) { 9932 return -1; 9933 } 9934 9935 accContext = parent.getAccessibleContext(); 9936 for (int i = 0; i < accContext.getAccessibleChildrenCount(); i++) { 9937 if (this.equals(accContext.getAccessibleChild(i))) { 9938 return i; 9939 } 9940 } 9941 9942 return -1; 9943 } 9944 } 9945 9946 /** 9947 * Gets the current state set of this object. 9948 * 9949 * @return an instance of {@code AccessibleStateSet} 9950 * containing the current state set of the object 9951 * @see AccessibleState 9952 */ 9953 AccessibleStateSet getAccessibleStateSet() { 9954 synchronized (getTreeLock()) { 9955 AccessibleStateSet states = new AccessibleStateSet(); 9956 if (this.isEnabled()) { 9957 states.add(AccessibleState.ENABLED); 9958 } 9959 if (this.isFocusTraversable()) { 9960 states.add(AccessibleState.FOCUSABLE); 9961 } 9962 if (this.isVisible()) { 9963 states.add(AccessibleState.VISIBLE); 9964 } 9965 if (this.isShowing()) { 9966 states.add(AccessibleState.SHOWING); 9967 } 9968 if (this.isFocusOwner()) { 9969 states.add(AccessibleState.FOCUSED); 9970 } 9971 if (this instanceof Accessible) { 9972 AccessibleContext ac = ((Accessible) this).getAccessibleContext(); 9973 if (ac != null) { 9974 Accessible ap = ac.getAccessibleParent(); 9975 if (ap != null) { 9976 AccessibleContext pac = ap.getAccessibleContext(); 9977 if (pac != null) { 9978 AccessibleSelection as = pac.getAccessibleSelection(); 9979 if (as != null) { 9980 states.add(AccessibleState.SELECTABLE); 9981 int i = ac.getAccessibleIndexInParent(); 9982 if (i >= 0) { 9983 if (as.isAccessibleChildSelected(i)) { 9984 states.add(AccessibleState.SELECTED); 9985 } 9986 } 9987 } 9988 } 9989 } 9990 } 9991 } 9992 if (Component.isInstanceOf(this, "javax.swing.JComponent")) { 9993 if (((javax.swing.JComponent) this).isOpaque()) { 9994 states.add(AccessibleState.OPAQUE); 9995 } 9996 } 9997 return states; 9998 } 9999 } 10000 10001 /** 10002 * Checks that the given object is instance of the given class. 10003 * @param obj Object to be checked 10004 * @param className The name of the class. Must be fully-qualified class name. 10005 * @return true, if this object is instanceof given class, 10006 * false, otherwise, or if obj or className is null 10007 */ 10008 static boolean isInstanceOf(Object obj, String className) { 10009 if (obj == null) return false; 10010 if (className == null) return false; 10011 10012 Class<?> cls = obj.getClass(); 10013 while (cls != null) { 10014 if (cls.getName().equals(className)) { 10015 return true; 10016 } 10017 cls = cls.getSuperclass(); 10018 } 10019 return false; 10020 } 10021 10022 10023 // ************************** MIXING CODE ******************************* 10024 10025 /** 10026 * Check whether we can trust the current bounds of the component. 10027 * The return value of false indicates that the container of the 10028 * component is invalid, and therefore needs to be laid out, which would 10029 * probably mean changing the bounds of its children. 10030 * Null-layout of the container or absence of the container mean 10031 * the bounds of the component are final and can be trusted. 10032 */ 10033 final boolean areBoundsValid() { 10034 Container cont = getContainer(); 10035 return cont == null || cont.isValid() || cont.getLayout() == null; 10036 } 10037 10038 /** 10039 * Applies the shape to the component 10040 * @param shape Shape to be applied to the component 10041 */ 10042 void applyCompoundShape(Region shape) { 10043 checkTreeLock(); 10044 10045 if (!areBoundsValid()) { 10046 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10047 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10048 } 10049 return; 10050 } 10051 10052 if (!isLightweight()) { 10053 ComponentPeer peer = this.peer; 10054 if (peer != null) { 10055 // The Region class has some optimizations. That's why 10056 // we should manually check whether it's empty and 10057 // substitute the object ourselves. Otherwise we end up 10058 // with some incorrect Region object with loX being 10059 // greater than the hiX for instance. 10060 if (shape.isEmpty()) { 10061 shape = Region.EMPTY_REGION; 10062 } 10063 10064 10065 // Note: the shape is not really copied/cloned. We create 10066 // the Region object ourselves, so there's no any possibility 10067 // to modify the object outside of the mixing code. 10068 // Nullifying compoundShape means that the component has normal shape 10069 // (or has no shape at all). 10070 if (shape.equals(getNormalShape())) { 10071 if (this.compoundShape == null) { 10072 return; 10073 } 10074 this.compoundShape = null; 10075 peer.applyShape(null); 10076 } else { 10077 if (shape.equals(getAppliedShape())) { 10078 return; 10079 } 10080 this.compoundShape = shape; 10081 Point compAbsolute = getLocationOnWindow(); 10082 if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) { 10083 mixingLog.fine("this = " + this + 10084 "; compAbsolute=" + compAbsolute + "; shape=" + shape); 10085 } 10086 peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y)); 10087 } 10088 } 10089 } 10090 } 10091 10092 /** 10093 * Returns the shape previously set with applyCompoundShape(). 10094 * If the component is LW or no shape was applied yet, 10095 * the method returns the normal shape. 10096 */ 10097 private Region getAppliedShape() { 10098 checkTreeLock(); 10099 //XXX: if we allow LW components to have a shape, this must be changed 10100 return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape; 10101 } 10102 10103 Point getLocationOnWindow() { 10104 checkTreeLock(); 10105 Point curLocation = getLocation(); 10106 10107 for (Container parent = getContainer(); 10108 parent != null && !(parent instanceof Window); 10109 parent = parent.getContainer()) 10110 { 10111 curLocation.x += parent.getX(); 10112 curLocation.y += parent.getY(); 10113 } 10114 10115 return curLocation; 10116 } 10117 10118 /** 10119 * Returns the full shape of the component located in window coordinates 10120 */ 10121 final Region getNormalShape() { 10122 checkTreeLock(); 10123 //XXX: we may take into account a user-specified shape for this component 10124 Point compAbsolute = getLocationOnWindow(); 10125 return 10126 Region.getInstanceXYWH( 10127 compAbsolute.x, 10128 compAbsolute.y, 10129 getWidth(), 10130 getHeight() 10131 ); 10132 } 10133 10134 /** 10135 * Returns the "opaque shape" of the component. 10136 * 10137 * The opaque shape of a lightweight components is the actual shape that 10138 * needs to be cut off of the heavyweight components in order to mix this 10139 * lightweight component correctly with them. 10140 * 10141 * The method is overriden in the java.awt.Container to handle non-opaque 10142 * containers containing opaque children. 10143 * 10144 * See 6637655 for details. 10145 */ 10146 Region getOpaqueShape() { 10147 checkTreeLock(); 10148 if (mixingCutoutRegion != null) { 10149 return mixingCutoutRegion; 10150 } else { 10151 return getNormalShape(); 10152 } 10153 } 10154 10155 final int getSiblingIndexAbove() { 10156 checkTreeLock(); 10157 Container parent = getContainer(); 10158 if (parent == null) { 10159 return -1; 10160 } 10161 10162 int nextAbove = parent.getComponentZOrder(this) - 1; 10163 10164 return nextAbove < 0 ? -1 : nextAbove; 10165 } 10166 10167 final ComponentPeer getHWPeerAboveMe() { 10168 checkTreeLock(); 10169 10170 Container cont = getContainer(); 10171 int indexAbove = getSiblingIndexAbove(); 10172 10173 while (cont != null) { 10174 for (int i = indexAbove; i > -1; i--) { 10175 Component comp = cont.getComponent(i); 10176 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) { 10177 return comp.peer; 10178 } 10179 } 10180 // traversing the hierarchy up to the closest HW container; 10181 // further traversing may return a component that is not actually 10182 // a native sibling of this component and this kind of z-order 10183 // request may not be allowed by the underlying system (6852051). 10184 if (!cont.isLightweight()) { 10185 break; 10186 } 10187 10188 indexAbove = cont.getSiblingIndexAbove(); 10189 cont = cont.getContainer(); 10190 } 10191 10192 return null; 10193 } 10194 10195 final int getSiblingIndexBelow() { 10196 checkTreeLock(); 10197 Container parent = getContainer(); 10198 if (parent == null) { 10199 return -1; 10200 } 10201 10202 int nextBelow = parent.getComponentZOrder(this) + 1; 10203 10204 return nextBelow >= parent.getComponentCount() ? -1 : nextBelow; 10205 } 10206 10207 final boolean isNonOpaqueForMixing() { 10208 return mixingCutoutRegion != null && 10209 mixingCutoutRegion.isEmpty(); 10210 } 10211 10212 private Region calculateCurrentShape() { 10213 checkTreeLock(); 10214 Region s = getNormalShape(); 10215 10216 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10217 mixingLog.fine("this = " + this + "; normalShape=" + s); 10218 } 10219 10220 if (getContainer() != null) { 10221 Component comp = this; 10222 Container cont = comp.getContainer(); 10223 10224 while (cont != null) { 10225 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) { 10226 /* It is assumed that: 10227 * 10228 * getComponent(getContainer().getComponentZOrder(comp)) == comp 10229 * 10230 * The assumption has been made according to the current 10231 * implementation of the Container class. 10232 */ 10233 Component c = cont.getComponent(index); 10234 if (c.isLightweight() && c.isShowing()) { 10235 s = s.getDifference(c.getOpaqueShape()); 10236 } 10237 } 10238 10239 if (cont.isLightweight()) { 10240 s = s.getIntersection(cont.getNormalShape()); 10241 } else { 10242 break; 10243 } 10244 10245 comp = cont; 10246 cont = cont.getContainer(); 10247 } 10248 } 10249 10250 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10251 mixingLog.fine("currentShape=" + s); 10252 } 10253 10254 return s; 10255 } 10256 10257 void applyCurrentShape() { 10258 checkTreeLock(); 10259 if (!areBoundsValid()) { 10260 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10261 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10262 } 10263 return; // Because applyCompoundShape() ignores such components anyway 10264 } 10265 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10266 mixingLog.fine("this = " + this); 10267 } 10268 applyCompoundShape(calculateCurrentShape()); 10269 } 10270 10271 final void subtractAndApplyShape(Region s) { 10272 checkTreeLock(); 10273 10274 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10275 mixingLog.fine("this = " + this + "; s=" + s); 10276 } 10277 10278 applyCompoundShape(getAppliedShape().getDifference(s)); 10279 } 10280 10281 private void applyCurrentShapeBelowMe() { 10282 checkTreeLock(); 10283 Container parent = getContainer(); 10284 if (parent != null && parent.isShowing()) { 10285 // First, reapply shapes of my siblings 10286 parent.recursiveApplyCurrentShape(getSiblingIndexBelow()); 10287 10288 // Second, if my container is non-opaque, reapply shapes of siblings of my container 10289 Container parent2 = parent.getContainer(); 10290 while (!parent.isOpaque() && parent2 != null) { 10291 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow()); 10292 10293 parent = parent2; 10294 parent2 = parent.getContainer(); 10295 } 10296 } 10297 } 10298 10299 final void subtractAndApplyShapeBelowMe() { 10300 checkTreeLock(); 10301 Container parent = getContainer(); 10302 if (parent != null && isShowing()) { 10303 Region opaqueShape = getOpaqueShape(); 10304 10305 // First, cut my siblings 10306 parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow()); 10307 10308 // Second, if my container is non-opaque, cut siblings of my container 10309 Container parent2 = parent.getContainer(); 10310 while (!parent.isOpaque() && parent2 != null) { 10311 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow()); 10312 10313 parent = parent2; 10314 parent2 = parent.getContainer(); 10315 } 10316 } 10317 } 10318 10319 void mixOnShowing() { 10320 synchronized (getTreeLock()) { 10321 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10322 mixingLog.fine("this = " + this); 10323 } 10324 if (!isMixingNeeded()) { 10325 return; 10326 } 10327 if (isLightweight()) { 10328 subtractAndApplyShapeBelowMe(); 10329 } else { 10330 applyCurrentShape(); 10331 } 10332 } 10333 } 10334 10335 void mixOnHiding(boolean isLightweight) { 10336 // We cannot be sure that the peer exists at this point, so we need the argument 10337 // to find out whether the hiding component is (well, actually was) a LW or a HW. 10338 synchronized (getTreeLock()) { 10339 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10340 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight); 10341 } 10342 if (!isMixingNeeded()) { 10343 return; 10344 } 10345 if (isLightweight) { 10346 applyCurrentShapeBelowMe(); 10347 } 10348 } 10349 } 10350 10351 void mixOnReshaping() { 10352 synchronized (getTreeLock()) { 10353 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10354 mixingLog.fine("this = " + this); 10355 } 10356 if (!isMixingNeeded()) { 10357 return; 10358 } 10359 if (isLightweight()) { 10360 applyCurrentShapeBelowMe(); 10361 } else { 10362 applyCurrentShape(); 10363 } 10364 } 10365 } 10366 10367 void mixOnZOrderChanging(int oldZorder, int newZorder) { 10368 synchronized (getTreeLock()) { 10369 boolean becameHigher = newZorder < oldZorder; 10370 Container parent = getContainer(); 10371 10372 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10373 mixingLog.fine("this = " + this + 10374 "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent); 10375 } 10376 if (!isMixingNeeded()) { 10377 return; 10378 } 10379 if (isLightweight()) { 10380 if (becameHigher) { 10381 if (parent != null && isShowing()) { 10382 parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder); 10383 } 10384 } else { 10385 if (parent != null) { 10386 parent.recursiveApplyCurrentShape(oldZorder, newZorder); 10387 } 10388 } 10389 } else { 10390 if (becameHigher) { 10391 applyCurrentShape(); 10392 } else { 10393 if (parent != null) { 10394 Region shape = getAppliedShape(); 10395 10396 for (int index = oldZorder; index < newZorder; index++) { 10397 Component c = parent.getComponent(index); 10398 if (c.isLightweight() && c.isShowing()) { 10399 shape = shape.getDifference(c.getOpaqueShape()); 10400 } 10401 } 10402 applyCompoundShape(shape); 10403 } 10404 } 10405 } 10406 } 10407 } 10408 10409 void mixOnValidating() { 10410 // This method gets overriden in the Container. Obviously, a plain 10411 // non-container components don't need to handle validation. 10412 } 10413 10414 final boolean isMixingNeeded() { 10415 if (SunToolkit.getSunAwtDisableMixing()) { 10416 if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) { 10417 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing"); 10418 } 10419 return false; 10420 } 10421 if (!areBoundsValid()) { 10422 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10423 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10424 } 10425 return false; 10426 } 10427 Window window = getContainingWindow(); 10428 if (window != null) { 10429 if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) { 10430 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10431 mixingLog.fine("containing window = " + window + 10432 "; has h/w descendants = " + window.hasHeavyweightDescendants() + 10433 "; has l/w descendants = " + window.hasLightweightDescendants() + 10434 "; disposing = " + window.isDisposing()); 10435 } 10436 return false; 10437 } 10438 } else { 10439 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10440 mixingLog.fine("this = " + this + "; containing window is null"); 10441 } 10442 return false; 10443 } 10444 return true; 10445 } 10446 10447 /** 10448 * Sets a 'mixing-cutout' shape for this lightweight component. 10449 * 10450 * This method is used exclusively for the purposes of the 10451 * Heavyweight/Lightweight Components Mixing feature and will 10452 * have no effect if applied to a heavyweight component. 10453 * 10454 * By default a lightweight component is treated as an opaque rectangle for 10455 * the purposes of the Heavyweight/Lightweight Components Mixing feature. 10456 * This method enables developers to set an arbitrary shape to be cut out 10457 * from heavyweight components positioned underneath the lightweight 10458 * component in the z-order. 10459 * <p> 10460 * The {@code shape} argument may have the following values: 10461 * <ul> 10462 * <li>{@code null} - reverts the default cutout shape (the rectangle equal 10463 * to the component's {@code getBounds()}) 10464 * <li><i>empty-shape</i> - does not cut out anything from heavyweight 10465 * components. This makes this lightweight component effectively 10466 * transparent. Note that descendants of the lightweight component still 10467 * affect the shapes of heavyweight components. An example of an 10468 * <i>empty-shape</i> is {@code new Rectangle()}. 10469 * <li><i>non-empty-shape</i> - the given shape will be cut out from 10470 * heavyweight components. 10471 * </ul> 10472 * <p> 10473 * The most common example when the 'mixing-cutout' shape is needed is a 10474 * glass pane component. The {@link JRootPane#setGlassPane} method 10475 * automatically sets the <i>empty-shape</i> as the 'mixing-cutout' shape 10476 * for the given glass pane component. If a developer needs some other 10477 * 'mixing-cutout' shape for the glass pane (which is rare), this must be 10478 * changed manually after installing the glass pane to the root pane. 10479 * 10480 * @param shape the new 'mixing-cutout' shape 10481 * @since 9 10482 */ 10483 public void setMixingCutoutShape(Shape shape) { 10484 Region region = shape == null ? null : Region.getInstance(shape, null); 10485 10486 synchronized (getTreeLock()) { 10487 boolean needShowing = false; 10488 boolean needHiding = false; 10489 10490 if (!isNonOpaqueForMixing()) { 10491 needHiding = true; 10492 } 10493 10494 mixingCutoutRegion = region; 10495 10496 if (!isNonOpaqueForMixing()) { 10497 needShowing = true; 10498 } 10499 10500 if (isMixingNeeded()) { 10501 if (needHiding) { 10502 mixOnHiding(isLightweight()); 10503 } 10504 if (needShowing) { 10505 mixOnShowing(); 10506 } 10507 } 10508 } 10509 } 10510 10511 // ****************** END OF MIXING CODE ******************************** 10512 10513 // Note that the method is overriden in the Window class, 10514 // a window doesn't need to be updated in the Z-order. 10515 void updateZOrder() { 10516 peer.setZOrder(getHWPeerAboveMe()); 10517 } 10518 10519 }