1 /* 2 * Copyright (c) 1995, 2018, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.awt; 26 27 import java.applet.Applet; 28 import java.awt.dnd.DropTarget; 29 import java.awt.event.ActionEvent; 30 import java.awt.event.AdjustmentEvent; 31 import java.awt.event.ComponentEvent; 32 import java.awt.event.ComponentListener; 33 import java.awt.event.FocusEvent; 34 import java.awt.event.FocusListener; 35 import java.awt.event.HierarchyBoundsListener; 36 import java.awt.event.HierarchyEvent; 37 import java.awt.event.HierarchyListener; 38 import java.awt.event.InputEvent; 39 import java.awt.event.InputMethodEvent; 40 import java.awt.event.InputMethodListener; 41 import java.awt.event.ItemEvent; 42 import java.awt.event.KeyEvent; 43 import java.awt.event.KeyListener; 44 import java.awt.event.MouseEvent; 45 import java.awt.event.MouseListener; 46 import java.awt.event.MouseMotionListener; 47 import java.awt.event.MouseWheelEvent; 48 import java.awt.event.MouseWheelListener; 49 import java.awt.event.PaintEvent; 50 import java.awt.event.TextEvent; 51 import java.awt.im.InputContext; 52 import java.awt.im.InputMethodRequests; 53 import java.awt.image.BufferStrategy; 54 import java.awt.image.ColorModel; 55 import java.awt.image.ImageObserver; 56 import java.awt.image.ImageProducer; 57 import java.awt.image.VolatileImage; 58 import java.awt.peer.ComponentPeer; 59 import java.awt.peer.ContainerPeer; 60 import java.awt.peer.LightweightPeer; 61 import java.beans.PropertyChangeListener; 62 import java.beans.PropertyChangeSupport; 63 import java.beans.Transient; 64 import java.io.IOException; 65 import java.io.ObjectInputStream; 66 import java.io.ObjectOutputStream; 67 import java.io.PrintStream; 68 import java.io.PrintWriter; 69 import java.io.Serializable; 70 import java.security.AccessControlContext; 71 import java.security.AccessController; 72 import java.util.Collections; 73 import java.util.EventListener; 74 import java.util.HashSet; 75 import java.util.Locale; 76 import java.util.Map; 77 import java.util.Objects; 78 import java.util.Set; 79 import java.util.Vector; 80 81 import javax.accessibility.Accessible; 82 import javax.accessibility.AccessibleComponent; 83 import javax.accessibility.AccessibleContext; 84 import javax.accessibility.AccessibleRole; 85 import javax.accessibility.AccessibleSelection; 86 import javax.accessibility.AccessibleState; 87 import javax.accessibility.AccessibleStateSet; 88 import javax.swing.JComponent; 89 import javax.swing.JRootPane; 90 91 import sun.awt.AWTAccessor; 92 import sun.awt.AppContext; 93 import sun.awt.ComponentFactory; 94 import sun.awt.ConstrainableGraphics; 95 import sun.awt.EmbeddedFrame; 96 import sun.awt.RequestFocusController; 97 import sun.awt.SubRegionShowable; 98 import sun.awt.SunToolkit; 99 import sun.awt.dnd.SunDropTargetEvent; 100 import sun.awt.im.CompositionArea; 101 import sun.awt.image.VSyncedBSManager; 102 import sun.font.FontManager; 103 import sun.font.FontManagerFactory; 104 import sun.font.SunFontManager; 105 import sun.java2d.SunGraphics2D; 106 import sun.java2d.SunGraphicsEnvironment; 107 import sun.java2d.pipe.Region; 108 import sun.java2d.pipe.hw.ExtendedBufferCapabilities; 109 import sun.security.action.GetPropertyAction; 110 import sun.swing.SwingAccessor; 111 import sun.util.logging.PlatformLogger; 112 113 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType 114 .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 * <h3>Serialization</h3> 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="http://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 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 int width; 4042 4043 /** 4044 * The height of the back buffers 4045 */ 4046 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 drawBuffer = null; 4120 drawVBuffer = null; 4121 destroyBuffers(); 4122 // ... then recreate the backbuffers 4123 } 4124 4125 if (caps instanceof ExtendedBufferCapabilities) { 4126 ExtendedBufferCapabilities ebc = 4127 (ExtendedBufferCapabilities)caps; 4128 if (ebc.getVSync() == VSYNC_ON) { 4129 // if this buffer strategy is not allowed to be v-synced, 4130 // change the caps that we pass to the peer but keep on 4131 // trying to create v-synced buffers; 4132 // do not throw IAE here in case it is disallowed, see 4133 // ExtendedBufferCapabilities for more info 4134 if (!VSyncedBSManager.vsyncAllowed(this)) { 4135 caps = ebc.derive(VSYNC_DEFAULT); 4136 } 4137 } 4138 } 4139 4140 peer.createBuffers(numBuffers, caps); 4141 updateInternalBuffers(); 4142 } 4143 4144 /** 4145 * Updates internal buffers (both volatile and non-volatile) 4146 * by requesting the back-buffer from the peer. 4147 */ 4148 private void updateInternalBuffers() { 4149 // get the images associated with the draw buffer 4150 drawBuffer = getBackBuffer(); 4151 if (drawBuffer instanceof VolatileImage) { 4152 drawVBuffer = (VolatileImage)drawBuffer; 4153 } else { 4154 drawVBuffer = null; 4155 } 4156 } 4157 4158 /** 4159 * @return direct access to the back buffer, as an image. 4160 * @exception IllegalStateException if the buffers have not yet 4161 * been created 4162 */ 4163 protected Image getBackBuffer() { 4164 if (peer != null) { 4165 return peer.getBackBuffer(); 4166 } else { 4167 throw new IllegalStateException( 4168 "Component must have a valid peer"); 4169 } 4170 } 4171 4172 /** 4173 * Flipping moves the contents of the back buffer to the front buffer, 4174 * either by copying or by moving the video pointer. 4175 * @param flipAction an integer value describing the flipping action 4176 * for the contents of the back buffer. This should be one of the 4177 * values of the {@code BufferCapabilities.FlipContents} 4178 * property. 4179 * @exception IllegalStateException if the buffers have not yet 4180 * been created 4181 * @see java.awt.BufferCapabilities#getFlipContents() 4182 */ 4183 protected void flip(BufferCapabilities.FlipContents flipAction) { 4184 if (peer != null) { 4185 Image backBuffer = getBackBuffer(); 4186 if (backBuffer != null) { 4187 peer.flip(0, 0, 4188 backBuffer.getWidth(null), 4189 backBuffer.getHeight(null), flipAction); 4190 } 4191 } else { 4192 throw new IllegalStateException( 4193 "Component must have a valid peer"); 4194 } 4195 } 4196 4197 void flipSubRegion(int x1, int y1, int x2, int y2, 4198 BufferCapabilities.FlipContents flipAction) 4199 { 4200 if (peer != null) { 4201 peer.flip(x1, y1, x2, y2, flipAction); 4202 } else { 4203 throw new IllegalStateException( 4204 "Component must have a valid peer"); 4205 } 4206 } 4207 4208 /** 4209 * Destroys the buffers created through this object 4210 */ 4211 protected void destroyBuffers() { 4212 VSyncedBSManager.releaseVsync(this); 4213 if (peer != null) { 4214 peer.destroyBuffers(); 4215 } else { 4216 throw new IllegalStateException( 4217 "Component must have a valid peer"); 4218 } 4219 } 4220 4221 /** 4222 * @return the buffering capabilities of this strategy 4223 */ 4224 public BufferCapabilities getCapabilities() { 4225 if (caps instanceof ProxyCapabilities) { 4226 return ((ProxyCapabilities)caps).orig; 4227 } else { 4228 return caps; 4229 } 4230 } 4231 4232 /** 4233 * @return the graphics on the drawing buffer. This method may not 4234 * be synchronized for performance reasons; use of this method by multiple 4235 * threads should be handled at the application level. Disposal of the 4236 * graphics object must be handled by the application. 4237 */ 4238 public Graphics getDrawGraphics() { 4239 revalidate(); 4240 return drawBuffer.getGraphics(); 4241 } 4242 4243 /** 4244 * Restore the drawing buffer if it has been lost 4245 */ 4246 protected void revalidate() { 4247 revalidate(true); 4248 } 4249 4250 void revalidate(boolean checkSize) { 4251 validatedContents = false; 4252 4253 if (checkSize && (getWidth() != width || getHeight() != height)) { 4254 // component has been resized; recreate the backbuffers 4255 try { 4256 createBuffers(numBuffers, caps); 4257 } catch (AWTException e) { 4258 // shouldn't be possible 4259 } 4260 validatedContents = true; 4261 } 4262 4263 // get the buffers from the peer every time since they 4264 // might have been replaced in response to a display change event 4265 updateInternalBuffers(); 4266 4267 // now validate the backbuffer 4268 if (drawVBuffer != null) { 4269 GraphicsConfiguration gc = 4270 getGraphicsConfiguration_NoClientCode(); 4271 int returnCode = drawVBuffer.validate(gc); 4272 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 4273 try { 4274 createBuffers(numBuffers, caps); 4275 } catch (AWTException e) { 4276 // shouldn't be possible 4277 } 4278 if (drawVBuffer != null) { 4279 // backbuffers were recreated, so validate again 4280 drawVBuffer.validate(gc); 4281 } 4282 validatedContents = true; 4283 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 4284 validatedContents = true; 4285 } 4286 } 4287 } 4288 4289 /** 4290 * @return whether the drawing buffer was lost since the last call to 4291 * {@code getDrawGraphics} 4292 */ 4293 public boolean contentsLost() { 4294 if (drawVBuffer == null) { 4295 return false; 4296 } 4297 return drawVBuffer.contentsLost(); 4298 } 4299 4300 /** 4301 * @return whether the drawing buffer was recently restored from a lost 4302 * state and reinitialized to the default background color (white) 4303 */ 4304 public boolean contentsRestored() { 4305 return validatedContents; 4306 } 4307 4308 /** 4309 * Makes the next available buffer visible by either blitting or 4310 * flipping. 4311 */ 4312 public void show() { 4313 flip(caps.getFlipContents()); 4314 } 4315 4316 /** 4317 * Makes specified region of the next available buffer visible 4318 * by either blitting or flipping. 4319 */ 4320 void showSubRegion(int x1, int y1, int x2, int y2) { 4321 flipSubRegion(x1, y1, x2, y2, caps.getFlipContents()); 4322 } 4323 4324 /** 4325 * {@inheritDoc} 4326 * @since 1.6 4327 */ 4328 public void dispose() { 4329 if (Component.this.bufferStrategy == this) { 4330 Component.this.bufferStrategy = null; 4331 if (peer != null) { 4332 destroyBuffers(); 4333 } 4334 } 4335 } 4336 4337 } // Inner class FlipBufferStrategy 4338 4339 /** 4340 * Inner class for blitting offscreen surfaces to a component. 4341 * 4342 * @author Michael Martak 4343 * @since 1.4 4344 */ 4345 protected class BltBufferStrategy extends BufferStrategy { 4346 4347 /** 4348 * The buffering capabilities 4349 */ 4350 protected BufferCapabilities caps; // = null 4351 /** 4352 * The back buffers 4353 */ 4354 protected VolatileImage[] backBuffers; // = null 4355 /** 4356 * Whether or not the drawing buffer has been recently restored from 4357 * a lost state. 4358 */ 4359 protected boolean validatedContents; // = false 4360 /** 4361 * Width of the back buffers 4362 */ 4363 protected int width; 4364 /** 4365 * Height of the back buffers 4366 */ 4367 protected int height; 4368 4369 /** 4370 * Insets for the hosting Component. The size of the back buffer 4371 * is constrained by these. 4372 */ 4373 private Insets insets; 4374 4375 /** 4376 * Creates a new blt buffer strategy around a component 4377 * @param numBuffers number of buffers to create, including the 4378 * front buffer 4379 * @param caps the capabilities of the buffers 4380 */ 4381 protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) { 4382 this.caps = caps; 4383 createBackBuffers(numBuffers - 1); 4384 } 4385 4386 /** 4387 * {@inheritDoc} 4388 * @since 1.6 4389 */ 4390 public void dispose() { 4391 if (backBuffers != null) { 4392 for (int counter = backBuffers.length - 1; counter >= 0; 4393 counter--) { 4394 if (backBuffers[counter] != null) { 4395 backBuffers[counter].flush(); 4396 backBuffers[counter] = null; 4397 } 4398 } 4399 } 4400 if (Component.this.bufferStrategy == this) { 4401 Component.this.bufferStrategy = null; 4402 } 4403 } 4404 4405 /** 4406 * Creates the back buffers 4407 * 4408 * @param numBuffers the number of buffers to create 4409 */ 4410 protected void createBackBuffers(int numBuffers) { 4411 if (numBuffers == 0) { 4412 backBuffers = null; 4413 } else { 4414 // save the current bounds 4415 width = getWidth(); 4416 height = getHeight(); 4417 insets = getInsets_NoClientCode(); 4418 int iWidth = width - insets.left - insets.right; 4419 int iHeight = height - insets.top - insets.bottom; 4420 4421 // It is possible for the component's width and/or height 4422 // to be 0 here. Force the size of the backbuffers to 4423 // be > 0 so that creating the image won't fail. 4424 iWidth = Math.max(1, iWidth); 4425 iHeight = Math.max(1, iHeight); 4426 if (backBuffers == null) { 4427 backBuffers = new VolatileImage[numBuffers]; 4428 } else { 4429 // flush any existing backbuffers 4430 for (int i = 0; i < numBuffers; i++) { 4431 if (backBuffers[i] != null) { 4432 backBuffers[i].flush(); 4433 backBuffers[i] = null; 4434 } 4435 } 4436 } 4437 4438 // create the backbuffers 4439 for (int i = 0; i < numBuffers; i++) { 4440 backBuffers[i] = createVolatileImage(iWidth, iHeight); 4441 } 4442 } 4443 } 4444 4445 /** 4446 * @return the buffering capabilities of this strategy 4447 */ 4448 public BufferCapabilities getCapabilities() { 4449 return caps; 4450 } 4451 4452 /** 4453 * @return the draw graphics 4454 */ 4455 public Graphics getDrawGraphics() { 4456 revalidate(); 4457 Image backBuffer = getBackBuffer(); 4458 if (backBuffer == null) { 4459 return getGraphics(); 4460 } 4461 SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics(); 4462 g.constrain(-insets.left, -insets.top, 4463 backBuffer.getWidth(null) + insets.left, 4464 backBuffer.getHeight(null) + insets.top); 4465 return g; 4466 } 4467 4468 /** 4469 * @return direct access to the back buffer, as an image. 4470 * If there is no back buffer, returns null. 4471 */ 4472 Image getBackBuffer() { 4473 if (backBuffers != null) { 4474 return backBuffers[backBuffers.length - 1]; 4475 } else { 4476 return null; 4477 } 4478 } 4479 4480 /** 4481 * Makes the next available buffer visible. 4482 */ 4483 public void show() { 4484 showSubRegion(insets.left, insets.top, 4485 width - insets.right, 4486 height - insets.bottom); 4487 } 4488 4489 /** 4490 * Package-private method to present a specific rectangular area 4491 * of this buffer. This class currently shows only the entire 4492 * buffer, by calling showSubRegion() with the full dimensions of 4493 * the buffer. Subclasses (e.g., BltSubRegionBufferStrategy 4494 * and FlipSubRegionBufferStrategy) may have region-specific show 4495 * methods that call this method with actual sub regions of the 4496 * buffer. 4497 */ 4498 void showSubRegion(int x1, int y1, int x2, int y2) { 4499 if (backBuffers == null) { 4500 return; 4501 } 4502 // Adjust location to be relative to client area. 4503 x1 -= insets.left; 4504 x2 -= insets.left; 4505 y1 -= insets.top; 4506 y2 -= insets.top; 4507 Graphics g = getGraphics_NoClientCode(); 4508 if (g == null) { 4509 // Not showing, bail 4510 return; 4511 } 4512 try { 4513 // First image copy is in terms of Frame's coordinates, need 4514 // to translate to client area. 4515 g.translate(insets.left, insets.top); 4516 for (int i = 0; i < backBuffers.length; i++) { 4517 g.drawImage(backBuffers[i], 4518 x1, y1, x2, y2, 4519 x1, y1, x2, y2, 4520 null); 4521 g.dispose(); 4522 g = null; 4523 g = backBuffers[i].getGraphics(); 4524 } 4525 } finally { 4526 if (g != null) { 4527 g.dispose(); 4528 } 4529 } 4530 } 4531 4532 /** 4533 * Restore the drawing buffer if it has been lost 4534 */ 4535 protected void revalidate() { 4536 revalidate(true); 4537 } 4538 4539 void revalidate(boolean checkSize) { 4540 validatedContents = false; 4541 4542 if (backBuffers == null) { 4543 return; 4544 } 4545 4546 if (checkSize) { 4547 Insets insets = getInsets_NoClientCode(); 4548 if (getWidth() != width || getHeight() != height || 4549 !insets.equals(this.insets)) { 4550 // component has been resized; recreate the backbuffers 4551 createBackBuffers(backBuffers.length); 4552 validatedContents = true; 4553 } 4554 } 4555 4556 // now validate the backbuffer 4557 GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); 4558 int returnCode = 4559 backBuffers[backBuffers.length - 1].validate(gc); 4560 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 4561 if (checkSize) { 4562 createBackBuffers(backBuffers.length); 4563 // backbuffers were recreated, so validate again 4564 backBuffers[backBuffers.length - 1].validate(gc); 4565 } 4566 // else case means we're called from Swing on the toolkit 4567 // thread, don't recreate buffers as that'll deadlock 4568 // (creating VolatileImages invokes getting GraphicsConfig 4569 // which grabs treelock). 4570 validatedContents = true; 4571 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 4572 validatedContents = true; 4573 } 4574 } 4575 4576 /** 4577 * @return whether the drawing buffer was lost since the last call to 4578 * {@code getDrawGraphics} 4579 */ 4580 public boolean contentsLost() { 4581 if (backBuffers == null) { 4582 return false; 4583 } else { 4584 return backBuffers[backBuffers.length - 1].contentsLost(); 4585 } 4586 } 4587 4588 /** 4589 * @return whether the drawing buffer was recently restored from a lost 4590 * state and reinitialized to the default background color (white) 4591 */ 4592 public boolean contentsRestored() { 4593 return validatedContents; 4594 } 4595 } // Inner class BltBufferStrategy 4596 4597 /** 4598 * Private class to perform sub-region flipping. 4599 */ 4600 private class FlipSubRegionBufferStrategy extends FlipBufferStrategy 4601 implements SubRegionShowable 4602 { 4603 4604 protected FlipSubRegionBufferStrategy(int numBuffers, 4605 BufferCapabilities caps) 4606 throws AWTException 4607 { 4608 super(numBuffers, caps); 4609 } 4610 4611 public void show(int x1, int y1, int x2, int y2) { 4612 showSubRegion(x1, y1, x2, y2); 4613 } 4614 4615 // This is invoked by Swing on the toolkit thread. 4616 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4617 if (!contentsLost()) { 4618 showSubRegion(x1, y1, x2, y2); 4619 return !contentsLost(); 4620 } 4621 return false; 4622 } 4623 } 4624 4625 /** 4626 * Private class to perform sub-region blitting. Swing will use 4627 * this subclass via the SubRegionShowable interface in order to 4628 * copy only the area changed during a repaint. 4629 * See javax.swing.BufferStrategyPaintManager. 4630 */ 4631 private class BltSubRegionBufferStrategy extends BltBufferStrategy 4632 implements SubRegionShowable 4633 { 4634 4635 protected BltSubRegionBufferStrategy(int numBuffers, 4636 BufferCapabilities caps) 4637 { 4638 super(numBuffers, caps); 4639 } 4640 4641 public void show(int x1, int y1, int x2, int y2) { 4642 showSubRegion(x1, y1, x2, y2); 4643 } 4644 4645 // This method is called by Swing on the toolkit thread. 4646 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4647 if (!contentsLost()) { 4648 showSubRegion(x1, y1, x2, y2); 4649 return !contentsLost(); 4650 } 4651 return false; 4652 } 4653 } 4654 4655 /** 4656 * Inner class for flipping buffers on a component. That component must 4657 * be a {@code Canvas} or {@code Window}. 4658 * @see Canvas 4659 * @see Window 4660 * @see java.awt.image.BufferStrategy 4661 * @author Michael Martak 4662 * @since 1.4 4663 */ 4664 private class SingleBufferStrategy extends BufferStrategy { 4665 4666 private BufferCapabilities caps; 4667 4668 public SingleBufferStrategy(BufferCapabilities caps) { 4669 this.caps = caps; 4670 } 4671 public BufferCapabilities getCapabilities() { 4672 return caps; 4673 } 4674 public Graphics getDrawGraphics() { 4675 return getGraphics(); 4676 } 4677 public boolean contentsLost() { 4678 return false; 4679 } 4680 public boolean contentsRestored() { 4681 return false; 4682 } 4683 public void show() { 4684 // Do nothing 4685 } 4686 } // Inner class SingleBufferStrategy 4687 4688 /** 4689 * Sets whether or not paint messages received from the operating system 4690 * should be ignored. This does not affect paint events generated in 4691 * software by the AWT, unless they are an immediate response to an 4692 * OS-level paint message. 4693 * <p> 4694 * This is useful, for example, if running under full-screen mode and 4695 * better performance is desired, or if page-flipping is used as the 4696 * buffer strategy. 4697 * 4698 * @param ignoreRepaint {@code true} if the paint messages from the OS 4699 * should be ignored; otherwise {@code false} 4700 * 4701 * @since 1.4 4702 * @see #getIgnoreRepaint 4703 * @see Canvas#createBufferStrategy 4704 * @see Window#createBufferStrategy 4705 * @see java.awt.image.BufferStrategy 4706 * @see GraphicsDevice#setFullScreenWindow 4707 */ 4708 public void setIgnoreRepaint(boolean ignoreRepaint) { 4709 this.ignoreRepaint = ignoreRepaint; 4710 } 4711 4712 /** 4713 * @return whether or not paint messages received from the operating system 4714 * should be ignored. 4715 * 4716 * @since 1.4 4717 * @see #setIgnoreRepaint 4718 */ 4719 public boolean getIgnoreRepaint() { 4720 return ignoreRepaint; 4721 } 4722 4723 /** 4724 * Checks whether this component "contains" the specified point, 4725 * where {@code x} and {@code y} are defined to be 4726 * relative to the coordinate system of this component. 4727 * 4728 * @param x the <i>x</i> coordinate of the point 4729 * @param y the <i>y</i> coordinate of the point 4730 * @return {@code true} if the point is within the component; 4731 * otherwise {@code false} 4732 * @see #getComponentAt(int, int) 4733 * @since 1.1 4734 */ 4735 public boolean contains(int x, int y) { 4736 return inside(x, y); 4737 } 4738 4739 /** 4740 * Checks whether the point is inside of this component. 4741 * 4742 * @param x the <i>x</i> coordinate of the point 4743 * @param y the <i>y</i> coordinate of the point 4744 * @return {@code true} if the point is within the component; 4745 * otherwise {@code false} 4746 * @deprecated As of JDK version 1.1, 4747 * replaced by contains(int, int). 4748 */ 4749 @Deprecated 4750 public boolean inside(int x, int y) { 4751 return (x >= 0) && (x < width) && (y >= 0) && (y < height); 4752 } 4753 4754 /** 4755 * Checks whether this component "contains" the specified point, 4756 * where the point's <i>x</i> and <i>y</i> coordinates are defined 4757 * to be relative to the coordinate system of this component. 4758 * 4759 * @param p the point 4760 * @return {@code true} if the point is within the component; 4761 * otherwise {@code false} 4762 * @throws NullPointerException if {@code p} is {@code null} 4763 * @see #getComponentAt(Point) 4764 * @since 1.1 4765 */ 4766 public boolean contains(Point p) { 4767 return contains(p.x, p.y); 4768 } 4769 4770 /** 4771 * Determines if this component or one of its immediate 4772 * subcomponents contains the (<i>x</i>, <i>y</i>) location, 4773 * and if so, returns the containing component. This method only 4774 * looks one level deep. If the point (<i>x</i>, <i>y</i>) is 4775 * inside a subcomponent that itself has subcomponents, it does not 4776 * go looking down the subcomponent tree. 4777 * <p> 4778 * The {@code locate} method of {@code Component} simply 4779 * returns the component itself if the (<i>x</i>, <i>y</i>) 4780 * coordinate location is inside its bounding box, and {@code null} 4781 * otherwise. 4782 * @param x the <i>x</i> coordinate 4783 * @param y the <i>y</i> coordinate 4784 * @return the component or subcomponent that contains the 4785 * (<i>x</i>, <i>y</i>) location; 4786 * {@code null} if the location 4787 * is outside this component 4788 * @see #contains(int, int) 4789 * @since 1.0 4790 */ 4791 public Component getComponentAt(int x, int y) { 4792 return locate(x, y); 4793 } 4794 4795 /** 4796 * Returns the component occupying the position specified (this component, 4797 * or immediate child component, or null if neither 4798 * of the first two occupies the location). 4799 * 4800 * @param x the <i>x</i> coordinate to search for components at 4801 * @param y the <i>y</i> coordinate to search for components at 4802 * @return the component at the specified location or {@code null} 4803 * @deprecated As of JDK version 1.1, 4804 * replaced by getComponentAt(int, int). 4805 */ 4806 @Deprecated 4807 public Component locate(int x, int y) { 4808 return contains(x, y) ? this : null; 4809 } 4810 4811 /** 4812 * Returns the component or subcomponent that contains the 4813 * specified point. 4814 * @param p the point 4815 * @return the component at the specified location or {@code null} 4816 * @see java.awt.Component#contains 4817 * @since 1.1 4818 */ 4819 public Component getComponentAt(Point p) { 4820 return getComponentAt(p.x, p.y); 4821 } 4822 4823 /** 4824 * @param e the event to deliver 4825 * @deprecated As of JDK version 1.1, 4826 * replaced by {@code dispatchEvent(AWTEvent e)}. 4827 */ 4828 @Deprecated 4829 public void deliverEvent(Event e) { 4830 postEvent(e); 4831 } 4832 4833 /** 4834 * Dispatches an event to this component or one of its sub components. 4835 * Calls {@code processEvent} before returning for 1.1-style 4836 * events which have been enabled for the {@code Component}. 4837 * @param e the event 4838 */ 4839 public final void dispatchEvent(AWTEvent e) { 4840 dispatchEventImpl(e); 4841 } 4842 4843 @SuppressWarnings("deprecation") 4844 void dispatchEventImpl(AWTEvent e) { 4845 int id = e.getID(); 4846 4847 // Check that this component belongs to this app-context 4848 AppContext compContext = appContext; 4849 if (compContext != null && !compContext.equals(AppContext.getAppContext())) { 4850 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) { 4851 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext"); 4852 } 4853 } 4854 4855 if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) { 4856 eventLog.finest("{0}", e); 4857 } 4858 4859 /* 4860 * 0. Set timestamp and modifiers of current event. 4861 */ 4862 if (!(e instanceof KeyEvent)) { 4863 // Timestamp of a key event is set later in DKFM.preDispatchKeyEvent(KeyEvent). 4864 EventQueue.setCurrentEventAndMostRecentTime(e); 4865 } 4866 4867 /* 4868 * 1. Pre-dispatchers. Do any necessary retargeting/reordering here 4869 * before we notify AWTEventListeners. 4870 */ 4871 4872 if (e instanceof SunDropTargetEvent) { 4873 ((SunDropTargetEvent)e).dispatch(); 4874 return; 4875 } 4876 4877 if (!e.focusManagerIsDispatching) { 4878 // Invoke the private focus retargeting method which provides 4879 // lightweight Component support 4880 if (e.isPosted) { 4881 e = KeyboardFocusManager.retargetFocusEvent(e); 4882 e.isPosted = true; 4883 } 4884 4885 // Now, with the event properly targeted to a lightweight 4886 // descendant if necessary, invoke the public focus retargeting 4887 // and dispatching function 4888 if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 4889 dispatchEvent(e)) 4890 { 4891 return; 4892 } 4893 } 4894 if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 4895 focusLog.finest("" + e); 4896 } 4897 // MouseWheel may need to be retargeted here so that 4898 // AWTEventListener sees the event go to the correct 4899 // Component. If the MouseWheelEvent needs to go to an ancestor, 4900 // the event is dispatched to the ancestor, and dispatching here 4901 // stops. 4902 if (id == MouseEvent.MOUSE_WHEEL && 4903 (!eventTypeEnabled(id)) && 4904 (peer != null && !peer.handlesWheelScrolling()) && 4905 (dispatchMouseWheelToAncestor((MouseWheelEvent)e))) 4906 { 4907 return; 4908 } 4909 4910 /* 4911 * 2. Allow the Toolkit to pass this to AWTEventListeners. 4912 */ 4913 Toolkit toolkit = Toolkit.getDefaultToolkit(); 4914 toolkit.notifyAWTEventListeners(e); 4915 4916 4917 /* 4918 * 3. If no one has consumed a key event, allow the 4919 * KeyboardFocusManager to process it. 4920 */ 4921 if (!e.isConsumed()) { 4922 if (e instanceof java.awt.event.KeyEvent) { 4923 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 4924 processKeyEvent(this, (KeyEvent)e); 4925 if (e.isConsumed()) { 4926 return; 4927 } 4928 } 4929 } 4930 4931 /* 4932 * 4. Allow input methods to process the event 4933 */ 4934 if (areInputMethodsEnabled()) { 4935 // We need to pass on InputMethodEvents since some host 4936 // input method adapters send them through the Java 4937 // event queue instead of directly to the component, 4938 // and the input context also handles the Java composition window 4939 if(((e instanceof InputMethodEvent) && !(this instanceof CompositionArea)) 4940 || 4941 // Otherwise, we only pass on input and focus events, because 4942 // a) input methods shouldn't know about semantic or component-level events 4943 // b) passing on the events takes time 4944 // c) isConsumed() is always true for semantic events. 4945 (e instanceof InputEvent) || (e instanceof FocusEvent)) { 4946 InputContext inputContext = getInputContext(); 4947 4948 4949 if (inputContext != null) { 4950 inputContext.dispatchEvent(e); 4951 if (e.isConsumed()) { 4952 if ((e instanceof FocusEvent) && focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 4953 focusLog.finest("3579: Skipping " + e); 4954 } 4955 return; 4956 } 4957 } 4958 } 4959 } else { 4960 // When non-clients get focus, we need to explicitly disable the native 4961 // input method. The native input method is actually not disabled when 4962 // the active/passive/peered clients loose focus. 4963 if (id == FocusEvent.FOCUS_GAINED) { 4964 InputContext inputContext = getInputContext(); 4965 if (inputContext != null && inputContext instanceof sun.awt.im.InputContext) { 4966 ((sun.awt.im.InputContext)inputContext).disableNativeIM(); 4967 } 4968 } 4969 } 4970 4971 4972 /* 4973 * 5. Pre-process any special events before delivery 4974 */ 4975 switch(id) { 4976 // Handling of the PAINT and UPDATE events is now done in the 4977 // peer's handleEvent() method so the background can be cleared 4978 // selectively for non-native components on Windows only. 4979 // - Fred.Ecks@Eng.sun.com, 5-8-98 4980 4981 case KeyEvent.KEY_PRESSED: 4982 case KeyEvent.KEY_RELEASED: 4983 Container p = (Container)((this instanceof Container) ? this : parent); 4984 if (p != null) { 4985 p.preProcessKeyEvent((KeyEvent)e); 4986 if (e.isConsumed()) { 4987 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 4988 focusLog.finest("Pre-process consumed event"); 4989 } 4990 return; 4991 } 4992 } 4993 break; 4994 4995 default: 4996 break; 4997 } 4998 4999 /* 5000 * 6. Deliver event for normal processing 5001 */ 5002 if (newEventsOnly) { 5003 // Filtering needs to really be moved to happen at a lower 5004 // level in order to get maximum performance gain; it is 5005 // here temporarily to ensure the API spec is honored. 5006 // 5007 if (eventEnabled(e)) { 5008 processEvent(e); 5009 } 5010 } else if (id == MouseEvent.MOUSE_WHEEL) { 5011 // newEventsOnly will be false for a listenerless ScrollPane, but 5012 // MouseWheelEvents still need to be dispatched to it so scrolling 5013 // can be done. 5014 autoProcessMouseWheel((MouseWheelEvent)e); 5015 } else if (!(e instanceof MouseEvent && !postsOldMouseEvents())) { 5016 // 5017 // backward compatibility 5018 // 5019 Event olde = e.convertToOld(); 5020 if (olde != null) { 5021 int key = olde.key; 5022 int modifiers = olde.modifiers; 5023 5024 postEvent(olde); 5025 if (olde.isConsumed()) { 5026 e.consume(); 5027 } 5028 // if target changed key or modifier values, copy them 5029 // back to original event 5030 // 5031 switch(olde.id) { 5032 case Event.KEY_PRESS: 5033 case Event.KEY_RELEASE: 5034 case Event.KEY_ACTION: 5035 case Event.KEY_ACTION_RELEASE: 5036 if (olde.key != key) { 5037 ((KeyEvent)e).setKeyChar(olde.getKeyEventChar()); 5038 } 5039 if (olde.modifiers != modifiers) { 5040 ((KeyEvent)e).setModifiers(olde.modifiers); 5041 } 5042 break; 5043 default: 5044 break; 5045 } 5046 } 5047 } 5048 5049 /* 5050 * 9. Allow the peer to process the event. 5051 * Except KeyEvents, they will be processed by peer after 5052 * all KeyEventPostProcessors 5053 * (see DefaultKeyboardFocusManager.dispatchKeyEvent()) 5054 */ 5055 if (!(e instanceof KeyEvent)) { 5056 ComponentPeer tpeer = peer; 5057 if (e instanceof FocusEvent && (tpeer == null || tpeer instanceof LightweightPeer)) { 5058 // if focus owner is lightweight then its native container 5059 // processes event 5060 Component source = (Component)e.getSource(); 5061 if (source != null) { 5062 Container target = source.getNativeContainer(); 5063 if (target != null) { 5064 tpeer = target.peer; 5065 } 5066 } 5067 } 5068 if (tpeer != null) { 5069 tpeer.handleEvent(e); 5070 } 5071 } 5072 5073 if (SunToolkit.isTouchKeyboardAutoShowEnabled() && 5074 (toolkit instanceof SunToolkit) && 5075 ((e instanceof MouseEvent) || (e instanceof FocusEvent))) { 5076 ((SunToolkit)toolkit).showOrHideTouchKeyboard(this, e); 5077 } 5078 } // dispatchEventImpl() 5079 5080 /* 5081 * If newEventsOnly is false, method is called so that ScrollPane can 5082 * override it and handle common-case mouse wheel scrolling. NOP 5083 * for Component. 5084 */ 5085 void autoProcessMouseWheel(MouseWheelEvent e) {} 5086 5087 /* 5088 * Dispatch given MouseWheelEvent to the first ancestor for which 5089 * MouseWheelEvents are enabled. 5090 * 5091 * Returns whether or not event was dispatched to an ancestor 5092 */ 5093 @SuppressWarnings("deprecation") 5094 boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) { 5095 int newX, newY; 5096 newX = e.getX() + getX(); // Coordinates take into account at least 5097 newY = e.getY() + getY(); // the cursor's position relative to this 5098 // Component (e.getX()), and this Component's 5099 // position relative to its parent. 5100 MouseWheelEvent newMWE; 5101 5102 if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) { 5103 eventLog.finest("dispatchMouseWheelToAncestor"); 5104 eventLog.finest("orig event src is of " + e.getSource().getClass()); 5105 } 5106 5107 /* parent field for Window refers to the owning Window. 5108 * MouseWheelEvents should NOT be propagated into owning Windows 5109 */ 5110 synchronized (getTreeLock()) { 5111 Container anc = getParent(); 5112 while (anc != null && !anc.eventEnabled(e)) { 5113 // fix coordinates to be relative to new event source 5114 newX += anc.getX(); 5115 newY += anc.getY(); 5116 5117 if (!(anc instanceof Window)) { 5118 anc = anc.getParent(); 5119 } 5120 else { 5121 break; 5122 } 5123 } 5124 5125 if (eventLog.isLoggable(PlatformLogger.Level.FINEST)) { 5126 eventLog.finest("new event src is " + anc.getClass()); 5127 } 5128 5129 if (anc != null && anc.eventEnabled(e)) { 5130 // Change event to be from new source, with new x,y 5131 // For now, just create a new event - yucky 5132 5133 newMWE = new MouseWheelEvent(anc, // new source 5134 e.getID(), 5135 e.getWhen(), 5136 e.getModifiers(), 5137 newX, // x relative to new source 5138 newY, // y relative to new source 5139 e.getXOnScreen(), 5140 e.getYOnScreen(), 5141 e.getClickCount(), 5142 e.isPopupTrigger(), 5143 e.getScrollType(), 5144 e.getScrollAmount(), 5145 e.getWheelRotation(), 5146 e.getPreciseWheelRotation()); 5147 ((AWTEvent)e).copyPrivateDataInto(newMWE); 5148 // When dispatching a wheel event to 5149 // ancestor, there is no need trying to find descendant 5150 // lightweights to dispatch event to. 5151 // If we dispatch the event to toplevel ancestor, 5152 // this could enclose the loop: 6480024. 5153 anc.dispatchEventToSelf(newMWE); 5154 if (newMWE.isConsumed()) { 5155 e.consume(); 5156 } 5157 return true; 5158 } 5159 } 5160 return false; 5161 } 5162 5163 boolean areInputMethodsEnabled() { 5164 // in 1.2, we assume input method support is required for all 5165 // components that handle key events, but components can turn off 5166 // input methods by calling enableInputMethods(false). 5167 return ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) && 5168 ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || keyListener != null); 5169 } 5170 5171 // REMIND: remove when filtering is handled at lower level 5172 boolean eventEnabled(AWTEvent e) { 5173 return eventTypeEnabled(e.id); 5174 } 5175 5176 boolean eventTypeEnabled(int type) { 5177 switch(type) { 5178 case ComponentEvent.COMPONENT_MOVED: 5179 case ComponentEvent.COMPONENT_RESIZED: 5180 case ComponentEvent.COMPONENT_SHOWN: 5181 case ComponentEvent.COMPONENT_HIDDEN: 5182 if ((eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 5183 componentListener != null) { 5184 return true; 5185 } 5186 break; 5187 case FocusEvent.FOCUS_GAINED: 5188 case FocusEvent.FOCUS_LOST: 5189 if ((eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0 || 5190 focusListener != null) { 5191 return true; 5192 } 5193 break; 5194 case KeyEvent.KEY_PRESSED: 5195 case KeyEvent.KEY_RELEASED: 5196 case KeyEvent.KEY_TYPED: 5197 if ((eventMask & AWTEvent.KEY_EVENT_MASK) != 0 || 5198 keyListener != null) { 5199 return true; 5200 } 5201 break; 5202 case MouseEvent.MOUSE_PRESSED: 5203 case MouseEvent.MOUSE_RELEASED: 5204 case MouseEvent.MOUSE_ENTERED: 5205 case MouseEvent.MOUSE_EXITED: 5206 case MouseEvent.MOUSE_CLICKED: 5207 if ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0 || 5208 mouseListener != null) { 5209 return true; 5210 } 5211 break; 5212 case MouseEvent.MOUSE_MOVED: 5213 case MouseEvent.MOUSE_DRAGGED: 5214 if ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0 || 5215 mouseMotionListener != null) { 5216 return true; 5217 } 5218 break; 5219 case MouseEvent.MOUSE_WHEEL: 5220 if ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0 || 5221 mouseWheelListener != null) { 5222 return true; 5223 } 5224 break; 5225 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: 5226 case InputMethodEvent.CARET_POSITION_CHANGED: 5227 if ((eventMask & AWTEvent.INPUT_METHOD_EVENT_MASK) != 0 || 5228 inputMethodListener != null) { 5229 return true; 5230 } 5231 break; 5232 case HierarchyEvent.HIERARCHY_CHANGED: 5233 if ((eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 5234 hierarchyListener != null) { 5235 return true; 5236 } 5237 break; 5238 case HierarchyEvent.ANCESTOR_MOVED: 5239 case HierarchyEvent.ANCESTOR_RESIZED: 5240 if ((eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || 5241 hierarchyBoundsListener != null) { 5242 return true; 5243 } 5244 break; 5245 case ActionEvent.ACTION_PERFORMED: 5246 if ((eventMask & AWTEvent.ACTION_EVENT_MASK) != 0) { 5247 return true; 5248 } 5249 break; 5250 case TextEvent.TEXT_VALUE_CHANGED: 5251 if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0) { 5252 return true; 5253 } 5254 break; 5255 case ItemEvent.ITEM_STATE_CHANGED: 5256 if ((eventMask & AWTEvent.ITEM_EVENT_MASK) != 0) { 5257 return true; 5258 } 5259 break; 5260 case AdjustmentEvent.ADJUSTMENT_VALUE_CHANGED: 5261 if ((eventMask & AWTEvent.ADJUSTMENT_EVENT_MASK) != 0) { 5262 return true; 5263 } 5264 break; 5265 default: 5266 break; 5267 } 5268 // 5269 // Always pass on events defined by external programs. 5270 // 5271 if (type > AWTEvent.RESERVED_ID_MAX) { 5272 return true; 5273 } 5274 return false; 5275 } 5276 5277 /** 5278 * @deprecated As of JDK version 1.1, 5279 * replaced by dispatchEvent(AWTEvent). 5280 */ 5281 @Deprecated 5282 public boolean postEvent(Event e) { 5283 ComponentPeer peer = this.peer; 5284 5285 if (handleEvent(e)) { 5286 e.consume(); 5287 return true; 5288 } 5289 5290 Component parent = this.parent; 5291 int eventx = e.x; 5292 int eventy = e.y; 5293 if (parent != null) { 5294 e.translate(x, y); 5295 if (parent.postEvent(e)) { 5296 e.consume(); 5297 return true; 5298 } 5299 // restore coords 5300 e.x = eventx; 5301 e.y = eventy; 5302 } 5303 return false; 5304 } 5305 5306 // Event source interfaces 5307 5308 /** 5309 * Adds the specified component listener to receive component events from 5310 * this component. 5311 * If listener {@code l} is {@code null}, 5312 * no exception is thrown and no action is performed. 5313 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5314 * >AWT Threading Issues</a> for details on AWT's threading model. 5315 * 5316 * @param l the component listener 5317 * @see java.awt.event.ComponentEvent 5318 * @see java.awt.event.ComponentListener 5319 * @see #removeComponentListener 5320 * @see #getComponentListeners 5321 * @since 1.1 5322 */ 5323 public synchronized void addComponentListener(ComponentListener l) { 5324 if (l == null) { 5325 return; 5326 } 5327 componentListener = AWTEventMulticaster.add(componentListener, l); 5328 newEventsOnly = true; 5329 } 5330 5331 /** 5332 * Removes the specified component listener so that it no longer 5333 * receives component events from this component. This method performs 5334 * no function, nor does it throw an exception, if the listener 5335 * specified by the argument was not previously added to this component. 5336 * If listener {@code l} is {@code null}, 5337 * no exception is thrown and no action is performed. 5338 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5339 * >AWT Threading Issues</a> for details on AWT's threading model. 5340 * @param l the component listener 5341 * @see java.awt.event.ComponentEvent 5342 * @see java.awt.event.ComponentListener 5343 * @see #addComponentListener 5344 * @see #getComponentListeners 5345 * @since 1.1 5346 */ 5347 public synchronized void removeComponentListener(ComponentListener l) { 5348 if (l == null) { 5349 return; 5350 } 5351 componentListener = AWTEventMulticaster.remove(componentListener, l); 5352 } 5353 5354 /** 5355 * Returns an array of all the component listeners 5356 * registered on this component. 5357 * 5358 * @return all {@code ComponentListener}s of this component 5359 * or an empty array if no component 5360 * listeners are currently registered 5361 * 5362 * @see #addComponentListener 5363 * @see #removeComponentListener 5364 * @since 1.4 5365 */ 5366 public synchronized ComponentListener[] getComponentListeners() { 5367 return getListeners(ComponentListener.class); 5368 } 5369 5370 /** 5371 * Adds the specified focus listener to receive focus events from 5372 * this component when this component gains input focus. 5373 * If listener {@code l} is {@code null}, 5374 * no exception is thrown and no action is performed. 5375 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5376 * >AWT Threading Issues</a> for details on AWT's threading model. 5377 * 5378 * @param l the focus listener 5379 * @see java.awt.event.FocusEvent 5380 * @see java.awt.event.FocusListener 5381 * @see #removeFocusListener 5382 * @see #getFocusListeners 5383 * @since 1.1 5384 */ 5385 public synchronized void addFocusListener(FocusListener l) { 5386 if (l == null) { 5387 return; 5388 } 5389 focusListener = AWTEventMulticaster.add(focusListener, l); 5390 newEventsOnly = true; 5391 5392 // if this is a lightweight component, enable focus events 5393 // in the native container. 5394 if (peer instanceof LightweightPeer) { 5395 parent.proxyEnableEvents(AWTEvent.FOCUS_EVENT_MASK); 5396 } 5397 } 5398 5399 /** 5400 * Removes the specified focus listener so that it no longer 5401 * receives focus events from this component. This method performs 5402 * no function, nor does it throw an exception, if the listener 5403 * specified by the argument was not previously added to this component. 5404 * If listener {@code l} is {@code null}, 5405 * no exception is thrown and no action is performed. 5406 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5407 * >AWT Threading Issues</a> for details on AWT's threading model. 5408 * 5409 * @param l the focus listener 5410 * @see java.awt.event.FocusEvent 5411 * @see java.awt.event.FocusListener 5412 * @see #addFocusListener 5413 * @see #getFocusListeners 5414 * @since 1.1 5415 */ 5416 public synchronized void removeFocusListener(FocusListener l) { 5417 if (l == null) { 5418 return; 5419 } 5420 focusListener = AWTEventMulticaster.remove(focusListener, l); 5421 } 5422 5423 /** 5424 * Returns an array of all the focus listeners 5425 * registered on this component. 5426 * 5427 * @return all of this component's {@code FocusListener}s 5428 * or an empty array if no component 5429 * listeners are currently registered 5430 * 5431 * @see #addFocusListener 5432 * @see #removeFocusListener 5433 * @since 1.4 5434 */ 5435 public synchronized FocusListener[] getFocusListeners() { 5436 return getListeners(FocusListener.class); 5437 } 5438 5439 /** 5440 * Adds the specified hierarchy listener to receive hierarchy changed 5441 * events from this component when the hierarchy to which this container 5442 * belongs changes. 5443 * If listener {@code l} is {@code null}, 5444 * no exception is thrown and no action is performed. 5445 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5446 * >AWT Threading Issues</a> for details on AWT's threading model. 5447 * 5448 * @param l the hierarchy listener 5449 * @see java.awt.event.HierarchyEvent 5450 * @see java.awt.event.HierarchyListener 5451 * @see #removeHierarchyListener 5452 * @see #getHierarchyListeners 5453 * @since 1.3 5454 */ 5455 public void addHierarchyListener(HierarchyListener l) { 5456 if (l == null) { 5457 return; 5458 } 5459 boolean notifyAncestors; 5460 synchronized (this) { 5461 notifyAncestors = 5462 (hierarchyListener == null && 5463 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); 5464 hierarchyListener = AWTEventMulticaster.add(hierarchyListener, l); 5465 notifyAncestors = (notifyAncestors && hierarchyListener != null); 5466 newEventsOnly = true; 5467 } 5468 if (notifyAncestors) { 5469 synchronized (getTreeLock()) { 5470 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, 5471 1); 5472 } 5473 } 5474 } 5475 5476 /** 5477 * Removes the specified hierarchy listener so that it no longer 5478 * receives hierarchy changed events from this component. This method 5479 * performs no function, nor does it throw an exception, if the listener 5480 * specified by the argument was not previously added to this component. 5481 * If listener {@code l} is {@code null}, 5482 * no exception is thrown and no action is performed. 5483 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5484 * >AWT Threading Issues</a> for details on AWT's threading model. 5485 * 5486 * @param l the hierarchy listener 5487 * @see java.awt.event.HierarchyEvent 5488 * @see java.awt.event.HierarchyListener 5489 * @see #addHierarchyListener 5490 * @see #getHierarchyListeners 5491 * @since 1.3 5492 */ 5493 public void removeHierarchyListener(HierarchyListener l) { 5494 if (l == null) { 5495 return; 5496 } 5497 boolean notifyAncestors; 5498 synchronized (this) { 5499 notifyAncestors = 5500 (hierarchyListener != null && 5501 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0); 5502 hierarchyListener = 5503 AWTEventMulticaster.remove(hierarchyListener, l); 5504 notifyAncestors = (notifyAncestors && hierarchyListener == null); 5505 } 5506 if (notifyAncestors) { 5507 synchronized (getTreeLock()) { 5508 adjustListeningChildrenOnParent(AWTEvent.HIERARCHY_EVENT_MASK, 5509 -1); 5510 } 5511 } 5512 } 5513 5514 /** 5515 * Returns an array of all the hierarchy listeners 5516 * registered on this component. 5517 * 5518 * @return all of this component's {@code HierarchyListener}s 5519 * or an empty array if no hierarchy 5520 * listeners are currently registered 5521 * 5522 * @see #addHierarchyListener 5523 * @see #removeHierarchyListener 5524 * @since 1.4 5525 */ 5526 public synchronized HierarchyListener[] getHierarchyListeners() { 5527 return getListeners(HierarchyListener.class); 5528 } 5529 5530 /** 5531 * Adds the specified hierarchy bounds listener to receive hierarchy 5532 * bounds events from this component when the hierarchy to which this 5533 * container belongs changes. 5534 * If listener {@code l} is {@code null}, 5535 * no exception is thrown and no action is performed. 5536 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5537 * >AWT Threading Issues</a> for details on AWT's threading model. 5538 * 5539 * @param l the hierarchy bounds listener 5540 * @see java.awt.event.HierarchyEvent 5541 * @see java.awt.event.HierarchyBoundsListener 5542 * @see #removeHierarchyBoundsListener 5543 * @see #getHierarchyBoundsListeners 5544 * @since 1.3 5545 */ 5546 public void addHierarchyBoundsListener(HierarchyBoundsListener l) { 5547 if (l == null) { 5548 return; 5549 } 5550 boolean notifyAncestors; 5551 synchronized (this) { 5552 notifyAncestors = 5553 (hierarchyBoundsListener == null && 5554 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); 5555 hierarchyBoundsListener = 5556 AWTEventMulticaster.add(hierarchyBoundsListener, l); 5557 notifyAncestors = (notifyAncestors && 5558 hierarchyBoundsListener != null); 5559 newEventsOnly = true; 5560 } 5561 if (notifyAncestors) { 5562 synchronized (getTreeLock()) { 5563 adjustListeningChildrenOnParent( 5564 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, 1); 5565 } 5566 } 5567 } 5568 5569 /** 5570 * Removes the specified hierarchy bounds listener so that it no longer 5571 * receives hierarchy bounds events from this component. This method 5572 * performs no function, nor does it throw an exception, if the listener 5573 * specified by the argument was not previously added to this component. 5574 * If listener {@code l} is {@code null}, 5575 * no exception is thrown and no action is performed. 5576 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5577 * >AWT Threading Issues</a> for details on AWT's threading model. 5578 * 5579 * @param l the hierarchy bounds listener 5580 * @see java.awt.event.HierarchyEvent 5581 * @see java.awt.event.HierarchyBoundsListener 5582 * @see #addHierarchyBoundsListener 5583 * @see #getHierarchyBoundsListeners 5584 * @since 1.3 5585 */ 5586 public void removeHierarchyBoundsListener(HierarchyBoundsListener l) { 5587 if (l == null) { 5588 return; 5589 } 5590 boolean notifyAncestors; 5591 synchronized (this) { 5592 notifyAncestors = 5593 (hierarchyBoundsListener != null && 5594 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0); 5595 hierarchyBoundsListener = 5596 AWTEventMulticaster.remove(hierarchyBoundsListener, l); 5597 notifyAncestors = (notifyAncestors && 5598 hierarchyBoundsListener == null); 5599 } 5600 if (notifyAncestors) { 5601 synchronized (getTreeLock()) { 5602 adjustListeningChildrenOnParent( 5603 AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK, -1); 5604 } 5605 } 5606 } 5607 5608 // Should only be called while holding the tree lock 5609 int numListening(long mask) { 5610 // One mask or the other, but not neither or both. 5611 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) { 5612 if ((mask != AWTEvent.HIERARCHY_EVENT_MASK) && 5613 (mask != AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)) 5614 { 5615 eventLog.fine("Assertion failed"); 5616 } 5617 } 5618 if ((mask == AWTEvent.HIERARCHY_EVENT_MASK && 5619 (hierarchyListener != null || 5620 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0)) || 5621 (mask == AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK && 5622 (hierarchyBoundsListener != null || 5623 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0))) { 5624 return 1; 5625 } else { 5626 return 0; 5627 } 5628 } 5629 5630 // Should only be called while holding tree lock 5631 int countHierarchyMembers() { 5632 return 1; 5633 } 5634 // Should only be called while holding the tree lock 5635 int createHierarchyEvents(int id, Component changed, 5636 Container changedParent, long changeFlags, 5637 boolean enabledOnToolkit) { 5638 switch (id) { 5639 case HierarchyEvent.HIERARCHY_CHANGED: 5640 if (hierarchyListener != null || 5641 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 5642 enabledOnToolkit) { 5643 HierarchyEvent e = new HierarchyEvent(this, id, changed, 5644 changedParent, 5645 changeFlags); 5646 dispatchEvent(e); 5647 return 1; 5648 } 5649 break; 5650 case HierarchyEvent.ANCESTOR_MOVED: 5651 case HierarchyEvent.ANCESTOR_RESIZED: 5652 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) { 5653 if (changeFlags != 0) { 5654 eventLog.fine("Assertion (changeFlags == 0) failed"); 5655 } 5656 } 5657 if (hierarchyBoundsListener != null || 5658 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 || 5659 enabledOnToolkit) { 5660 HierarchyEvent e = new HierarchyEvent(this, id, changed, 5661 changedParent); 5662 dispatchEvent(e); 5663 return 1; 5664 } 5665 break; 5666 default: 5667 // assert false 5668 if (eventLog.isLoggable(PlatformLogger.Level.FINE)) { 5669 eventLog.fine("This code must never be reached"); 5670 } 5671 break; 5672 } 5673 return 0; 5674 } 5675 5676 /** 5677 * Returns an array of all the hierarchy bounds listeners 5678 * registered on this component. 5679 * 5680 * @return all of this component's {@code HierarchyBoundsListener}s 5681 * or an empty array if no hierarchy bounds 5682 * listeners are currently registered 5683 * 5684 * @see #addHierarchyBoundsListener 5685 * @see #removeHierarchyBoundsListener 5686 * @since 1.4 5687 */ 5688 public synchronized HierarchyBoundsListener[] getHierarchyBoundsListeners() { 5689 return getListeners(HierarchyBoundsListener.class); 5690 } 5691 5692 /* 5693 * Should only be called while holding the tree lock. 5694 * It's added only for overriding in java.awt.Window 5695 * because parent in Window is owner. 5696 */ 5697 void adjustListeningChildrenOnParent(long mask, int num) { 5698 if (parent != null) { 5699 parent.adjustListeningChildren(mask, num); 5700 } 5701 } 5702 5703 /** 5704 * Adds the specified key listener to receive key events from 5705 * this component. 5706 * If l is null, no exception is thrown and no action is performed. 5707 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5708 * >AWT Threading Issues</a> for details on AWT's threading model. 5709 * 5710 * @param l the key listener. 5711 * @see java.awt.event.KeyEvent 5712 * @see java.awt.event.KeyListener 5713 * @see #removeKeyListener 5714 * @see #getKeyListeners 5715 * @since 1.1 5716 */ 5717 public synchronized void addKeyListener(KeyListener l) { 5718 if (l == null) { 5719 return; 5720 } 5721 keyListener = AWTEventMulticaster.add(keyListener, l); 5722 newEventsOnly = true; 5723 5724 // if this is a lightweight component, enable key events 5725 // in the native container. 5726 if (peer instanceof LightweightPeer) { 5727 parent.proxyEnableEvents(AWTEvent.KEY_EVENT_MASK); 5728 } 5729 } 5730 5731 /** 5732 * Removes the specified key listener so that it no longer 5733 * receives key events from this component. This method performs 5734 * no function, nor does it throw an exception, if the listener 5735 * specified by the argument was not previously added to this component. 5736 * If listener {@code l} is {@code null}, 5737 * no exception is thrown and no action is performed. 5738 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5739 * >AWT Threading Issues</a> for details on AWT's threading model. 5740 * 5741 * @param l the key listener 5742 * @see java.awt.event.KeyEvent 5743 * @see java.awt.event.KeyListener 5744 * @see #addKeyListener 5745 * @see #getKeyListeners 5746 * @since 1.1 5747 */ 5748 public synchronized void removeKeyListener(KeyListener l) { 5749 if (l == null) { 5750 return; 5751 } 5752 keyListener = AWTEventMulticaster.remove(keyListener, l); 5753 } 5754 5755 /** 5756 * Returns an array of all the key listeners 5757 * registered on this component. 5758 * 5759 * @return all of this component's {@code KeyListener}s 5760 * or an empty array if no key 5761 * listeners are currently registered 5762 * 5763 * @see #addKeyListener 5764 * @see #removeKeyListener 5765 * @since 1.4 5766 */ 5767 public synchronized KeyListener[] getKeyListeners() { 5768 return getListeners(KeyListener.class); 5769 } 5770 5771 /** 5772 * Adds the specified mouse listener to receive mouse events from 5773 * this component. 5774 * If listener {@code l} is {@code null}, 5775 * no exception is thrown and no action is performed. 5776 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5777 * >AWT Threading Issues</a> for details on AWT's threading model. 5778 * 5779 * @param l the mouse listener 5780 * @see java.awt.event.MouseEvent 5781 * @see java.awt.event.MouseListener 5782 * @see #removeMouseListener 5783 * @see #getMouseListeners 5784 * @since 1.1 5785 */ 5786 public synchronized void addMouseListener(MouseListener l) { 5787 if (l == null) { 5788 return; 5789 } 5790 mouseListener = AWTEventMulticaster.add(mouseListener,l); 5791 newEventsOnly = true; 5792 5793 // if this is a lightweight component, enable mouse events 5794 // in the native container. 5795 if (peer instanceof LightweightPeer) { 5796 parent.proxyEnableEvents(AWTEvent.MOUSE_EVENT_MASK); 5797 } 5798 } 5799 5800 /** 5801 * Removes the specified mouse listener so that it no longer 5802 * receives mouse events from this component. This method performs 5803 * no function, nor does it throw an exception, if the listener 5804 * specified by the argument was not previously added to this component. 5805 * If listener {@code l} is {@code null}, 5806 * no exception is thrown and no action is performed. 5807 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5808 * >AWT Threading Issues</a> for details on AWT's threading model. 5809 * 5810 * @param l the mouse listener 5811 * @see java.awt.event.MouseEvent 5812 * @see java.awt.event.MouseListener 5813 * @see #addMouseListener 5814 * @see #getMouseListeners 5815 * @since 1.1 5816 */ 5817 public synchronized void removeMouseListener(MouseListener l) { 5818 if (l == null) { 5819 return; 5820 } 5821 mouseListener = AWTEventMulticaster.remove(mouseListener, l); 5822 } 5823 5824 /** 5825 * Returns an array of all the mouse listeners 5826 * registered on this component. 5827 * 5828 * @return all of this component's {@code MouseListener}s 5829 * or an empty array if no mouse 5830 * listeners are currently registered 5831 * 5832 * @see #addMouseListener 5833 * @see #removeMouseListener 5834 * @since 1.4 5835 */ 5836 public synchronized MouseListener[] getMouseListeners() { 5837 return getListeners(MouseListener.class); 5838 } 5839 5840 /** 5841 * Adds the specified mouse motion listener to receive mouse motion 5842 * events from this component. 5843 * If listener {@code l} is {@code null}, 5844 * no exception is thrown and no action is performed. 5845 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5846 * >AWT Threading Issues</a> for details on AWT's threading model. 5847 * 5848 * @param l the mouse motion listener 5849 * @see java.awt.event.MouseEvent 5850 * @see java.awt.event.MouseMotionListener 5851 * @see #removeMouseMotionListener 5852 * @see #getMouseMotionListeners 5853 * @since 1.1 5854 */ 5855 public synchronized void addMouseMotionListener(MouseMotionListener l) { 5856 if (l == null) { 5857 return; 5858 } 5859 mouseMotionListener = AWTEventMulticaster.add(mouseMotionListener,l); 5860 newEventsOnly = true; 5861 5862 // if this is a lightweight component, enable mouse events 5863 // in the native container. 5864 if (peer instanceof LightweightPeer) { 5865 parent.proxyEnableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); 5866 } 5867 } 5868 5869 /** 5870 * Removes the specified mouse motion listener so that it no longer 5871 * receives mouse motion events from this component. This method performs 5872 * no function, nor does it throw an exception, if the listener 5873 * specified by the argument was not previously added to this component. 5874 * If listener {@code l} is {@code null}, 5875 * no exception is thrown and no action is performed. 5876 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5877 * >AWT Threading Issues</a> for details on AWT's threading model. 5878 * 5879 * @param l the mouse motion listener 5880 * @see java.awt.event.MouseEvent 5881 * @see java.awt.event.MouseMotionListener 5882 * @see #addMouseMotionListener 5883 * @see #getMouseMotionListeners 5884 * @since 1.1 5885 */ 5886 public synchronized void removeMouseMotionListener(MouseMotionListener l) { 5887 if (l == null) { 5888 return; 5889 } 5890 mouseMotionListener = AWTEventMulticaster.remove(mouseMotionListener, l); 5891 } 5892 5893 /** 5894 * Returns an array of all the mouse motion listeners 5895 * registered on this component. 5896 * 5897 * @return all of this component's {@code MouseMotionListener}s 5898 * or an empty array if no mouse motion 5899 * listeners are currently registered 5900 * 5901 * @see #addMouseMotionListener 5902 * @see #removeMouseMotionListener 5903 * @since 1.4 5904 */ 5905 public synchronized MouseMotionListener[] getMouseMotionListeners() { 5906 return getListeners(MouseMotionListener.class); 5907 } 5908 5909 /** 5910 * Adds the specified mouse wheel listener to receive mouse wheel events 5911 * from this component. Containers also receive mouse wheel events from 5912 * sub-components. 5913 * <p> 5914 * For information on how mouse wheel events are dispatched, see 5915 * the class description for {@link MouseWheelEvent}. 5916 * <p> 5917 * If l is {@code null}, no exception is thrown and no 5918 * action is performed. 5919 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5920 * >AWT Threading Issues</a> for details on AWT's threading model. 5921 * 5922 * @param l the mouse wheel listener 5923 * @see java.awt.event.MouseWheelEvent 5924 * @see java.awt.event.MouseWheelListener 5925 * @see #removeMouseWheelListener 5926 * @see #getMouseWheelListeners 5927 * @since 1.4 5928 */ 5929 public synchronized void addMouseWheelListener(MouseWheelListener l) { 5930 if (l == null) { 5931 return; 5932 } 5933 mouseWheelListener = AWTEventMulticaster.add(mouseWheelListener,l); 5934 newEventsOnly = true; 5935 5936 // if this is a lightweight component, enable mouse events 5937 // in the native container. 5938 if (peer instanceof LightweightPeer) { 5939 parent.proxyEnableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK); 5940 } 5941 } 5942 5943 /** 5944 * Removes the specified mouse wheel listener so that it no longer 5945 * receives mouse wheel events from this component. This method performs 5946 * no function, nor does it throw an exception, if the listener 5947 * specified by the argument was not previously added to this component. 5948 * If l is null, no exception is thrown and no action is performed. 5949 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 5950 * >AWT Threading Issues</a> for details on AWT's threading model. 5951 * 5952 * @param l the mouse wheel listener. 5953 * @see java.awt.event.MouseWheelEvent 5954 * @see java.awt.event.MouseWheelListener 5955 * @see #addMouseWheelListener 5956 * @see #getMouseWheelListeners 5957 * @since 1.4 5958 */ 5959 public synchronized void removeMouseWheelListener(MouseWheelListener l) { 5960 if (l == null) { 5961 return; 5962 } 5963 mouseWheelListener = AWTEventMulticaster.remove(mouseWheelListener, l); 5964 } 5965 5966 /** 5967 * Returns an array of all the mouse wheel listeners 5968 * registered on this component. 5969 * 5970 * @return all of this component's {@code MouseWheelListener}s 5971 * or an empty array if no mouse wheel 5972 * listeners are currently registered 5973 * 5974 * @see #addMouseWheelListener 5975 * @see #removeMouseWheelListener 5976 * @since 1.4 5977 */ 5978 public synchronized MouseWheelListener[] getMouseWheelListeners() { 5979 return getListeners(MouseWheelListener.class); 5980 } 5981 5982 /** 5983 * Adds the specified input method listener to receive 5984 * input method events from this component. A component will 5985 * only receive input method events from input methods 5986 * if it also overrides {@code getInputMethodRequests} to return an 5987 * {@code InputMethodRequests} instance. 5988 * If listener {@code l} is {@code null}, 5989 * no exception is thrown and no action is performed. 5990 * <p>Refer to <a href="{@docRoot}/java/awt/doc-files/AWTThreadIssues.html#ListenersThreads" 5991 * >AWT Threading Issues</a> for details on AWT's threading model. 5992 * 5993 * @param l the input method listener 5994 * @see java.awt.event.InputMethodEvent 5995 * @see java.awt.event.InputMethodListener 5996 * @see #removeInputMethodListener 5997 * @see #getInputMethodListeners 5998 * @see #getInputMethodRequests 5999 * @since 1.2 6000 */ 6001 public synchronized void addInputMethodListener(InputMethodListener l) { 6002 if (l == null) { 6003 return; 6004 } 6005 inputMethodListener = AWTEventMulticaster.add(inputMethodListener, l); 6006 newEventsOnly = true; 6007 } 6008 6009 /** 6010 * Removes the specified input method listener so that it no longer 6011 * receives input method events from this component. This method performs 6012 * no function, nor does it throw an exception, if the listener 6013 * specified by the argument was not previously added to this component. 6014 * If listener {@code l} is {@code null}, 6015 * no exception is thrown and no action is performed. 6016 * <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads" 6017 * >AWT Threading Issues</a> for details on AWT's threading model. 6018 * 6019 * @param l the input method listener 6020 * @see java.awt.event.InputMethodEvent 6021 * @see java.awt.event.InputMethodListener 6022 * @see #addInputMethodListener 6023 * @see #getInputMethodListeners 6024 * @since 1.2 6025 */ 6026 public synchronized void removeInputMethodListener(InputMethodListener l) { 6027 if (l == null) { 6028 return; 6029 } 6030 inputMethodListener = AWTEventMulticaster.remove(inputMethodListener, l); 6031 } 6032 6033 /** 6034 * Returns an array of all the input method listeners 6035 * registered on this component. 6036 * 6037 * @return all of this component's {@code InputMethodListener}s 6038 * or an empty array if no input method 6039 * listeners are currently registered 6040 * 6041 * @see #addInputMethodListener 6042 * @see #removeInputMethodListener 6043 * @since 1.4 6044 */ 6045 public synchronized InputMethodListener[] getInputMethodListeners() { 6046 return getListeners(InputMethodListener.class); 6047 } 6048 6049 /** 6050 * Returns an array of all the objects currently registered 6051 * as <code><em>Foo</em>Listener</code>s 6052 * upon this {@code Component}. 6053 * <code><em>Foo</em>Listener</code>s are registered using the 6054 * <code>add<em>Foo</em>Listener</code> method. 6055 * 6056 * <p> 6057 * You can specify the {@code listenerType} argument 6058 * with a class literal, such as 6059 * <code><em>Foo</em>Listener.class</code>. 6060 * For example, you can query a 6061 * {@code Component c} 6062 * for its mouse listeners with the following code: 6063 * 6064 * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre> 6065 * 6066 * If no such listeners exist, this method returns an empty array. 6067 * 6068 * @param <T> the type of the listeners 6069 * @param listenerType the type of listeners requested; this parameter 6070 * should specify an interface that descends from 6071 * {@code java.util.EventListener} 6072 * @return an array of all objects registered as 6073 * <code><em>Foo</em>Listener</code>s on this component, 6074 * or an empty array if no such listeners have been added 6075 * @exception ClassCastException if {@code listenerType} 6076 * doesn't specify a class or interface that implements 6077 * {@code java.util.EventListener} 6078 * @throws NullPointerException if {@code listenerType} is {@code null} 6079 * @see #getComponentListeners 6080 * @see #getFocusListeners 6081 * @see #getHierarchyListeners 6082 * @see #getHierarchyBoundsListeners 6083 * @see #getKeyListeners 6084 * @see #getMouseListeners 6085 * @see #getMouseMotionListeners 6086 * @see #getMouseWheelListeners 6087 * @see #getInputMethodListeners 6088 * @see #getPropertyChangeListeners 6089 * 6090 * @since 1.3 6091 */ 6092 @SuppressWarnings("unchecked") 6093 public <T extends EventListener> T[] getListeners(Class<T> listenerType) { 6094 EventListener l = null; 6095 if (listenerType == ComponentListener.class) { 6096 l = componentListener; 6097 } else if (listenerType == FocusListener.class) { 6098 l = focusListener; 6099 } else if (listenerType == HierarchyListener.class) { 6100 l = hierarchyListener; 6101 } else if (listenerType == HierarchyBoundsListener.class) { 6102 l = hierarchyBoundsListener; 6103 } else if (listenerType == KeyListener.class) { 6104 l = keyListener; 6105 } else if (listenerType == MouseListener.class) { 6106 l = mouseListener; 6107 } else if (listenerType == MouseMotionListener.class) { 6108 l = mouseMotionListener; 6109 } else if (listenerType == MouseWheelListener.class) { 6110 l = mouseWheelListener; 6111 } else if (listenerType == InputMethodListener.class) { 6112 l = inputMethodListener; 6113 } else if (listenerType == PropertyChangeListener.class) { 6114 return (T[])getPropertyChangeListeners(); 6115 } 6116 return AWTEventMulticaster.getListeners(l, listenerType); 6117 } 6118 6119 /** 6120 * Gets the input method request handler which supports 6121 * requests from input methods for this component. A component 6122 * that supports on-the-spot text input must override this 6123 * method to return an {@code InputMethodRequests} instance. 6124 * At the same time, it also has to handle input method events. 6125 * 6126 * @return the input method request handler for this component, 6127 * {@code null} by default 6128 * @see #addInputMethodListener 6129 * @since 1.2 6130 */ 6131 public InputMethodRequests getInputMethodRequests() { 6132 return null; 6133 } 6134 6135 /** 6136 * Gets the input context used by this component for handling 6137 * the communication with input methods when text is entered 6138 * in this component. By default, the input context used for 6139 * the parent component is returned. Components may 6140 * override this to return a private input context. 6141 * 6142 * @return the input context used by this component; 6143 * {@code null} if no context can be determined 6144 * @since 1.2 6145 */ 6146 public InputContext getInputContext() { 6147 Container parent = this.parent; 6148 if (parent == null) { 6149 return null; 6150 } else { 6151 return parent.getInputContext(); 6152 } 6153 } 6154 6155 /** 6156 * Enables the events defined by the specified event mask parameter 6157 * to be delivered to this component. 6158 * <p> 6159 * Event types are automatically enabled when a listener for 6160 * that event type is added to the component. 6161 * <p> 6162 * This method only needs to be invoked by subclasses of 6163 * {@code Component} which desire to have the specified event 6164 * types delivered to {@code processEvent} regardless of whether 6165 * or not a listener is registered. 6166 * @param eventsToEnable the event mask defining the event types 6167 * @see #processEvent 6168 * @see #disableEvents 6169 * @see AWTEvent 6170 * @since 1.1 6171 */ 6172 protected final void enableEvents(long eventsToEnable) { 6173 long notifyAncestors = 0; 6174 synchronized (this) { 6175 if ((eventsToEnable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && 6176 hierarchyListener == null && 6177 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) == 0) { 6178 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; 6179 } 6180 if ((eventsToEnable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0 && 6181 hierarchyBoundsListener == null && 6182 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) == 0) { 6183 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; 6184 } 6185 eventMask |= eventsToEnable; 6186 newEventsOnly = true; 6187 } 6188 6189 // if this is a lightweight component, enable mouse events 6190 // in the native container. 6191 if (peer instanceof LightweightPeer) { 6192 parent.proxyEnableEvents(eventMask); 6193 } 6194 if (notifyAncestors != 0) { 6195 synchronized (getTreeLock()) { 6196 adjustListeningChildrenOnParent(notifyAncestors, 1); 6197 } 6198 } 6199 } 6200 6201 /** 6202 * Disables the events defined by the specified event mask parameter 6203 * from being delivered to this component. 6204 * @param eventsToDisable the event mask defining the event types 6205 * @see #enableEvents 6206 * @since 1.1 6207 */ 6208 protected final void disableEvents(long eventsToDisable) { 6209 long notifyAncestors = 0; 6210 synchronized (this) { 6211 if ((eventsToDisable & AWTEvent.HIERARCHY_EVENT_MASK) != 0 && 6212 hierarchyListener == null && 6213 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0) { 6214 notifyAncestors |= AWTEvent.HIERARCHY_EVENT_MASK; 6215 } 6216 if ((eventsToDisable & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK)!=0 && 6217 hierarchyBoundsListener == null && 6218 (eventMask & AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK) != 0) { 6219 notifyAncestors |= AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK; 6220 } 6221 eventMask &= ~eventsToDisable; 6222 } 6223 if (notifyAncestors != 0) { 6224 synchronized (getTreeLock()) { 6225 adjustListeningChildrenOnParent(notifyAncestors, -1); 6226 } 6227 } 6228 } 6229 6230 transient sun.awt.EventQueueItem[] eventCache; 6231 6232 /** 6233 * @see #isCoalescingEnabled 6234 * @see #checkCoalescing 6235 */ 6236 private transient boolean coalescingEnabled = checkCoalescing(); 6237 6238 /** 6239 * Weak map of known coalesceEvent overriders. 6240 * Value indicates whether overriden. 6241 * Bootstrap classes are not included. 6242 */ 6243 private static final Map<Class<?>, Boolean> coalesceMap = 6244 new java.util.WeakHashMap<Class<?>, Boolean>(); 6245 6246 /** 6247 * Indicates whether this class overrides coalesceEvents. 6248 * It is assumed that all classes that are loaded from the bootstrap 6249 * do not. 6250 * The bootstrap class loader is assumed to be represented by null. 6251 * We do not check that the method really overrides 6252 * (it might be static, private or package private). 6253 */ 6254 private boolean checkCoalescing() { 6255 if (getClass().getClassLoader()==null) { 6256 return false; 6257 } 6258 final Class<? extends Component> clazz = getClass(); 6259 synchronized (coalesceMap) { 6260 // Check cache. 6261 Boolean value = coalesceMap.get(clazz); 6262 if (value != null) { 6263 return value; 6264 } 6265 6266 // Need to check non-bootstraps. 6267 Boolean enabled = java.security.AccessController.doPrivileged( 6268 new java.security.PrivilegedAction<Boolean>() { 6269 public Boolean run() { 6270 return isCoalesceEventsOverriden(clazz); 6271 } 6272 } 6273 ); 6274 coalesceMap.put(clazz, enabled); 6275 return enabled; 6276 } 6277 } 6278 6279 /** 6280 * Parameter types of coalesceEvents(AWTEvent,AWTEVent). 6281 */ 6282 private static final Class<?>[] coalesceEventsParams = { 6283 AWTEvent.class, AWTEvent.class 6284 }; 6285 6286 /** 6287 * Indicates whether a class or its superclasses override coalesceEvents. 6288 * Must be called with lock on coalesceMap and privileged. 6289 * @see #checkCoalescing 6290 */ 6291 private static boolean isCoalesceEventsOverriden(Class<?> clazz) { 6292 assert Thread.holdsLock(coalesceMap); 6293 6294 // First check superclass - we may not need to bother ourselves. 6295 Class<?> superclass = clazz.getSuperclass(); 6296 if (superclass == null) { 6297 // Only occurs on implementations that 6298 // do not use null to represent the bootstrap class loader. 6299 return false; 6300 } 6301 if (superclass.getClassLoader() != null) { 6302 Boolean value = coalesceMap.get(superclass); 6303 if (value == null) { 6304 // Not done already - recurse. 6305 if (isCoalesceEventsOverriden(superclass)) { 6306 coalesceMap.put(superclass, true); 6307 return true; 6308 } 6309 } else if (value) { 6310 return true; 6311 } 6312 } 6313 6314 try { 6315 // Throws if not overriden. 6316 clazz.getDeclaredMethod( 6317 "coalesceEvents", coalesceEventsParams 6318 ); 6319 return true; 6320 } catch (NoSuchMethodException e) { 6321 // Not present in this class. 6322 return false; 6323 } 6324 } 6325 6326 /** 6327 * Indicates whether coalesceEvents may do something. 6328 */ 6329 final boolean isCoalescingEnabled() { 6330 return coalescingEnabled; 6331 } 6332 6333 6334 /** 6335 * Potentially coalesce an event being posted with an existing 6336 * event. This method is called by {@code EventQueue.postEvent} 6337 * if an event with the same ID as the event to be posted is found in 6338 * the queue (both events must have this component as their source). 6339 * This method either returns a coalesced event which replaces 6340 * the existing event (and the new event is then discarded), or 6341 * {@code null} to indicate that no combining should be done 6342 * (add the second event to the end of the queue). Either event 6343 * parameter may be modified and returned, as the other one is discarded 6344 * unless {@code null} is returned. 6345 * <p> 6346 * This implementation of {@code coalesceEvents} coalesces 6347 * two event types: mouse move (and drag) events, 6348 * and paint (and update) events. 6349 * For mouse move events the last event is always returned, causing 6350 * intermediate moves to be discarded. For paint events, the new 6351 * event is coalesced into a complex {@code RepaintArea} in the peer. 6352 * The new {@code AWTEvent} is always returned. 6353 * 6354 * @param existingEvent the event already on the {@code EventQueue} 6355 * @param newEvent the event being posted to the 6356 * {@code EventQueue} 6357 * @return a coalesced event, or {@code null} indicating that no 6358 * coalescing was done 6359 */ 6360 protected AWTEvent coalesceEvents(AWTEvent existingEvent, 6361 AWTEvent newEvent) { 6362 return null; 6363 } 6364 6365 /** 6366 * Processes events occurring on this component. By default this 6367 * method calls the appropriate 6368 * <code>process<event type>Event</code> 6369 * method for the given class of event. 6370 * <p>Note that if the event parameter is {@code null} 6371 * the behavior is unspecified and may result in an 6372 * exception. 6373 * 6374 * @param e the event 6375 * @see #processComponentEvent 6376 * @see #processFocusEvent 6377 * @see #processKeyEvent 6378 * @see #processMouseEvent 6379 * @see #processMouseMotionEvent 6380 * @see #processInputMethodEvent 6381 * @see #processHierarchyEvent 6382 * @see #processMouseWheelEvent 6383 * @since 1.1 6384 */ 6385 protected void processEvent(AWTEvent e) { 6386 if (e instanceof FocusEvent) { 6387 processFocusEvent((FocusEvent)e); 6388 6389 } else if (e instanceof MouseEvent) { 6390 switch(e.getID()) { 6391 case MouseEvent.MOUSE_PRESSED: 6392 case MouseEvent.MOUSE_RELEASED: 6393 case MouseEvent.MOUSE_CLICKED: 6394 case MouseEvent.MOUSE_ENTERED: 6395 case MouseEvent.MOUSE_EXITED: 6396 processMouseEvent((MouseEvent)e); 6397 break; 6398 case MouseEvent.MOUSE_MOVED: 6399 case MouseEvent.MOUSE_DRAGGED: 6400 processMouseMotionEvent((MouseEvent)e); 6401 break; 6402 case MouseEvent.MOUSE_WHEEL: 6403 processMouseWheelEvent((MouseWheelEvent)e); 6404 break; 6405 } 6406 6407 } else if (e instanceof KeyEvent) { 6408 processKeyEvent((KeyEvent)e); 6409 6410 } else if (e instanceof ComponentEvent) { 6411 processComponentEvent((ComponentEvent)e); 6412 } else if (e instanceof InputMethodEvent) { 6413 processInputMethodEvent((InputMethodEvent)e); 6414 } else if (e instanceof HierarchyEvent) { 6415 switch (e.getID()) { 6416 case HierarchyEvent.HIERARCHY_CHANGED: 6417 processHierarchyEvent((HierarchyEvent)e); 6418 break; 6419 case HierarchyEvent.ANCESTOR_MOVED: 6420 case HierarchyEvent.ANCESTOR_RESIZED: 6421 processHierarchyBoundsEvent((HierarchyEvent)e); 6422 break; 6423 } 6424 } 6425 } 6426 6427 /** 6428 * Processes component events occurring on this component by 6429 * dispatching them to any registered 6430 * {@code ComponentListener} objects. 6431 * <p> 6432 * This method is not called unless component events are 6433 * enabled for this component. Component events are enabled 6434 * when one of the following occurs: 6435 * <ul> 6436 * <li>A {@code ComponentListener} object is registered 6437 * via {@code addComponentListener}. 6438 * <li>Component events are enabled via {@code enableEvents}. 6439 * </ul> 6440 * <p>Note that if the event parameter is {@code null} 6441 * the behavior is unspecified and may result in an 6442 * exception. 6443 * 6444 * @param e the component event 6445 * @see java.awt.event.ComponentEvent 6446 * @see java.awt.event.ComponentListener 6447 * @see #addComponentListener 6448 * @see #enableEvents 6449 * @since 1.1 6450 */ 6451 protected void processComponentEvent(ComponentEvent e) { 6452 ComponentListener listener = componentListener; 6453 if (listener != null) { 6454 int id = e.getID(); 6455 switch(id) { 6456 case ComponentEvent.COMPONENT_RESIZED: 6457 listener.componentResized(e); 6458 break; 6459 case ComponentEvent.COMPONENT_MOVED: 6460 listener.componentMoved(e); 6461 break; 6462 case ComponentEvent.COMPONENT_SHOWN: 6463 listener.componentShown(e); 6464 break; 6465 case ComponentEvent.COMPONENT_HIDDEN: 6466 listener.componentHidden(e); 6467 break; 6468 } 6469 } 6470 } 6471 6472 /** 6473 * Processes focus events occurring on this component by 6474 * dispatching them to any registered 6475 * {@code FocusListener} objects. 6476 * <p> 6477 * This method is not called unless focus events are 6478 * enabled for this component. Focus events are enabled 6479 * when one of the following occurs: 6480 * <ul> 6481 * <li>A {@code FocusListener} object is registered 6482 * via {@code addFocusListener}. 6483 * <li>Focus events are enabled via {@code enableEvents}. 6484 * </ul> 6485 * <p> 6486 * If focus events are enabled for a {@code Component}, 6487 * the current {@code KeyboardFocusManager} determines 6488 * whether or not a focus event should be dispatched to 6489 * registered {@code FocusListener} objects. If the 6490 * events are to be dispatched, the {@code KeyboardFocusManager} 6491 * calls the {@code Component}'s {@code dispatchEvent} 6492 * method, which results in a call to the {@code Component}'s 6493 * {@code processFocusEvent} method. 6494 * <p> 6495 * If focus events are enabled for a {@code Component}, calling 6496 * the {@code Component}'s {@code dispatchEvent} method 6497 * with a {@code FocusEvent} as the argument will result in a 6498 * call to the {@code Component}'s {@code processFocusEvent} 6499 * method regardless of the current {@code KeyboardFocusManager}. 6500 * 6501 * <p>Note that if the event parameter is {@code null} 6502 * the behavior is unspecified and may result in an 6503 * exception. 6504 * 6505 * @param e the focus event 6506 * @see java.awt.event.FocusEvent 6507 * @see java.awt.event.FocusListener 6508 * @see java.awt.KeyboardFocusManager 6509 * @see #addFocusListener 6510 * @see #enableEvents 6511 * @see #dispatchEvent 6512 * @since 1.1 6513 */ 6514 protected void processFocusEvent(FocusEvent e) { 6515 FocusListener listener = focusListener; 6516 if (listener != null) { 6517 int id = e.getID(); 6518 switch(id) { 6519 case FocusEvent.FOCUS_GAINED: 6520 listener.focusGained(e); 6521 break; 6522 case FocusEvent.FOCUS_LOST: 6523 listener.focusLost(e); 6524 break; 6525 } 6526 } 6527 } 6528 6529 /** 6530 * Processes key events occurring on this component by 6531 * dispatching them to any registered 6532 * {@code KeyListener} objects. 6533 * <p> 6534 * This method is not called unless key events are 6535 * enabled for this component. Key events are enabled 6536 * when one of the following occurs: 6537 * <ul> 6538 * <li>A {@code KeyListener} object is registered 6539 * via {@code addKeyListener}. 6540 * <li>Key events are enabled via {@code enableEvents}. 6541 * </ul> 6542 * 6543 * <p> 6544 * If key events are enabled for a {@code Component}, 6545 * the current {@code KeyboardFocusManager} determines 6546 * whether or not a key event should be dispatched to 6547 * registered {@code KeyListener} objects. The 6548 * {@code DefaultKeyboardFocusManager} will not dispatch 6549 * key events to a {@code Component} that is not the focus 6550 * owner or is not showing. 6551 * <p> 6552 * As of J2SE 1.4, {@code KeyEvent}s are redirected to 6553 * the focus owner. Please see the 6554 * <a href="doc-files/FocusSpec.html">Focus Specification</a> 6555 * for further information. 6556 * <p> 6557 * Calling a {@code Component}'s {@code dispatchEvent} 6558 * method with a {@code KeyEvent} as the argument will 6559 * result in a call to the {@code Component}'s 6560 * {@code processKeyEvent} method regardless of the 6561 * current {@code KeyboardFocusManager} as long as the 6562 * component is showing, focused, and enabled, and key events 6563 * are enabled on it. 6564 * <p>If the event parameter is {@code null} 6565 * the behavior is unspecified and may result in an 6566 * exception. 6567 * 6568 * @param e the key event 6569 * @see java.awt.event.KeyEvent 6570 * @see java.awt.event.KeyListener 6571 * @see java.awt.KeyboardFocusManager 6572 * @see java.awt.DefaultKeyboardFocusManager 6573 * @see #processEvent 6574 * @see #dispatchEvent 6575 * @see #addKeyListener 6576 * @see #enableEvents 6577 * @see #isShowing 6578 * @since 1.1 6579 */ 6580 protected void processKeyEvent(KeyEvent e) { 6581 KeyListener listener = keyListener; 6582 if (listener != null) { 6583 int id = e.getID(); 6584 switch(id) { 6585 case KeyEvent.KEY_TYPED: 6586 listener.keyTyped(e); 6587 break; 6588 case KeyEvent.KEY_PRESSED: 6589 listener.keyPressed(e); 6590 break; 6591 case KeyEvent.KEY_RELEASED: 6592 listener.keyReleased(e); 6593 break; 6594 } 6595 } 6596 } 6597 6598 /** 6599 * Processes mouse events occurring on this component by 6600 * dispatching them to any registered 6601 * {@code MouseListener} objects. 6602 * <p> 6603 * This method is not called unless mouse events are 6604 * enabled for this component. Mouse events are enabled 6605 * when one of the following occurs: 6606 * <ul> 6607 * <li>A {@code MouseListener} object is registered 6608 * via {@code addMouseListener}. 6609 * <li>Mouse events are enabled via {@code enableEvents}. 6610 * </ul> 6611 * <p>Note that if the event parameter is {@code null} 6612 * the behavior is unspecified and may result in an 6613 * exception. 6614 * 6615 * @param e the mouse event 6616 * @see java.awt.event.MouseEvent 6617 * @see java.awt.event.MouseListener 6618 * @see #addMouseListener 6619 * @see #enableEvents 6620 * @since 1.1 6621 */ 6622 protected void processMouseEvent(MouseEvent e) { 6623 MouseListener listener = mouseListener; 6624 if (listener != null) { 6625 int id = e.getID(); 6626 switch(id) { 6627 case MouseEvent.MOUSE_PRESSED: 6628 listener.mousePressed(e); 6629 break; 6630 case MouseEvent.MOUSE_RELEASED: 6631 listener.mouseReleased(e); 6632 break; 6633 case MouseEvent.MOUSE_CLICKED: 6634 listener.mouseClicked(e); 6635 break; 6636 case MouseEvent.MOUSE_EXITED: 6637 listener.mouseExited(e); 6638 break; 6639 case MouseEvent.MOUSE_ENTERED: 6640 listener.mouseEntered(e); 6641 break; 6642 } 6643 } 6644 } 6645 6646 /** 6647 * Processes mouse motion events occurring on this component by 6648 * dispatching them to any registered 6649 * {@code MouseMotionListener} objects. 6650 * <p> 6651 * This method is not called unless mouse motion events are 6652 * enabled for this component. Mouse motion events are enabled 6653 * when one of the following occurs: 6654 * <ul> 6655 * <li>A {@code MouseMotionListener} object is registered 6656 * via {@code addMouseMotionListener}. 6657 * <li>Mouse motion events are enabled via {@code enableEvents}. 6658 * </ul> 6659 * <p>Note that if the event parameter is {@code null} 6660 * the behavior is unspecified and may result in an 6661 * exception. 6662 * 6663 * @param e the mouse motion event 6664 * @see java.awt.event.MouseEvent 6665 * @see java.awt.event.MouseMotionListener 6666 * @see #addMouseMotionListener 6667 * @see #enableEvents 6668 * @since 1.1 6669 */ 6670 protected void processMouseMotionEvent(MouseEvent e) { 6671 MouseMotionListener listener = mouseMotionListener; 6672 if (listener != null) { 6673 int id = e.getID(); 6674 switch(id) { 6675 case MouseEvent.MOUSE_MOVED: 6676 listener.mouseMoved(e); 6677 break; 6678 case MouseEvent.MOUSE_DRAGGED: 6679 listener.mouseDragged(e); 6680 break; 6681 } 6682 } 6683 } 6684 6685 /** 6686 * Processes mouse wheel events occurring on this component by 6687 * dispatching them to any registered 6688 * {@code MouseWheelListener} objects. 6689 * <p> 6690 * This method is not called unless mouse wheel events are 6691 * enabled for this component. Mouse wheel events are enabled 6692 * when one of the following occurs: 6693 * <ul> 6694 * <li>A {@code MouseWheelListener} object is registered 6695 * via {@code addMouseWheelListener}. 6696 * <li>Mouse wheel events are enabled via {@code enableEvents}. 6697 * </ul> 6698 * <p> 6699 * For information on how mouse wheel events are dispatched, see 6700 * the class description for {@link MouseWheelEvent}. 6701 * <p> 6702 * Note that if the event parameter is {@code null} 6703 * the behavior is unspecified and may result in an 6704 * exception. 6705 * 6706 * @param e the mouse wheel event 6707 * @see java.awt.event.MouseWheelEvent 6708 * @see java.awt.event.MouseWheelListener 6709 * @see #addMouseWheelListener 6710 * @see #enableEvents 6711 * @since 1.4 6712 */ 6713 protected void processMouseWheelEvent(MouseWheelEvent e) { 6714 MouseWheelListener listener = mouseWheelListener; 6715 if (listener != null) { 6716 int id = e.getID(); 6717 switch(id) { 6718 case MouseEvent.MOUSE_WHEEL: 6719 listener.mouseWheelMoved(e); 6720 break; 6721 } 6722 } 6723 } 6724 6725 boolean postsOldMouseEvents() { 6726 return false; 6727 } 6728 6729 /** 6730 * Processes input method events occurring on this component by 6731 * dispatching them to any registered 6732 * {@code InputMethodListener} objects. 6733 * <p> 6734 * This method is not called unless input method events 6735 * are enabled for this component. Input method events are enabled 6736 * when one of the following occurs: 6737 * <ul> 6738 * <li>An {@code InputMethodListener} object is registered 6739 * via {@code addInputMethodListener}. 6740 * <li>Input method events are enabled via {@code enableEvents}. 6741 * </ul> 6742 * <p>Note that if the event parameter is {@code null} 6743 * the behavior is unspecified and may result in an 6744 * exception. 6745 * 6746 * @param e the input method event 6747 * @see java.awt.event.InputMethodEvent 6748 * @see java.awt.event.InputMethodListener 6749 * @see #addInputMethodListener 6750 * @see #enableEvents 6751 * @since 1.2 6752 */ 6753 protected void processInputMethodEvent(InputMethodEvent e) { 6754 InputMethodListener listener = inputMethodListener; 6755 if (listener != null) { 6756 int id = e.getID(); 6757 switch (id) { 6758 case InputMethodEvent.INPUT_METHOD_TEXT_CHANGED: 6759 listener.inputMethodTextChanged(e); 6760 break; 6761 case InputMethodEvent.CARET_POSITION_CHANGED: 6762 listener.caretPositionChanged(e); 6763 break; 6764 } 6765 } 6766 } 6767 6768 /** 6769 * Processes hierarchy events occurring on this component by 6770 * dispatching them to any registered 6771 * {@code HierarchyListener} objects. 6772 * <p> 6773 * This method is not called unless hierarchy events 6774 * are enabled for this component. Hierarchy events are enabled 6775 * when one of the following occurs: 6776 * <ul> 6777 * <li>An {@code HierarchyListener} object is registered 6778 * via {@code addHierarchyListener}. 6779 * <li>Hierarchy events are enabled via {@code enableEvents}. 6780 * </ul> 6781 * <p>Note that if the event parameter is {@code null} 6782 * the behavior is unspecified and may result in an 6783 * exception. 6784 * 6785 * @param e the hierarchy event 6786 * @see java.awt.event.HierarchyEvent 6787 * @see java.awt.event.HierarchyListener 6788 * @see #addHierarchyListener 6789 * @see #enableEvents 6790 * @since 1.3 6791 */ 6792 protected void processHierarchyEvent(HierarchyEvent e) { 6793 HierarchyListener listener = hierarchyListener; 6794 if (listener != null) { 6795 int id = e.getID(); 6796 switch (id) { 6797 case HierarchyEvent.HIERARCHY_CHANGED: 6798 listener.hierarchyChanged(e); 6799 break; 6800 } 6801 } 6802 } 6803 6804 /** 6805 * Processes hierarchy bounds events occurring on this component by 6806 * dispatching them to any registered 6807 * {@code HierarchyBoundsListener} objects. 6808 * <p> 6809 * This method is not called unless hierarchy bounds events 6810 * are enabled for this component. Hierarchy bounds events are enabled 6811 * when one of the following occurs: 6812 * <ul> 6813 * <li>An {@code HierarchyBoundsListener} object is registered 6814 * via {@code addHierarchyBoundsListener}. 6815 * <li>Hierarchy bounds events are enabled via {@code enableEvents}. 6816 * </ul> 6817 * <p>Note that if the event parameter is {@code null} 6818 * the behavior is unspecified and may result in an 6819 * exception. 6820 * 6821 * @param e the hierarchy event 6822 * @see java.awt.event.HierarchyEvent 6823 * @see java.awt.event.HierarchyBoundsListener 6824 * @see #addHierarchyBoundsListener 6825 * @see #enableEvents 6826 * @since 1.3 6827 */ 6828 protected void processHierarchyBoundsEvent(HierarchyEvent e) { 6829 HierarchyBoundsListener listener = hierarchyBoundsListener; 6830 if (listener != null) { 6831 int id = e.getID(); 6832 switch (id) { 6833 case HierarchyEvent.ANCESTOR_MOVED: 6834 listener.ancestorMoved(e); 6835 break; 6836 case HierarchyEvent.ANCESTOR_RESIZED: 6837 listener.ancestorResized(e); 6838 break; 6839 } 6840 } 6841 } 6842 6843 /** 6844 * @param evt the event to handle 6845 * @return {@code true} if the event was handled, {@code false} otherwise 6846 * @deprecated As of JDK version 1.1 6847 * replaced by processEvent(AWTEvent). 6848 */ 6849 @Deprecated 6850 public boolean handleEvent(Event evt) { 6851 switch (evt.id) { 6852 case Event.MOUSE_ENTER: 6853 return mouseEnter(evt, evt.x, evt.y); 6854 6855 case Event.MOUSE_EXIT: 6856 return mouseExit(evt, evt.x, evt.y); 6857 6858 case Event.MOUSE_MOVE: 6859 return mouseMove(evt, evt.x, evt.y); 6860 6861 case Event.MOUSE_DOWN: 6862 return mouseDown(evt, evt.x, evt.y); 6863 6864 case Event.MOUSE_DRAG: 6865 return mouseDrag(evt, evt.x, evt.y); 6866 6867 case Event.MOUSE_UP: 6868 return mouseUp(evt, evt.x, evt.y); 6869 6870 case Event.KEY_PRESS: 6871 case Event.KEY_ACTION: 6872 return keyDown(evt, evt.key); 6873 6874 case Event.KEY_RELEASE: 6875 case Event.KEY_ACTION_RELEASE: 6876 return keyUp(evt, evt.key); 6877 6878 case Event.ACTION_EVENT: 6879 return action(evt, evt.arg); 6880 case Event.GOT_FOCUS: 6881 return gotFocus(evt, evt.arg); 6882 case Event.LOST_FOCUS: 6883 return lostFocus(evt, evt.arg); 6884 } 6885 return false; 6886 } 6887 6888 /** 6889 * @param evt the event to handle 6890 * @param x the x coordinate 6891 * @param y the y coordinate 6892 * @return {@code false} 6893 * @deprecated As of JDK version 1.1, 6894 * replaced by processMouseEvent(MouseEvent). 6895 */ 6896 @Deprecated 6897 public boolean mouseDown(Event evt, int x, int y) { 6898 return false; 6899 } 6900 6901 /** 6902 * @param evt the event to handle 6903 * @param x the x coordinate 6904 * @param y the y coordinate 6905 * @return {@code false} 6906 * @deprecated As of JDK version 1.1, 6907 * replaced by processMouseMotionEvent(MouseEvent). 6908 */ 6909 @Deprecated 6910 public boolean mouseDrag(Event evt, int x, int y) { 6911 return false; 6912 } 6913 6914 /** 6915 * @param evt the event to handle 6916 * @param x the x coordinate 6917 * @param y the y coordinate 6918 * @return {@code false} 6919 * @deprecated As of JDK version 1.1, 6920 * replaced by processMouseEvent(MouseEvent). 6921 */ 6922 @Deprecated 6923 public boolean mouseUp(Event evt, int x, int y) { 6924 return false; 6925 } 6926 6927 /** 6928 * @param evt the event to handle 6929 * @param x the x coordinate 6930 * @param y the y coordinate 6931 * @return {@code false} 6932 * @deprecated As of JDK version 1.1, 6933 * replaced by processMouseMotionEvent(MouseEvent). 6934 */ 6935 @Deprecated 6936 public boolean mouseMove(Event evt, int x, int y) { 6937 return false; 6938 } 6939 6940 /** 6941 * @param evt the event to handle 6942 * @param x the x coordinate 6943 * @param y the y coordinate 6944 * @return {@code false} 6945 * @deprecated As of JDK version 1.1, 6946 * replaced by processMouseEvent(MouseEvent). 6947 */ 6948 @Deprecated 6949 public boolean mouseEnter(Event evt, int x, int y) { 6950 return false; 6951 } 6952 6953 /** 6954 * @param evt the event to handle 6955 * @param x the x coordinate 6956 * @param y the y coordinate 6957 * @return {@code false} 6958 * @deprecated As of JDK version 1.1, 6959 * replaced by processMouseEvent(MouseEvent). 6960 */ 6961 @Deprecated 6962 public boolean mouseExit(Event evt, int x, int y) { 6963 return false; 6964 } 6965 6966 /** 6967 * @param evt the event to handle 6968 * @param key the key pressed 6969 * @return {@code false} 6970 * @deprecated As of JDK version 1.1, 6971 * replaced by processKeyEvent(KeyEvent). 6972 */ 6973 @Deprecated 6974 public boolean keyDown(Event evt, int key) { 6975 return false; 6976 } 6977 6978 /** 6979 * @param evt the event to handle 6980 * @param key the key pressed 6981 * @return {@code false} 6982 * @deprecated As of JDK version 1.1, 6983 * replaced by processKeyEvent(KeyEvent). 6984 */ 6985 @Deprecated 6986 public boolean keyUp(Event evt, int key) { 6987 return false; 6988 } 6989 6990 /** 6991 * @param evt the event to handle 6992 * @param what the object acted on 6993 * @return {@code false} 6994 * @deprecated As of JDK version 1.1, 6995 * should register this component as ActionListener on component 6996 * which fires action events. 6997 */ 6998 @Deprecated 6999 public boolean action(Event evt, Object what) { 7000 return false; 7001 } 7002 7003 /** 7004 * Makes this {@code Component} displayable by connecting it to a 7005 * native screen resource. 7006 * This method is called internally by the toolkit and should 7007 * not be called directly by programs. 7008 * <p> 7009 * This method changes layout-related information, and therefore, 7010 * invalidates the component hierarchy. 7011 * 7012 * @see #isDisplayable 7013 * @see #removeNotify 7014 * @see #invalidate 7015 * @since 1.0 7016 */ 7017 public void addNotify() { 7018 synchronized (getTreeLock()) { 7019 ComponentPeer peer = this.peer; 7020 if (peer == null || peer instanceof LightweightPeer){ 7021 if (peer == null) { 7022 // Update both the Component's peer variable and the local 7023 // variable we use for thread safety. 7024 this.peer = peer = getComponentFactory().createComponent(this); 7025 } 7026 7027 // This is a lightweight component which means it won't be 7028 // able to get window-related events by itself. If any 7029 // have been enabled, then the nearest native container must 7030 // be enabled. 7031 if (parent != null) { 7032 long mask = 0; 7033 if ((mouseListener != null) || ((eventMask & AWTEvent.MOUSE_EVENT_MASK) != 0)) { 7034 mask |= AWTEvent.MOUSE_EVENT_MASK; 7035 } 7036 if ((mouseMotionListener != null) || 7037 ((eventMask & AWTEvent.MOUSE_MOTION_EVENT_MASK) != 0)) { 7038 mask |= AWTEvent.MOUSE_MOTION_EVENT_MASK; 7039 } 7040 if ((mouseWheelListener != null ) || 7041 ((eventMask & AWTEvent.MOUSE_WHEEL_EVENT_MASK) != 0)) { 7042 mask |= AWTEvent.MOUSE_WHEEL_EVENT_MASK; 7043 } 7044 if (focusListener != null || (eventMask & AWTEvent.FOCUS_EVENT_MASK) != 0) { 7045 mask |= AWTEvent.FOCUS_EVENT_MASK; 7046 } 7047 if (keyListener != null || (eventMask & AWTEvent.KEY_EVENT_MASK) != 0) { 7048 mask |= AWTEvent.KEY_EVENT_MASK; 7049 } 7050 if (mask != 0) { 7051 parent.proxyEnableEvents(mask); 7052 } 7053 } 7054 } else { 7055 // It's native. If the parent is lightweight it will need some 7056 // help. 7057 Container parent = getContainer(); 7058 if (parent != null && parent.isLightweight()) { 7059 relocateComponent(); 7060 if (!parent.isRecursivelyVisibleUpToHeavyweightContainer()) 7061 { 7062 peer.setVisible(false); 7063 } 7064 } 7065 } 7066 invalidate(); 7067 7068 int npopups = (popups != null? popups.size() : 0); 7069 for (int i = 0 ; i < npopups ; i++) { 7070 PopupMenu popup = popups.elementAt(i); 7071 popup.addNotify(); 7072 } 7073 7074 if (dropTarget != null) dropTarget.addNotify(); 7075 7076 peerFont = getFont(); 7077 7078 if (getContainer() != null && !isAddNotifyComplete) { 7079 getContainer().increaseComponentCount(this); 7080 } 7081 7082 7083 // Update stacking order 7084 updateZOrder(); 7085 7086 if (!isAddNotifyComplete) { 7087 mixOnShowing(); 7088 } 7089 7090 isAddNotifyComplete = true; 7091 7092 if (hierarchyListener != null || 7093 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 7094 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { 7095 HierarchyEvent e = 7096 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, 7097 this, parent, 7098 HierarchyEvent.DISPLAYABILITY_CHANGED | 7099 ((isRecursivelyVisible()) 7100 ? HierarchyEvent.SHOWING_CHANGED 7101 : 0)); 7102 dispatchEvent(e); 7103 } 7104 } 7105 } 7106 7107 /** 7108 * Makes this {@code Component} undisplayable by destroying it native 7109 * screen resource. 7110 * <p> 7111 * This method is called by the toolkit internally and should 7112 * not be called directly by programs. Code overriding 7113 * this method should call {@code super.removeNotify} as 7114 * the first line of the overriding method. 7115 * 7116 * @see #isDisplayable 7117 * @see #addNotify 7118 * @since 1.0 7119 */ 7120 public void removeNotify() { 7121 KeyboardFocusManager.clearMostRecentFocusOwner(this); 7122 if (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7123 getPermanentFocusOwner() == this) 7124 { 7125 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7126 setGlobalPermanentFocusOwner(null); 7127 } 7128 7129 synchronized (getTreeLock()) { 7130 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabledFor(this)) { 7131 transferFocus(true); 7132 } 7133 7134 if (getContainer() != null && isAddNotifyComplete) { 7135 getContainer().decreaseComponentCount(this); 7136 } 7137 7138 int npopups = (popups != null? popups.size() : 0); 7139 for (int i = 0 ; i < npopups ; i++) { 7140 PopupMenu popup = popups.elementAt(i); 7141 popup.removeNotify(); 7142 } 7143 // If there is any input context for this component, notify 7144 // that this component is being removed. (This has to be done 7145 // before hiding peer.) 7146 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { 7147 InputContext inputContext = getInputContext(); 7148 if (inputContext != null) { 7149 inputContext.removeNotify(this); 7150 } 7151 } 7152 7153 ComponentPeer p = peer; 7154 if (p != null) { 7155 boolean isLightweight = isLightweight(); 7156 7157 if (bufferStrategy instanceof FlipBufferStrategy) { 7158 ((FlipBufferStrategy)bufferStrategy).destroyBuffers(); 7159 } 7160 7161 if (dropTarget != null) dropTarget.removeNotify(); 7162 7163 // Hide peer first to stop system events such as cursor moves. 7164 if (visible) { 7165 p.setVisible(false); 7166 } 7167 7168 peer = null; // Stop peer updates. 7169 peerFont = null; 7170 7171 Toolkit.getEventQueue().removeSourceEvents(this, false); 7172 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7173 discardKeyEvents(this); 7174 7175 p.dispose(); 7176 7177 mixOnHiding(isLightweight); 7178 7179 isAddNotifyComplete = false; 7180 // Nullifying compoundShape means that the component has normal shape 7181 // (or has no shape at all). 7182 this.compoundShape = null; 7183 } 7184 7185 if (hierarchyListener != null || 7186 (eventMask & AWTEvent.HIERARCHY_EVENT_MASK) != 0 || 7187 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)) { 7188 HierarchyEvent e = 7189 new HierarchyEvent(this, HierarchyEvent.HIERARCHY_CHANGED, 7190 this, parent, 7191 HierarchyEvent.DISPLAYABILITY_CHANGED | 7192 ((isRecursivelyVisible()) 7193 ? HierarchyEvent.SHOWING_CHANGED 7194 : 0)); 7195 dispatchEvent(e); 7196 } 7197 } 7198 } 7199 7200 /** 7201 * @param evt the event to handle 7202 * @param what the object focused 7203 * @return {@code false} 7204 * @deprecated As of JDK version 1.1, 7205 * replaced by processFocusEvent(FocusEvent). 7206 */ 7207 @Deprecated 7208 public boolean gotFocus(Event evt, Object what) { 7209 return false; 7210 } 7211 7212 /** 7213 * @param evt the event to handle 7214 * @param what the object focused 7215 * @return {@code false} 7216 * @deprecated As of JDK version 1.1, 7217 * replaced by processFocusEvent(FocusEvent). 7218 */ 7219 @Deprecated 7220 public boolean lostFocus(Event evt, Object what) { 7221 return false; 7222 } 7223 7224 /** 7225 * Returns whether this {@code Component} can become the focus 7226 * owner. 7227 * 7228 * @return {@code true} if this {@code Component} is 7229 * focusable; {@code false} otherwise 7230 * @see #setFocusable 7231 * @since 1.1 7232 * @deprecated As of 1.4, replaced by {@code isFocusable()}. 7233 */ 7234 @Deprecated 7235 public boolean isFocusTraversable() { 7236 if (isFocusTraversableOverridden == FOCUS_TRAVERSABLE_UNKNOWN) { 7237 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_DEFAULT; 7238 } 7239 return focusable; 7240 } 7241 7242 /** 7243 * Returns whether this Component can be focused. 7244 * 7245 * @return {@code true} if this Component is focusable; 7246 * {@code false} otherwise. 7247 * @see #setFocusable 7248 * @since 1.4 7249 */ 7250 public boolean isFocusable() { 7251 return isFocusTraversable(); 7252 } 7253 7254 /** 7255 * Sets the focusable state of this Component to the specified value. This 7256 * value overrides the Component's default focusability. 7257 * 7258 * @param focusable indicates whether this Component is focusable 7259 * @see #isFocusable 7260 * @since 1.4 7261 */ 7262 public void setFocusable(boolean focusable) { 7263 boolean oldFocusable; 7264 synchronized (this) { 7265 oldFocusable = this.focusable; 7266 this.focusable = focusable; 7267 } 7268 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_SET; 7269 7270 firePropertyChange("focusable", oldFocusable, focusable); 7271 if (oldFocusable && !focusable) { 7272 if (isFocusOwner() && KeyboardFocusManager.isAutoFocusTransferEnabled()) { 7273 transferFocus(true); 7274 } 7275 KeyboardFocusManager.clearMostRecentFocusOwner(this); 7276 } 7277 } 7278 7279 final boolean isFocusTraversableOverridden() { 7280 return (isFocusTraversableOverridden != FOCUS_TRAVERSABLE_DEFAULT); 7281 } 7282 7283 /** 7284 * Sets the focus traversal keys for a given traversal operation for this 7285 * Component. 7286 * <p> 7287 * The default values for a Component's focus traversal keys are 7288 * implementation-dependent. Sun recommends that all implementations for a 7289 * particular native platform use the same default values. The 7290 * recommendations for Windows and Unix are listed below. These 7291 * recommendations are used in the Sun AWT implementations. 7292 * 7293 * <table class="striped"> 7294 * <caption>Recommended default values for a Component's focus traversal 7295 * keys</caption> 7296 * <thead> 7297 * <tr> 7298 * <th scope="col">Identifier 7299 * <th scope="col">Meaning 7300 * <th scope="col">Default 7301 * </thead> 7302 * <tbody> 7303 * <tr> 7304 * <th scope="row">KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS 7305 * <td>Normal forward keyboard traversal 7306 * <td>TAB on KEY_PRESSED, CTRL-TAB on KEY_PRESSED 7307 * <tr> 7308 * <th scope="row">KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS 7309 * <td>Normal reverse keyboard traversal 7310 * <td>SHIFT-TAB on KEY_PRESSED, CTRL-SHIFT-TAB on KEY_PRESSED 7311 * <tr> 7312 * <th scope="row">KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7313 * <td>Go up one focus traversal cycle 7314 * <td>none 7315 * </tbody> 7316 * </table> 7317 * 7318 * To disable a traversal key, use an empty Set; Collections.EMPTY_SET is 7319 * recommended. 7320 * <p> 7321 * Using the AWTKeyStroke API, client code can specify on which of two 7322 * specific KeyEvents, KEY_PRESSED or KEY_RELEASED, the focus traversal 7323 * operation will occur. Regardless of which KeyEvent is specified, 7324 * however, all KeyEvents related to the focus traversal key, including the 7325 * associated KEY_TYPED event, will be consumed, and will not be dispatched 7326 * to any Component. It is a runtime error to specify a KEY_TYPED event as 7327 * mapping to a focus traversal operation, or to map the same event to 7328 * multiple default focus traversal operations. 7329 * <p> 7330 * If a value of null is specified for the Set, this Component inherits the 7331 * Set from its parent. If all ancestors of this Component have null 7332 * specified for the Set, then the current KeyboardFocusManager's default 7333 * Set is used. 7334 * <p> 7335 * This method may throw a {@code ClassCastException} if any {@code Object} 7336 * in {@code keystrokes} is not an {@code AWTKeyStroke}. 7337 * 7338 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7339 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7340 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7341 * @param keystrokes the Set of AWTKeyStroke for the specified operation 7342 * @see #getFocusTraversalKeys 7343 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 7344 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 7345 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 7346 * @throws IllegalArgumentException if id is not one of 7347 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7348 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7349 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes 7350 * contains null, or if any keystroke represents a KEY_TYPED event, 7351 * or if any keystroke already maps to another focus traversal 7352 * operation for this Component 7353 * @since 1.4 7354 */ 7355 public void setFocusTraversalKeys(int id, 7356 Set<? extends AWTKeyStroke> keystrokes) 7357 { 7358 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7359 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7360 } 7361 7362 setFocusTraversalKeys_NoIDCheck(id, keystrokes); 7363 } 7364 7365 /** 7366 * Returns the Set of focus traversal keys for a given traversal operation 7367 * for this Component. (See 7368 * {@code setFocusTraversalKeys} for a full description of each key.) 7369 * <p> 7370 * If a Set of traversal keys has not been explicitly defined for this 7371 * Component, then this Component's parent's Set is returned. If no Set 7372 * has been explicitly defined for any of this Component's ancestors, then 7373 * the current KeyboardFocusManager's default Set is returned. 7374 * 7375 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7376 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7377 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7378 * @return the Set of AWTKeyStrokes for the specified operation. The Set 7379 * will be unmodifiable, and may be empty. null will never be 7380 * returned. 7381 * @see #setFocusTraversalKeys 7382 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 7383 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 7384 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 7385 * @throws IllegalArgumentException if id is not one of 7386 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7387 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7388 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7389 * @since 1.4 7390 */ 7391 public Set<AWTKeyStroke> getFocusTraversalKeys(int id) { 7392 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7393 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7394 } 7395 7396 return getFocusTraversalKeys_NoIDCheck(id); 7397 } 7398 7399 // We define these methods so that Container does not need to repeat this 7400 // code. Container cannot call super.<method> because Container allows 7401 // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method 7402 // would erroneously generate an IllegalArgumentException for 7403 // DOWN_CYCLE_TRAVERSAL_KEY. 7404 final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) { 7405 Set<AWTKeyStroke> oldKeys; 7406 7407 synchronized (this) { 7408 if (focusTraversalKeys == null) { 7409 initializeFocusTraversalKeys(); 7410 } 7411 7412 if (keystrokes != null) { 7413 for (AWTKeyStroke keystroke : keystrokes ) { 7414 7415 if (keystroke == null) { 7416 throw new IllegalArgumentException("cannot set null focus traversal key"); 7417 } 7418 7419 if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { 7420 throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events"); 7421 } 7422 7423 for (int i = 0; i < focusTraversalKeys.length; i++) { 7424 if (i == id) { 7425 continue; 7426 } 7427 7428 if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke)) 7429 { 7430 throw new IllegalArgumentException("focus traversal keys must be unique for a Component"); 7431 } 7432 } 7433 } 7434 } 7435 7436 oldKeys = focusTraversalKeys[id]; 7437 focusTraversalKeys[id] = (keystrokes != null) 7438 ? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes)) 7439 : null; 7440 } 7441 7442 firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys, 7443 keystrokes); 7444 } 7445 final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) { 7446 // Okay to return Set directly because it is an unmodifiable view 7447 @SuppressWarnings("unchecked") 7448 Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null) 7449 ? focusTraversalKeys[id] 7450 : null; 7451 7452 if (keystrokes != null) { 7453 return keystrokes; 7454 } else { 7455 Container parent = this.parent; 7456 if (parent != null) { 7457 return parent.getFocusTraversalKeys(id); 7458 } else { 7459 return KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7460 getDefaultFocusTraversalKeys(id); 7461 } 7462 } 7463 } 7464 7465 /** 7466 * Returns whether the Set of focus traversal keys for the given focus 7467 * traversal operation has been explicitly defined for this Component. If 7468 * this method returns {@code false}, this Component is inheriting the 7469 * Set from an ancestor, or from the current KeyboardFocusManager. 7470 * 7471 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7472 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7473 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7474 * @return {@code true} if the Set of focus traversal keys for the 7475 * given focus traversal operation has been explicitly defined for 7476 * this Component; {@code false} otherwise. 7477 * @throws IllegalArgumentException if id is not one of 7478 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7479 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7480 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7481 * @since 1.4 7482 */ 7483 public boolean areFocusTraversalKeysSet(int id) { 7484 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7485 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7486 } 7487 7488 return (focusTraversalKeys != null && focusTraversalKeys[id] != null); 7489 } 7490 7491 /** 7492 * Sets whether focus traversal keys are enabled for this Component. 7493 * Components for which focus traversal keys are disabled receive key 7494 * events for focus traversal keys. Components for which focus traversal 7495 * keys are enabled do not see these events; instead, the events are 7496 * automatically converted to traversal operations. 7497 * 7498 * @param focusTraversalKeysEnabled whether focus traversal keys are 7499 * enabled for this Component 7500 * @see #getFocusTraversalKeysEnabled 7501 * @see #setFocusTraversalKeys 7502 * @see #getFocusTraversalKeys 7503 * @since 1.4 7504 */ 7505 public void setFocusTraversalKeysEnabled(boolean 7506 focusTraversalKeysEnabled) { 7507 boolean oldFocusTraversalKeysEnabled; 7508 synchronized (this) { 7509 oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled; 7510 this.focusTraversalKeysEnabled = focusTraversalKeysEnabled; 7511 } 7512 firePropertyChange("focusTraversalKeysEnabled", 7513 oldFocusTraversalKeysEnabled, 7514 focusTraversalKeysEnabled); 7515 } 7516 7517 /** 7518 * Returns whether focus traversal keys are enabled for this Component. 7519 * Components for which focus traversal keys are disabled receive key 7520 * events for focus traversal keys. Components for which focus traversal 7521 * keys are enabled do not see these events; instead, the events are 7522 * automatically converted to traversal operations. 7523 * 7524 * @return whether focus traversal keys are enabled for this Component 7525 * @see #setFocusTraversalKeysEnabled 7526 * @see #setFocusTraversalKeys 7527 * @see #getFocusTraversalKeys 7528 * @since 1.4 7529 */ 7530 public boolean getFocusTraversalKeysEnabled() { 7531 return focusTraversalKeysEnabled; 7532 } 7533 7534 /** 7535 * Requests that this Component get the input focus, and that this 7536 * Component's top-level ancestor become the focused Window. This 7537 * component must be displayable, focusable, visible and all of 7538 * its ancestors (with the exception of the top-level Window) must 7539 * be visible for the request to be granted. Every effort will be 7540 * made to honor the request; however, in some cases it may be 7541 * impossible to do so. Developers must never assume that this 7542 * Component is the focus owner until this Component receives a 7543 * FOCUS_GAINED event. If this request is denied because this 7544 * Component's top-level Window cannot become the focused Window, 7545 * the request will be remembered and will be granted when the 7546 * Window is later focused by the user. 7547 * <p> 7548 * This method cannot be used to set the focus owner to no Component at 7549 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()} 7550 * instead. 7551 * <p> 7552 * Because the focus behavior of this method is platform-dependent, 7553 * developers are strongly encouraged to use 7554 * {@code requestFocusInWindow} when possible. 7555 * 7556 * <p>Note: Not all focus transfers result from invoking this method. As 7557 * such, a component may receive focus without this or any of the other 7558 * {@code requestFocus} methods of {@code Component} being invoked. 7559 * 7560 * @see #requestFocusInWindow 7561 * @see java.awt.event.FocusEvent 7562 * @see #addFocusListener 7563 * @see #isFocusable 7564 * @see #isDisplayable 7565 * @see KeyboardFocusManager#clearGlobalFocusOwner 7566 * @since 1.0 7567 */ 7568 public void requestFocus() { 7569 requestFocusHelper(false, true); 7570 } 7571 7572 7573 /** 7574 * Requests by the reason of {@code cause} that this Component get the input 7575 * focus, and that this Component's top-level ancestor become the 7576 * focused Window. This component must be displayable, focusable, visible 7577 * and all of its ancestors (with the exception of the top-level Window) 7578 * must be visible for the request to be granted. Every effort will be 7579 * made to honor the request; however, in some cases it may be 7580 * impossible to do so. Developers must never assume that this 7581 * Component is the focus owner until this Component receives a 7582 * FOCUS_GAINED event. 7583 * <p> 7584 * The focus request effect may also depend on the provided 7585 * cause value. If this request is succeed the {@code FocusEvent} 7586 * generated in the result will receive the cause value specified as the 7587 * argument of method. If this request is denied because this Component's 7588 * top-level Window cannot become the focused Window, the request will be 7589 * remembered and will be granted when the Window is later focused by the 7590 * user. 7591 * <p> 7592 * This method cannot be used to set the focus owner to no Component at 7593 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()} 7594 * instead. 7595 * <p> 7596 * Because the focus behavior of this method is platform-dependent, 7597 * developers are strongly encouraged to use 7598 * {@code requestFocusInWindow(FocusEvent.Cause)} when possible. 7599 * 7600 * <p>Note: Not all focus transfers result from invoking this method. As 7601 * such, a component may receive focus without this or any of the other 7602 * {@code requestFocus} methods of {@code Component} being invoked. 7603 * 7604 * @param cause the cause why the focus is requested 7605 * @see FocusEvent 7606 * @see FocusEvent.Cause 7607 * @see #requestFocusInWindow(FocusEvent.Cause) 7608 * @see java.awt.event.FocusEvent 7609 * @see #addFocusListener 7610 * @see #isFocusable 7611 * @see #isDisplayable 7612 * @see KeyboardFocusManager#clearGlobalFocusOwner 7613 * @since 9 7614 */ 7615 public void requestFocus(FocusEvent.Cause cause) { 7616 requestFocusHelper(false, true, cause); 7617 } 7618 7619 /** 7620 * Requests that this {@code Component} get the input focus, 7621 * and that this {@code Component}'s top-level ancestor 7622 * become the focused {@code Window}. This component must be 7623 * displayable, focusable, visible and all of its ancestors (with 7624 * the exception of the top-level Window) must be visible for the 7625 * request to be granted. Every effort will be made to honor the 7626 * request; however, in some cases it may be impossible to do 7627 * so. Developers must never assume that this component is the 7628 * focus owner until this component receives a FOCUS_GAINED 7629 * event. If this request is denied because this component's 7630 * top-level window cannot become the focused window, the request 7631 * will be remembered and will be granted when the window is later 7632 * focused by the user. 7633 * <p> 7634 * This method returns a boolean value. If {@code false} is returned, 7635 * the request is <b>guaranteed to fail</b>. If {@code true} is 7636 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7637 * extraordinary event, such as disposal of the component's peer, occurs 7638 * before the request can be granted by the native windowing system. Again, 7639 * while a return value of {@code true} indicates that the request is 7640 * likely to succeed, developers must never assume that this component is 7641 * the focus owner until this component receives a FOCUS_GAINED event. 7642 * <p> 7643 * This method cannot be used to set the focus owner to no component at 7644 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner} 7645 * instead. 7646 * <p> 7647 * Because the focus behavior of this method is platform-dependent, 7648 * developers are strongly encouraged to use 7649 * {@code requestFocusInWindow} when possible. 7650 * <p> 7651 * Every effort will be made to ensure that {@code FocusEvent}s 7652 * generated as a 7653 * result of this request will have the specified temporary value. However, 7654 * because specifying an arbitrary temporary state may not be implementable 7655 * on all native windowing systems, correct behavior for this method can be 7656 * guaranteed only for lightweight {@code Component}s. 7657 * This method is not intended 7658 * for general use, but exists instead as a hook for lightweight component 7659 * libraries, such as Swing. 7660 * 7661 * <p>Note: Not all focus transfers result from invoking this method. As 7662 * such, a component may receive focus without this or any of the other 7663 * {@code requestFocus} methods of {@code Component} being invoked. 7664 * 7665 * @param temporary true if the focus change is temporary, 7666 * such as when the window loses the focus; for 7667 * more information on temporary focus changes see the 7668 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7669 * @return {@code false} if the focus change request is guaranteed to 7670 * fail; {@code true} if it is likely to succeed 7671 * @see java.awt.event.FocusEvent 7672 * @see #addFocusListener 7673 * @see #isFocusable 7674 * @see #isDisplayable 7675 * @see KeyboardFocusManager#clearGlobalFocusOwner 7676 * @since 1.4 7677 */ 7678 protected boolean requestFocus(boolean temporary) { 7679 return requestFocusHelper(temporary, true); 7680 } 7681 7682 /** 7683 * Requests by the reason of {@code cause} that this {@code Component} get 7684 * the input focus, and that this {@code Component}'s top-level ancestor 7685 * become the focused {@code Window}. This component must be 7686 * displayable, focusable, visible and all of its ancestors (with 7687 * the exception of the top-level Window) must be visible for the 7688 * request to be granted. Every effort will be made to honor the 7689 * request; however, in some cases it may be impossible to do 7690 * so. Developers must never assume that this component is the 7691 * focus owner until this component receives a FOCUS_GAINED 7692 * event. If this request is denied because this component's 7693 * top-level window cannot become the focused window, the request 7694 * will be remembered and will be granted when the window is later 7695 * focused by the user. 7696 * <p> 7697 * This method returns a boolean value. If {@code false} is returned, 7698 * the request is <b>guaranteed to fail</b>. If {@code true} is 7699 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7700 * extraordinary event, such as disposal of the component's peer, occurs 7701 * before the request can be granted by the native windowing system. Again, 7702 * while a return value of {@code true} indicates that the request is 7703 * likely to succeed, developers must never assume that this component is 7704 * the focus owner until this component receives a FOCUS_GAINED event. 7705 * <p> 7706 * The focus request effect may also depend on the provided 7707 * cause value. If this request is succeed the {FocusEvent} 7708 * generated in the result will receive the cause value specified as the 7709 * argument of the method. 7710 * <p> 7711 * This method cannot be used to set the focus owner to no component at 7712 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner} 7713 * instead. 7714 * <p> 7715 * Because the focus behavior of this method is platform-dependent, 7716 * developers are strongly encouraged to use 7717 * {@code requestFocusInWindow} when possible. 7718 * <p> 7719 * Every effort will be made to ensure that {@code FocusEvent}s 7720 * generated as a 7721 * result of this request will have the specified temporary value. However, 7722 * because specifying an arbitrary temporary state may not be implementable 7723 * on all native windowing systems, correct behavior for this method can be 7724 * guaranteed only for lightweight {@code Component}s. 7725 * This method is not intended 7726 * for general use, but exists instead as a hook for lightweight component 7727 * libraries, such as Swing. 7728 * <p> 7729 * Note: Not all focus transfers result from invoking this method. As 7730 * such, a component may receive focus without this or any of the other 7731 * {@code requestFocus} methods of {@code Component} being invoked. 7732 * 7733 * @param temporary true if the focus change is temporary, 7734 * such as when the window loses the focus; for 7735 * more information on temporary focus changes see the 7736 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7737 * 7738 * @param cause the cause why the focus is requested 7739 * @return {@code false} if the focus change request is guaranteed to 7740 * fail; {@code true} if it is likely to succeed 7741 * @see FocusEvent 7742 * @see FocusEvent.Cause 7743 * @see #addFocusListener 7744 * @see #isFocusable 7745 * @see #isDisplayable 7746 * @see KeyboardFocusManager#clearGlobalFocusOwner 7747 * @since 9 7748 */ 7749 protected boolean requestFocus(boolean temporary, FocusEvent.Cause cause) { 7750 return requestFocusHelper(temporary, true, cause); 7751 } 7752 7753 /** 7754 * Requests that this Component get the input focus, if this 7755 * Component's top-level ancestor is already the focused 7756 * Window. This component must be displayable, focusable, visible 7757 * and all of its ancestors (with the exception of the top-level 7758 * Window) must be visible for the request to be granted. Every 7759 * effort will be made to honor the request; however, in some 7760 * cases it may be impossible to do so. Developers must never 7761 * assume that this Component is the focus owner until this 7762 * Component receives a FOCUS_GAINED event. 7763 * <p> 7764 * This method returns a boolean value. If {@code false} is returned, 7765 * the request is <b>guaranteed to fail</b>. If {@code true} is 7766 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7767 * extraordinary event, such as disposal of the Component's peer, occurs 7768 * before the request can be granted by the native windowing system. Again, 7769 * while a return value of {@code true} indicates that the request is 7770 * likely to succeed, developers must never assume that this Component is 7771 * the focus owner until this Component receives a FOCUS_GAINED event. 7772 * <p> 7773 * This method cannot be used to set the focus owner to no Component at 7774 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()} 7775 * instead. 7776 * <p> 7777 * The focus behavior of this method can be implemented uniformly across 7778 * platforms, and thus developers are strongly encouraged to use this 7779 * method over {@code requestFocus} when possible. Code which relies 7780 * on {@code requestFocus} may exhibit different focus behavior on 7781 * different platforms. 7782 * 7783 * <p>Note: Not all focus transfers result from invoking this method. As 7784 * such, a component may receive focus without this or any of the other 7785 * {@code requestFocus} methods of {@code Component} being invoked. 7786 * 7787 * @return {@code false} if the focus change request is guaranteed to 7788 * fail; {@code true} if it is likely to succeed 7789 * @see #requestFocus 7790 * @see java.awt.event.FocusEvent 7791 * @see #addFocusListener 7792 * @see #isFocusable 7793 * @see #isDisplayable 7794 * @see KeyboardFocusManager#clearGlobalFocusOwner 7795 * @since 1.4 7796 */ 7797 public boolean requestFocusInWindow() { 7798 return requestFocusHelper(false, false); 7799 } 7800 7801 /** 7802 * Requests by the reason of {@code cause} that this Component get the input 7803 * focus, if this Component's top-level ancestor is already the focused 7804 * Window. This component must be displayable, focusable, visible 7805 * and all of its ancestors (with the exception of the top-level 7806 * Window) must be visible for the request to be granted. Every 7807 * effort will be made to honor the request; however, in some 7808 * cases it may be impossible to do so. Developers must never 7809 * assume that this Component is the focus owner until this 7810 * Component receives a FOCUS_GAINED event. 7811 * <p> 7812 * This method returns a boolean value. If {@code false} is returned, 7813 * the request is <b>guaranteed to fail</b>. If {@code true} is 7814 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7815 * extraordinary event, such as disposal of the Component's peer, occurs 7816 * before the request can be granted by the native windowing system. Again, 7817 * while a return value of {@code true} indicates that the request is 7818 * likely to succeed, developers must never assume that this Component is 7819 * the focus owner until this Component receives a FOCUS_GAINED event. 7820 * <p> 7821 * The focus request effect may also depend on the provided 7822 * cause value. If this request is succeed the {@code FocusEvent} 7823 * generated in the result will receive the cause value specified as the 7824 * argument of the method. 7825 * <p> 7826 * This method cannot be used to set the focus owner to no Component at 7827 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner()} 7828 * instead. 7829 * <p> 7830 * The focus behavior of this method can be implemented uniformly across 7831 * platforms, and thus developers are strongly encouraged to use this 7832 * method over {@code requestFocus(FocusEvent.Cause)} when possible. 7833 * Code which relies on {@code requestFocus(FocusEvent.Cause)} may exhibit 7834 * different focus behavior on different platforms. 7835 * 7836 * <p>Note: Not all focus transfers result from invoking this method. As 7837 * such, a component may receive focus without this or any of the other 7838 * {@code requestFocus} methods of {@code Component} being invoked. 7839 * 7840 * @param cause the cause why the focus is requested 7841 * @return {@code false} if the focus change request is guaranteed to 7842 * fail; {@code true} if it is likely to succeed 7843 * @see #requestFocus(FocusEvent.Cause) 7844 * @see FocusEvent 7845 * @see FocusEvent.Cause 7846 * @see java.awt.event.FocusEvent 7847 * @see #addFocusListener 7848 * @see #isFocusable 7849 * @see #isDisplayable 7850 * @see KeyboardFocusManager#clearGlobalFocusOwner 7851 * @since 9 7852 */ 7853 public boolean requestFocusInWindow(FocusEvent.Cause cause) { 7854 return requestFocusHelper(false, false, cause); 7855 } 7856 7857 /** 7858 * Requests that this {@code Component} get the input focus, 7859 * if this {@code Component}'s top-level ancestor is already 7860 * the focused {@code Window}. This component must be 7861 * displayable, focusable, visible and all of its ancestors (with 7862 * the exception of the top-level Window) must be visible for the 7863 * request to be granted. Every effort will be made to honor the 7864 * request; however, in some cases it may be impossible to do 7865 * so. Developers must never assume that this component is the 7866 * focus owner until this component receives a FOCUS_GAINED event. 7867 * <p> 7868 * This method returns a boolean value. If {@code false} is returned, 7869 * the request is <b>guaranteed to fail</b>. If {@code true} is 7870 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7871 * extraordinary event, such as disposal of the component's peer, occurs 7872 * before the request can be granted by the native windowing system. Again, 7873 * while a return value of {@code true} indicates that the request is 7874 * likely to succeed, developers must never assume that this component is 7875 * the focus owner until this component receives a FOCUS_GAINED event. 7876 * <p> 7877 * This method cannot be used to set the focus owner to no component at 7878 * all. Use {@code KeyboardFocusManager.clearGlobalFocusOwner} 7879 * instead. 7880 * <p> 7881 * The focus behavior of this method can be implemented uniformly across 7882 * platforms, and thus developers are strongly encouraged to use this 7883 * method over {@code requestFocus} when possible. Code which relies 7884 * on {@code requestFocus} may exhibit different focus behavior on 7885 * different platforms. 7886 * <p> 7887 * Every effort will be made to ensure that {@code FocusEvent}s 7888 * generated as a 7889 * result of this request will have the specified temporary value. However, 7890 * because specifying an arbitrary temporary state may not be implementable 7891 * on all native windowing systems, correct behavior for this method can be 7892 * guaranteed only for lightweight components. This method is not intended 7893 * for general use, but exists instead as a hook for lightweight component 7894 * libraries, such as Swing. 7895 * 7896 * <p>Note: Not all focus transfers result from invoking this method. As 7897 * such, a component may receive focus without this or any of the other 7898 * {@code requestFocus} methods of {@code Component} being invoked. 7899 * 7900 * @param temporary true if the focus change is temporary, 7901 * such as when the window loses the focus; for 7902 * more information on temporary focus changes see the 7903 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7904 * @return {@code false} if the focus change request is guaranteed to 7905 * fail; {@code true} if it is likely to succeed 7906 * @see #requestFocus 7907 * @see java.awt.event.FocusEvent 7908 * @see #addFocusListener 7909 * @see #isFocusable 7910 * @see #isDisplayable 7911 * @see KeyboardFocusManager#clearGlobalFocusOwner 7912 * @since 1.4 7913 */ 7914 protected boolean requestFocusInWindow(boolean temporary) { 7915 return requestFocusHelper(temporary, false); 7916 } 7917 7918 boolean requestFocusInWindow(boolean temporary, FocusEvent.Cause cause) { 7919 return requestFocusHelper(temporary, false, cause); 7920 } 7921 7922 final boolean requestFocusHelper(boolean temporary, 7923 boolean focusedWindowChangeAllowed) { 7924 return requestFocusHelper(temporary, focusedWindowChangeAllowed, FocusEvent.Cause.UNKNOWN); 7925 } 7926 7927 final boolean requestFocusHelper(boolean temporary, 7928 boolean focusedWindowChangeAllowed, 7929 FocusEvent.Cause cause) 7930 { 7931 // 1) Check if the event being dispatched is a system-generated mouse event. 7932 AWTEvent currentEvent = EventQueue.getCurrentEvent(); 7933 if (currentEvent instanceof MouseEvent && 7934 SunToolkit.isSystemGenerated(currentEvent)) 7935 { 7936 // 2) Sanity check: if the mouse event component source belongs to the same containing window. 7937 Component source = ((MouseEvent)currentEvent).getComponent(); 7938 if (source == null || source.getContainingWindow() == getContainingWindow()) { 7939 focusLog.finest("requesting focus by mouse event \"in window\""); 7940 7941 // If both the conditions are fulfilled the focus request should be strictly 7942 // bounded by the toplevel window. It's assumed that the mouse event activates 7943 // the window (if it wasn't active) and this makes it possible for a focus 7944 // request with a strong in-window requirement to change focus in the bounds 7945 // of the toplevel. If, by any means, due to asynchronous nature of the event 7946 // dispatching mechanism, the window happens to be natively inactive by the time 7947 // this focus request is eventually handled, it should not re-activate the 7948 // toplevel. Otherwise the result may not meet user expectations. See 6981400. 7949 focusedWindowChangeAllowed = false; 7950 } 7951 } 7952 if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) { 7953 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 7954 focusLog.finest("requestFocus is not accepted"); 7955 } 7956 return false; 7957 } 7958 // Update most-recent map 7959 KeyboardFocusManager.setMostRecentFocusOwner(this); 7960 7961 Component window = this; 7962 while ( (window != null) && !(window instanceof Window)) { 7963 if (!window.isVisible()) { 7964 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 7965 focusLog.finest("component is recursively invisible"); 7966 } 7967 return false; 7968 } 7969 window = window.parent; 7970 } 7971 7972 ComponentPeer peer = this.peer; 7973 Component heavyweight = (peer instanceof LightweightPeer) 7974 ? getNativeContainer() : this; 7975 if (heavyweight == null || !heavyweight.isVisible()) { 7976 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 7977 focusLog.finest("Component is not a part of visible hierarchy"); 7978 } 7979 return false; 7980 } 7981 peer = heavyweight.peer; 7982 if (peer == null) { 7983 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 7984 focusLog.finest("Peer is null"); 7985 } 7986 return false; 7987 } 7988 7989 // Focus this Component 7990 long time = 0; 7991 if (EventQueue.isDispatchThread()) { 7992 time = Toolkit.getEventQueue().getMostRecentKeyEventTime(); 7993 } else { 7994 // A focus request made from outside EDT should not be associated with any event 7995 // and so its time stamp is simply set to the current time. 7996 time = System.currentTimeMillis(); 7997 } 7998 7999 boolean success = peer.requestFocus 8000 (this, temporary, focusedWindowChangeAllowed, time, cause); 8001 if (!success) { 8002 KeyboardFocusManager.getCurrentKeyboardFocusManager 8003 (appContext).dequeueKeyEvents(time, this); 8004 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8005 focusLog.finest("Peer request failed"); 8006 } 8007 } else { 8008 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8009 focusLog.finest("Pass for " + this); 8010 } 8011 } 8012 return success; 8013 } 8014 8015 private boolean isRequestFocusAccepted(boolean temporary, 8016 boolean focusedWindowChangeAllowed, 8017 FocusEvent.Cause cause) 8018 { 8019 if (!isFocusable() || !isVisible()) { 8020 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8021 focusLog.finest("Not focusable or not visible"); 8022 } 8023 return false; 8024 } 8025 8026 ComponentPeer peer = this.peer; 8027 if (peer == null) { 8028 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8029 focusLog.finest("peer is null"); 8030 } 8031 return false; 8032 } 8033 8034 Window window = getContainingWindow(); 8035 if (window == null || !window.isFocusableWindow()) { 8036 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8037 focusLog.finest("Component doesn't have toplevel"); 8038 } 8039 return false; 8040 } 8041 8042 // We have passed all regular checks for focus request, 8043 // now let's call RequestFocusController and see what it says. 8044 Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window); 8045 if (focusOwner == null) { 8046 // sometimes most recent focus owner may be null, but focus owner is not 8047 // e.g. we reset most recent focus owner if user removes focus owner 8048 focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); 8049 if (focusOwner != null && focusOwner.getContainingWindow() != window) { 8050 focusOwner = null; 8051 } 8052 } 8053 8054 if (focusOwner == this || focusOwner == null) { 8055 // Controller is supposed to verify focus transfers and for this it 8056 // should know both from and to components. And it shouldn't verify 8057 // transfers from when these components are equal. 8058 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8059 focusLog.finest("focus owner is null or this"); 8060 } 8061 return true; 8062 } 8063 8064 if (FocusEvent.Cause.ACTIVATION == cause) { 8065 // we shouldn't call RequestFocusController in case we are 8066 // in activation. We do request focus on component which 8067 // has got temporary focus lost and then on component which is 8068 // most recent focus owner. But most recent focus owner can be 8069 // changed by requestFocusXXX() call only, so this transfer has 8070 // been already approved. 8071 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8072 focusLog.finest("cause is activation"); 8073 } 8074 return true; 8075 } 8076 8077 boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner, 8078 this, 8079 temporary, 8080 focusedWindowChangeAllowed, 8081 cause); 8082 if (focusLog.isLoggable(PlatformLogger.Level.FINEST)) { 8083 focusLog.finest("RequestFocusController returns {0}", ret); 8084 } 8085 8086 return ret; 8087 } 8088 8089 private static RequestFocusController requestFocusController = new DummyRequestFocusController(); 8090 8091 // Swing access this method through reflection to implement InputVerifier's functionality. 8092 // Perhaps, we should make this method public (later ;) 8093 private static class DummyRequestFocusController implements RequestFocusController { 8094 public boolean acceptRequestFocus(Component from, Component to, 8095 boolean temporary, boolean focusedWindowChangeAllowed, 8096 FocusEvent.Cause cause) 8097 { 8098 return true; 8099 } 8100 }; 8101 8102 static synchronized void setRequestFocusController(RequestFocusController requestController) 8103 { 8104 if (requestController == null) { 8105 requestFocusController = new DummyRequestFocusController(); 8106 } else { 8107 requestFocusController = requestController; 8108 } 8109 } 8110 8111 /** 8112 * Returns the Container which is the focus cycle root of this Component's 8113 * focus traversal cycle. Each focus traversal cycle has only a single 8114 * focus cycle root and each Component which is not a Container belongs to 8115 * only a single focus traversal cycle. Containers which are focus cycle 8116 * roots belong to two cycles: one rooted at the Container itself, and one 8117 * rooted at the Container's nearest focus-cycle-root ancestor. For such 8118 * Containers, this method will return the Container's nearest focus-cycle- 8119 * root ancestor. 8120 * 8121 * @return this Component's nearest focus-cycle-root ancestor 8122 * @see Container#isFocusCycleRoot() 8123 * @since 1.4 8124 */ 8125 public Container getFocusCycleRootAncestor() { 8126 Container rootAncestor = this.parent; 8127 while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) { 8128 rootAncestor = rootAncestor.parent; 8129 } 8130 return rootAncestor; 8131 } 8132 8133 /** 8134 * Returns whether the specified Container is the focus cycle root of this 8135 * Component's focus traversal cycle. Each focus traversal cycle has only 8136 * a single focus cycle root and each Component which is not a Container 8137 * belongs to only a single focus traversal cycle. 8138 * 8139 * @param container the Container to be tested 8140 * @return {@code true} if the specified Container is a focus-cycle- 8141 * root of this Component; {@code false} otherwise 8142 * @see Container#isFocusCycleRoot() 8143 * @since 1.4 8144 */ 8145 public boolean isFocusCycleRoot(Container container) { 8146 Container rootAncestor = getFocusCycleRootAncestor(); 8147 return (rootAncestor == container); 8148 } 8149 8150 Container getTraversalRoot() { 8151 return getFocusCycleRootAncestor(); 8152 } 8153 8154 /** 8155 * Transfers the focus to the next component, as though this Component were 8156 * the focus owner. 8157 * @see #requestFocus() 8158 * @since 1.1 8159 */ 8160 public void transferFocus() { 8161 nextFocus(); 8162 } 8163 8164 /** 8165 * @deprecated As of JDK version 1.1, 8166 * replaced by transferFocus(). 8167 */ 8168 @Deprecated 8169 public void nextFocus() { 8170 transferFocus(false); 8171 } 8172 8173 boolean transferFocus(boolean clearOnFailure) { 8174 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8175 focusLog.finer("clearOnFailure = " + clearOnFailure); 8176 } 8177 Component toFocus = getNextFocusCandidate(); 8178 boolean res = false; 8179 if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) { 8180 res = toFocus.requestFocusInWindow(FocusEvent.Cause.TRAVERSAL_FORWARD); 8181 } 8182 if (clearOnFailure && !res) { 8183 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8184 focusLog.finer("clear global focus owner"); 8185 } 8186 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv(); 8187 } 8188 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8189 focusLog.finer("returning result: " + res); 8190 } 8191 return res; 8192 } 8193 8194 @SuppressWarnings("deprecation") 8195 final Component getNextFocusCandidate() { 8196 Container rootAncestor = getTraversalRoot(); 8197 Component comp = this; 8198 while (rootAncestor != null && 8199 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 8200 { 8201 comp = rootAncestor; 8202 rootAncestor = comp.getFocusCycleRootAncestor(); 8203 } 8204 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8205 focusLog.finer("comp = " + comp + ", root = " + rootAncestor); 8206 } 8207 Component candidate = null; 8208 if (rootAncestor != null) { 8209 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 8210 Component toFocus = policy.getComponentAfter(rootAncestor, comp); 8211 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8212 focusLog.finer("component after is " + toFocus); 8213 } 8214 if (toFocus == null) { 8215 toFocus = policy.getDefaultComponent(rootAncestor); 8216 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8217 focusLog.finer("default component is " + toFocus); 8218 } 8219 } 8220 if (toFocus == null) { 8221 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this); 8222 if (applet != null) { 8223 toFocus = applet; 8224 } 8225 } 8226 candidate = toFocus; 8227 } 8228 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8229 focusLog.finer("Focus transfer candidate: " + candidate); 8230 } 8231 return candidate; 8232 } 8233 8234 /** 8235 * Transfers the focus to the previous component, as though this Component 8236 * were the focus owner. 8237 * @see #requestFocus() 8238 * @since 1.4 8239 */ 8240 public void transferFocusBackward() { 8241 transferFocusBackward(false); 8242 } 8243 8244 boolean transferFocusBackward(boolean clearOnFailure) { 8245 Container rootAncestor = getTraversalRoot(); 8246 Component comp = this; 8247 while (rootAncestor != null && 8248 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 8249 { 8250 comp = rootAncestor; 8251 rootAncestor = comp.getFocusCycleRootAncestor(); 8252 } 8253 boolean res = false; 8254 if (rootAncestor != null) { 8255 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 8256 Component toFocus = policy.getComponentBefore(rootAncestor, comp); 8257 if (toFocus == null) { 8258 toFocus = policy.getDefaultComponent(rootAncestor); 8259 } 8260 if (toFocus != null) { 8261 res = toFocus.requestFocusInWindow(FocusEvent.Cause.TRAVERSAL_BACKWARD); 8262 } 8263 } 8264 if (clearOnFailure && !res) { 8265 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8266 focusLog.finer("clear global focus owner"); 8267 } 8268 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv(); 8269 } 8270 if (focusLog.isLoggable(PlatformLogger.Level.FINER)) { 8271 focusLog.finer("returning result: " + res); 8272 } 8273 return res; 8274 } 8275 8276 /** 8277 * Transfers the focus up one focus traversal cycle. Typically, the focus 8278 * owner is set to this Component's focus cycle root, and the current focus 8279 * cycle root is set to the new focus owner's focus cycle root. If, 8280 * however, this Component's focus cycle root is a Window, then the focus 8281 * owner is set to the focus cycle root's default Component to focus, and 8282 * the current focus cycle root is unchanged. 8283 * 8284 * @see #requestFocus() 8285 * @see Container#isFocusCycleRoot() 8286 * @see Container#setFocusCycleRoot(boolean) 8287 * @since 1.4 8288 */ 8289 public void transferFocusUpCycle() { 8290 Container rootAncestor; 8291 for (rootAncestor = getFocusCycleRootAncestor(); 8292 rootAncestor != null && !(rootAncestor.isShowing() && 8293 rootAncestor.isFocusable() && 8294 rootAncestor.isEnabled()); 8295 rootAncestor = rootAncestor.getFocusCycleRootAncestor()) { 8296 } 8297 8298 if (rootAncestor != null) { 8299 Container rootAncestorRootAncestor = 8300 rootAncestor.getFocusCycleRootAncestor(); 8301 Container fcr = (rootAncestorRootAncestor != null) ? 8302 rootAncestorRootAncestor : rootAncestor; 8303 8304 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 8305 setGlobalCurrentFocusCycleRootPriv(fcr); 8306 rootAncestor.requestFocus(FocusEvent.Cause.TRAVERSAL_UP); 8307 } else { 8308 Window window = getContainingWindow(); 8309 8310 if (window != null) { 8311 Component toFocus = window.getFocusTraversalPolicy(). 8312 getDefaultComponent(window); 8313 if (toFocus != null) { 8314 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 8315 setGlobalCurrentFocusCycleRootPriv(window); 8316 toFocus.requestFocus(FocusEvent.Cause.TRAVERSAL_UP); 8317 } 8318 } 8319 } 8320 } 8321 8322 /** 8323 * Returns {@code true} if this {@code Component} is the 8324 * focus owner. This method is obsolete, and has been replaced by 8325 * {@code isFocusOwner()}. 8326 * 8327 * @return {@code true} if this {@code Component} is the 8328 * focus owner; {@code false} otherwise 8329 * @since 1.2 8330 */ 8331 public boolean hasFocus() { 8332 return (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 8333 getFocusOwner() == this); 8334 } 8335 8336 /** 8337 * Returns {@code true} if this {@code Component} is the 8338 * focus owner. 8339 * 8340 * @return {@code true} if this {@code Component} is the 8341 * focus owner; {@code false} otherwise 8342 * @since 1.4 8343 */ 8344 public boolean isFocusOwner() { 8345 return hasFocus(); 8346 } 8347 8348 /* 8349 * Used to disallow auto-focus-transfer on disposal of the focus owner 8350 * in the process of disposing its parent container. 8351 */ 8352 private boolean autoFocusTransferOnDisposal = true; 8353 8354 void setAutoFocusTransferOnDisposal(boolean value) { 8355 autoFocusTransferOnDisposal = value; 8356 } 8357 8358 boolean isAutoFocusTransferOnDisposal() { 8359 return autoFocusTransferOnDisposal; 8360 } 8361 8362 /** 8363 * Adds the specified popup menu to the component. 8364 * @param popup the popup menu to be added to the component. 8365 * @see #remove(MenuComponent) 8366 * @exception NullPointerException if {@code popup} is {@code null} 8367 * @since 1.1 8368 */ 8369 public void add(PopupMenu popup) { 8370 synchronized (getTreeLock()) { 8371 if (popup.parent != null) { 8372 popup.parent.remove(popup); 8373 } 8374 if (popups == null) { 8375 popups = new Vector<PopupMenu>(); 8376 } 8377 popups.addElement(popup); 8378 popup.parent = this; 8379 8380 if (peer != null) { 8381 if (popup.peer == null) { 8382 popup.addNotify(); 8383 } 8384 } 8385 } 8386 } 8387 8388 /** 8389 * Removes the specified popup menu from the component. 8390 * @param popup the popup menu to be removed 8391 * @see #add(PopupMenu) 8392 * @since 1.1 8393 */ 8394 @SuppressWarnings("unchecked") 8395 public void remove(MenuComponent popup) { 8396 synchronized (getTreeLock()) { 8397 if (popups == null) { 8398 return; 8399 } 8400 int index = popups.indexOf(popup); 8401 if (index >= 0) { 8402 PopupMenu pmenu = (PopupMenu)popup; 8403 if (pmenu.peer != null) { 8404 pmenu.removeNotify(); 8405 } 8406 pmenu.parent = null; 8407 popups.removeElementAt(index); 8408 if (popups.size() == 0) { 8409 popups = null; 8410 } 8411 } 8412 } 8413 } 8414 8415 /** 8416 * Returns a string representing the state of this component. This 8417 * method is intended to be used only for debugging purposes, and the 8418 * content and format of the returned string may vary between 8419 * implementations. The returned string may be empty but may not be 8420 * {@code null}. 8421 * 8422 * @return a string representation of this component's state 8423 * @since 1.0 8424 */ 8425 protected String paramString() { 8426 final String thisName = Objects.toString(getName(), ""); 8427 final String invalid = isValid() ? "" : ",invalid"; 8428 final String hidden = visible ? "" : ",hidden"; 8429 final String disabled = enabled ? "" : ",disabled"; 8430 return thisName + ',' + x + ',' + y + ',' + width + 'x' + height 8431 + invalid + hidden + disabled; 8432 } 8433 8434 /** 8435 * Returns a string representation of this component and its values. 8436 * @return a string representation of this component 8437 * @since 1.0 8438 */ 8439 public String toString() { 8440 return getClass().getName() + '[' + paramString() + ']'; 8441 } 8442 8443 /** 8444 * Prints a listing of this component to the standard system output 8445 * stream {@code System.out}. 8446 * @see java.lang.System#out 8447 * @since 1.0 8448 */ 8449 public void list() { 8450 list(System.out, 0); 8451 } 8452 8453 /** 8454 * Prints a listing of this component to the specified output 8455 * stream. 8456 * @param out a print stream 8457 * @throws NullPointerException if {@code out} is {@code null} 8458 * @since 1.0 8459 */ 8460 public void list(PrintStream out) { 8461 list(out, 0); 8462 } 8463 8464 /** 8465 * Prints out a list, starting at the specified indentation, to the 8466 * specified print stream. 8467 * @param out a print stream 8468 * @param indent number of spaces to indent 8469 * @see java.io.PrintStream#println(java.lang.Object) 8470 * @throws NullPointerException if {@code out} is {@code null} 8471 * @since 1.0 8472 */ 8473 public void list(PrintStream out, int indent) { 8474 for (int i = 0 ; i < indent ; i++) { 8475 out.print(" "); 8476 } 8477 out.println(this); 8478 } 8479 8480 /** 8481 * Prints a listing to the specified print writer. 8482 * @param out the print writer to print to 8483 * @throws NullPointerException if {@code out} is {@code null} 8484 * @since 1.1 8485 */ 8486 public void list(PrintWriter out) { 8487 list(out, 0); 8488 } 8489 8490 /** 8491 * Prints out a list, starting at the specified indentation, to 8492 * the specified print writer. 8493 * @param out the print writer to print to 8494 * @param indent the number of spaces to indent 8495 * @throws NullPointerException if {@code out} is {@code null} 8496 * @see java.io.PrintStream#println(java.lang.Object) 8497 * @since 1.1 8498 */ 8499 public void list(PrintWriter out, int indent) { 8500 for (int i = 0 ; i < indent ; i++) { 8501 out.print(" "); 8502 } 8503 out.println(this); 8504 } 8505 8506 /* 8507 * Fetches the native container somewhere higher up in the component 8508 * tree that contains this component. 8509 */ 8510 final Container getNativeContainer() { 8511 Container p = getContainer(); 8512 while (p != null && p.peer instanceof LightweightPeer) { 8513 p = p.getContainer(); 8514 } 8515 return p; 8516 } 8517 8518 /** 8519 * Adds a PropertyChangeListener to the listener list. The listener is 8520 * registered for all bound properties of this class, including the 8521 * following: 8522 * <ul> 8523 * <li>this Component's font ("font")</li> 8524 * <li>this Component's background color ("background")</li> 8525 * <li>this Component's foreground color ("foreground")</li> 8526 * <li>this Component's focusability ("focusable")</li> 8527 * <li>this Component's focus traversal keys enabled state 8528 * ("focusTraversalKeysEnabled")</li> 8529 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 8530 * ("forwardFocusTraversalKeys")</li> 8531 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 8532 * ("backwardFocusTraversalKeys")</li> 8533 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 8534 * ("upCycleFocusTraversalKeys")</li> 8535 * <li>this Component's preferred size ("preferredSize")</li> 8536 * <li>this Component's minimum size ("minimumSize")</li> 8537 * <li>this Component's maximum size ("maximumSize")</li> 8538 * <li>this Component's name ("name")</li> 8539 * </ul> 8540 * Note that if this {@code Component} is inheriting a bound property, then no 8541 * event will be fired in response to a change in the inherited property. 8542 * <p> 8543 * If {@code listener} is {@code null}, 8544 * no exception is thrown and no action is performed. 8545 * 8546 * @param listener the property change listener to be added 8547 * 8548 * @see #removePropertyChangeListener 8549 * @see #getPropertyChangeListeners 8550 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8551 */ 8552 public void addPropertyChangeListener( 8553 PropertyChangeListener listener) { 8554 synchronized (getObjectLock()) { 8555 if (listener == null) { 8556 return; 8557 } 8558 if (changeSupport == null) { 8559 changeSupport = new PropertyChangeSupport(this); 8560 } 8561 changeSupport.addPropertyChangeListener(listener); 8562 } 8563 } 8564 8565 /** 8566 * Removes a PropertyChangeListener from the listener list. This method 8567 * should be used to remove PropertyChangeListeners that were registered 8568 * for all bound properties of this class. 8569 * <p> 8570 * If listener is null, no exception is thrown and no action is performed. 8571 * 8572 * @param listener the PropertyChangeListener to be removed 8573 * 8574 * @see #addPropertyChangeListener 8575 * @see #getPropertyChangeListeners 8576 * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener) 8577 */ 8578 public void removePropertyChangeListener( 8579 PropertyChangeListener listener) { 8580 synchronized (getObjectLock()) { 8581 if (listener == null || changeSupport == null) { 8582 return; 8583 } 8584 changeSupport.removePropertyChangeListener(listener); 8585 } 8586 } 8587 8588 /** 8589 * Returns an array of all the property change listeners 8590 * registered on this component. 8591 * 8592 * @return all of this component's {@code PropertyChangeListener}s 8593 * or an empty array if no property change 8594 * listeners are currently registered 8595 * 8596 * @see #addPropertyChangeListener 8597 * @see #removePropertyChangeListener 8598 * @see #getPropertyChangeListeners(java.lang.String) 8599 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners 8600 * @since 1.4 8601 */ 8602 public PropertyChangeListener[] getPropertyChangeListeners() { 8603 synchronized (getObjectLock()) { 8604 if (changeSupport == null) { 8605 return new PropertyChangeListener[0]; 8606 } 8607 return changeSupport.getPropertyChangeListeners(); 8608 } 8609 } 8610 8611 /** 8612 * Adds a PropertyChangeListener to the listener list for a specific 8613 * property. The specified property may be user-defined, or one of the 8614 * following: 8615 * <ul> 8616 * <li>this Component's font ("font")</li> 8617 * <li>this Component's background color ("background")</li> 8618 * <li>this Component's foreground color ("foreground")</li> 8619 * <li>this Component's focusability ("focusable")</li> 8620 * <li>this Component's focus traversal keys enabled state 8621 * ("focusTraversalKeysEnabled")</li> 8622 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 8623 * ("forwardFocusTraversalKeys")</li> 8624 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 8625 * ("backwardFocusTraversalKeys")</li> 8626 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 8627 * ("upCycleFocusTraversalKeys")</li> 8628 * </ul> 8629 * Note that if this {@code Component} is inheriting a bound property, then no 8630 * event will be fired in response to a change in the inherited property. 8631 * <p> 8632 * If {@code propertyName} or {@code listener} is {@code null}, 8633 * no exception is thrown and no action is taken. 8634 * 8635 * @param propertyName one of the property names listed above 8636 * @param listener the property change listener to be added 8637 * 8638 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8639 * @see #getPropertyChangeListeners(java.lang.String) 8640 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8641 */ 8642 public void addPropertyChangeListener( 8643 String propertyName, 8644 PropertyChangeListener listener) { 8645 synchronized (getObjectLock()) { 8646 if (listener == null) { 8647 return; 8648 } 8649 if (changeSupport == null) { 8650 changeSupport = new PropertyChangeSupport(this); 8651 } 8652 changeSupport.addPropertyChangeListener(propertyName, listener); 8653 } 8654 } 8655 8656 /** 8657 * Removes a {@code PropertyChangeListener} from the listener 8658 * list for a specific property. This method should be used to remove 8659 * {@code PropertyChangeListener}s 8660 * that were registered for a specific bound property. 8661 * <p> 8662 * If {@code propertyName} or {@code listener} is {@code null}, 8663 * no exception is thrown and no action is taken. 8664 * 8665 * @param propertyName a valid property name 8666 * @param listener the PropertyChangeListener to be removed 8667 * 8668 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8669 * @see #getPropertyChangeListeners(java.lang.String) 8670 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) 8671 */ 8672 public void removePropertyChangeListener( 8673 String propertyName, 8674 PropertyChangeListener listener) { 8675 synchronized (getObjectLock()) { 8676 if (listener == null || changeSupport == null) { 8677 return; 8678 } 8679 changeSupport.removePropertyChangeListener(propertyName, listener); 8680 } 8681 } 8682 8683 /** 8684 * Returns an array of all the listeners which have been associated 8685 * with the named property. 8686 * 8687 * @param propertyName the property name 8688 * @return all of the {@code PropertyChangeListener}s associated with 8689 * the named property; if no such listeners have been added or 8690 * if {@code propertyName} is {@code null}, an empty 8691 * array is returned 8692 * 8693 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8694 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8695 * @see #getPropertyChangeListeners 8696 * @since 1.4 8697 */ 8698 public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { 8699 synchronized (getObjectLock()) { 8700 if (changeSupport == null) { 8701 return new PropertyChangeListener[0]; 8702 } 8703 return changeSupport.getPropertyChangeListeners(propertyName); 8704 } 8705 } 8706 8707 /** 8708 * Support for reporting bound property changes for Object properties. 8709 * This method can be called when a bound property has changed and it will 8710 * send the appropriate PropertyChangeEvent to any registered 8711 * PropertyChangeListeners. 8712 * 8713 * @param propertyName the property whose value has changed 8714 * @param oldValue the property's previous value 8715 * @param newValue the property's new value 8716 */ 8717 protected void firePropertyChange(String propertyName, 8718 Object oldValue, Object newValue) { 8719 PropertyChangeSupport changeSupport; 8720 synchronized (getObjectLock()) { 8721 changeSupport = this.changeSupport; 8722 } 8723 if (changeSupport == null || 8724 (oldValue != null && newValue != null && oldValue.equals(newValue))) { 8725 return; 8726 } 8727 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8728 } 8729 8730 /** 8731 * Support for reporting bound property changes for boolean properties. 8732 * This method can be called when a bound property has changed and it will 8733 * send the appropriate PropertyChangeEvent to any registered 8734 * PropertyChangeListeners. 8735 * 8736 * @param propertyName the property whose value has changed 8737 * @param oldValue the property's previous value 8738 * @param newValue the property's new value 8739 * @since 1.4 8740 */ 8741 protected void firePropertyChange(String propertyName, 8742 boolean oldValue, boolean newValue) { 8743 PropertyChangeSupport changeSupport = this.changeSupport; 8744 if (changeSupport == null || oldValue == newValue) { 8745 return; 8746 } 8747 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8748 } 8749 8750 /** 8751 * Support for reporting bound property changes for integer properties. 8752 * This method can be called when a bound property has changed and it will 8753 * send the appropriate PropertyChangeEvent to any registered 8754 * PropertyChangeListeners. 8755 * 8756 * @param propertyName the property whose value has changed 8757 * @param oldValue the property's previous value 8758 * @param newValue the property's new value 8759 * @since 1.4 8760 */ 8761 protected void firePropertyChange(String propertyName, 8762 int oldValue, int newValue) { 8763 PropertyChangeSupport changeSupport = this.changeSupport; 8764 if (changeSupport == null || oldValue == newValue) { 8765 return; 8766 } 8767 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8768 } 8769 8770 /** 8771 * Reports a bound property change. 8772 * 8773 * @param propertyName the programmatic name of the property 8774 * that was changed 8775 * @param oldValue the old value of the property (as a byte) 8776 * @param newValue the new value of the property (as a byte) 8777 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8778 * java.lang.Object) 8779 * @since 1.5 8780 */ 8781 public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { 8782 if (changeSupport == null || oldValue == newValue) { 8783 return; 8784 } 8785 firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue)); 8786 } 8787 8788 /** 8789 * Reports a bound property change. 8790 * 8791 * @param propertyName the programmatic name of the property 8792 * that was changed 8793 * @param oldValue the old value of the property (as a char) 8794 * @param newValue the new value of the property (as a char) 8795 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8796 * java.lang.Object) 8797 * @since 1.5 8798 */ 8799 public void firePropertyChange(String propertyName, char oldValue, char newValue) { 8800 if (changeSupport == null || oldValue == newValue) { 8801 return; 8802 } 8803 firePropertyChange(propertyName, Character.valueOf(oldValue), Character.valueOf(newValue)); 8804 } 8805 8806 /** 8807 * Reports a bound property change. 8808 * 8809 * @param propertyName the programmatic name of the property 8810 * that was changed 8811 * @param oldValue the old value of the property (as a short) 8812 * @param newValue the new value of the property (as a short) 8813 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8814 * java.lang.Object) 8815 * @since 1.5 8816 */ 8817 public void firePropertyChange(String propertyName, short oldValue, short newValue) { 8818 if (changeSupport == null || oldValue == newValue) { 8819 return; 8820 } 8821 firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue)); 8822 } 8823 8824 8825 /** 8826 * Reports a bound property change. 8827 * 8828 * @param propertyName the programmatic name of the property 8829 * that was changed 8830 * @param oldValue the old value of the property (as a long) 8831 * @param newValue the new value of the property (as a long) 8832 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8833 * java.lang.Object) 8834 * @since 1.5 8835 */ 8836 public void firePropertyChange(String propertyName, long oldValue, long newValue) { 8837 if (changeSupport == null || oldValue == newValue) { 8838 return; 8839 } 8840 firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue)); 8841 } 8842 8843 /** 8844 * Reports a bound property change. 8845 * 8846 * @param propertyName the programmatic name of the property 8847 * that was changed 8848 * @param oldValue the old value of the property (as a float) 8849 * @param newValue the new value of the property (as a float) 8850 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8851 * java.lang.Object) 8852 * @since 1.5 8853 */ 8854 public void firePropertyChange(String propertyName, float oldValue, float newValue) { 8855 if (changeSupport == null || oldValue == newValue) { 8856 return; 8857 } 8858 firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue)); 8859 } 8860 8861 /** 8862 * Reports a bound property change. 8863 * 8864 * @param propertyName the programmatic name of the property 8865 * that was changed 8866 * @param oldValue the old value of the property (as a double) 8867 * @param newValue the new value of the property (as a double) 8868 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8869 * java.lang.Object) 8870 * @since 1.5 8871 */ 8872 public void firePropertyChange(String propertyName, double oldValue, double newValue) { 8873 if (changeSupport == null || oldValue == newValue) { 8874 return; 8875 } 8876 firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue)); 8877 } 8878 8879 8880 // Serialization support. 8881 8882 /** 8883 * Component Serialized Data Version. 8884 * 8885 * @serial 8886 */ 8887 private int componentSerializedDataVersion = 4; 8888 8889 /** 8890 * This hack is for Swing serialization. It will invoke 8891 * the Swing package private method {@code compWriteObjectNotify}. 8892 */ 8893 private void doSwingSerialization() { 8894 if (!(this instanceof JComponent)) { 8895 return; 8896 } 8897 @SuppressWarnings("deprecation") 8898 Package swingPackage = Package.getPackage("javax.swing"); 8899 // For Swing serialization to correctly work Swing needs to 8900 // be notified before Component does it's serialization. This 8901 // hack accommodates this. 8902 // 8903 // Swing classes MUST be loaded by the bootstrap class loader, 8904 // otherwise we don't consider them. 8905 for (Class<?> klass = Component.this.getClass(); klass != null; 8906 klass = klass.getSuperclass()) { 8907 if (klass.getPackage() == swingPackage && 8908 klass.getClassLoader() == null) { 8909 8910 SwingAccessor.getJComponentAccessor() 8911 .compWriteObjectNotify((JComponent) this); 8912 return; 8913 } 8914 } 8915 } 8916 8917 /** 8918 * Writes default serializable fields to stream. Writes 8919 * a variety of serializable listeners as optional data. 8920 * The non-serializable listeners are detected and 8921 * no attempt is made to serialize them. 8922 * 8923 * @param s the {@code ObjectOutputStream} to write 8924 * @serialData {@code null} terminated sequence of 8925 * 0 or more pairs; the pair consists of a {@code String} 8926 * and an {@code Object}; the {@code String} indicates 8927 * the type of object and is one of the following (as of 1.4): 8928 * {@code componentListenerK} indicating an 8929 * {@code ComponentListener} object; 8930 * {@code focusListenerK} indicating an 8931 * {@code FocusListener} object; 8932 * {@code keyListenerK} indicating an 8933 * {@code KeyListener} object; 8934 * {@code mouseListenerK} indicating an 8935 * {@code MouseListener} object; 8936 * {@code mouseMotionListenerK} indicating an 8937 * {@code MouseMotionListener} object; 8938 * {@code inputMethodListenerK} indicating an 8939 * {@code InputMethodListener} object; 8940 * {@code hierarchyListenerK} indicating an 8941 * {@code HierarchyListener} object; 8942 * {@code hierarchyBoundsListenerK} indicating an 8943 * {@code HierarchyBoundsListener} object; 8944 * {@code mouseWheelListenerK} indicating an 8945 * {@code MouseWheelListener} object 8946 * @serialData an optional {@code ComponentOrientation} 8947 * (after {@code inputMethodListener}, as of 1.2) 8948 * 8949 * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener) 8950 * @see #componentListenerK 8951 * @see #focusListenerK 8952 * @see #keyListenerK 8953 * @see #mouseListenerK 8954 * @see #mouseMotionListenerK 8955 * @see #inputMethodListenerK 8956 * @see #hierarchyListenerK 8957 * @see #hierarchyBoundsListenerK 8958 * @see #mouseWheelListenerK 8959 * @see #readObject(ObjectInputStream) 8960 */ 8961 private void writeObject(ObjectOutputStream s) 8962 throws IOException 8963 { 8964 doSwingSerialization(); 8965 8966 s.defaultWriteObject(); 8967 8968 AWTEventMulticaster.save(s, componentListenerK, componentListener); 8969 AWTEventMulticaster.save(s, focusListenerK, focusListener); 8970 AWTEventMulticaster.save(s, keyListenerK, keyListener); 8971 AWTEventMulticaster.save(s, mouseListenerK, mouseListener); 8972 AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener); 8973 AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener); 8974 8975 s.writeObject(null); 8976 s.writeObject(componentOrientation); 8977 8978 AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener); 8979 AWTEventMulticaster.save(s, hierarchyBoundsListenerK, 8980 hierarchyBoundsListener); 8981 s.writeObject(null); 8982 8983 AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener); 8984 s.writeObject(null); 8985 8986 } 8987 8988 /** 8989 * Reads the {@code ObjectInputStream} and if it isn't 8990 * {@code null} adds a listener to receive a variety 8991 * of events fired by the component. 8992 * Unrecognized keys or values will be ignored. 8993 * 8994 * @param s the {@code ObjectInputStream} to read 8995 * @see #writeObject(ObjectOutputStream) 8996 */ 8997 private void readObject(ObjectInputStream s) 8998 throws ClassNotFoundException, IOException 8999 { 9000 objectLock = new Object(); 9001 9002 acc = AccessController.getContext(); 9003 9004 s.defaultReadObject(); 9005 9006 appContext = AppContext.getAppContext(); 9007 coalescingEnabled = checkCoalescing(); 9008 if (componentSerializedDataVersion < 4) { 9009 // These fields are non-transient and rely on default 9010 // serialization. However, the default values are insufficient, 9011 // so we need to set them explicitly for object data streams prior 9012 // to 1.4. 9013 focusable = true; 9014 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; 9015 initializeFocusTraversalKeys(); 9016 focusTraversalKeysEnabled = true; 9017 } 9018 9019 Object keyOrNull; 9020 while(null != (keyOrNull = s.readObject())) { 9021 String key = ((String)keyOrNull).intern(); 9022 9023 if (componentListenerK == key) 9024 addComponentListener((ComponentListener)(s.readObject())); 9025 9026 else if (focusListenerK == key) 9027 addFocusListener((FocusListener)(s.readObject())); 9028 9029 else if (keyListenerK == key) 9030 addKeyListener((KeyListener)(s.readObject())); 9031 9032 else if (mouseListenerK == key) 9033 addMouseListener((MouseListener)(s.readObject())); 9034 9035 else if (mouseMotionListenerK == key) 9036 addMouseMotionListener((MouseMotionListener)(s.readObject())); 9037 9038 else if (inputMethodListenerK == key) 9039 addInputMethodListener((InputMethodListener)(s.readObject())); 9040 9041 else // skip value for unrecognized key 9042 s.readObject(); 9043 9044 } 9045 9046 // Read the component's orientation if it's present 9047 Object orient = null; 9048 9049 try { 9050 orient = s.readObject(); 9051 } catch (java.io.OptionalDataException e) { 9052 // JDK 1.1 instances will not have this optional data. 9053 // e.eof will be true to indicate that there is no more 9054 // data available for this object. 9055 // If e.eof is not true, throw the exception as it 9056 // might have been caused by reasons unrelated to 9057 // componentOrientation. 9058 9059 if (!e.eof) { 9060 throw (e); 9061 } 9062 } 9063 9064 if (orient != null) { 9065 componentOrientation = (ComponentOrientation)orient; 9066 } else { 9067 componentOrientation = ComponentOrientation.UNKNOWN; 9068 } 9069 9070 try { 9071 while(null != (keyOrNull = s.readObject())) { 9072 String key = ((String)keyOrNull).intern(); 9073 9074 if (hierarchyListenerK == key) { 9075 addHierarchyListener((HierarchyListener)(s.readObject())); 9076 } 9077 else if (hierarchyBoundsListenerK == key) { 9078 addHierarchyBoundsListener((HierarchyBoundsListener) 9079 (s.readObject())); 9080 } 9081 else { 9082 // skip value for unrecognized key 9083 s.readObject(); 9084 } 9085 } 9086 } catch (java.io.OptionalDataException e) { 9087 // JDK 1.1/1.2 instances will not have this optional data. 9088 // e.eof will be true to indicate that there is no more 9089 // data available for this object. 9090 // If e.eof is not true, throw the exception as it 9091 // might have been caused by reasons unrelated to 9092 // hierarchy and hierarchyBounds listeners. 9093 9094 if (!e.eof) { 9095 throw (e); 9096 } 9097 } 9098 9099 try { 9100 while (null != (keyOrNull = s.readObject())) { 9101 String key = ((String)keyOrNull).intern(); 9102 9103 if (mouseWheelListenerK == key) { 9104 addMouseWheelListener((MouseWheelListener)(s.readObject())); 9105 } 9106 else { 9107 // skip value for unrecognized key 9108 s.readObject(); 9109 } 9110 } 9111 } catch (java.io.OptionalDataException e) { 9112 // pre-1.3 instances will not have this optional data. 9113 // e.eof will be true to indicate that there is no more 9114 // data available for this object. 9115 // If e.eof is not true, throw the exception as it 9116 // might have been caused by reasons unrelated to 9117 // mouse wheel listeners 9118 9119 if (!e.eof) { 9120 throw (e); 9121 } 9122 } 9123 9124 if (popups != null) { 9125 int npopups = popups.size(); 9126 for (int i = 0 ; i < npopups ; i++) { 9127 PopupMenu popup = popups.elementAt(i); 9128 popup.parent = this; 9129 } 9130 } 9131 } 9132 9133 /** 9134 * Sets the language-sensitive orientation that is to be used to order 9135 * the elements or text within this component. Language-sensitive 9136 * {@code LayoutManager} and {@code Component} 9137 * subclasses will use this property to 9138 * determine how to lay out and draw components. 9139 * <p> 9140 * At construction time, a component's orientation is set to 9141 * {@code ComponentOrientation.UNKNOWN}, 9142 * indicating that it has not been specified 9143 * explicitly. The UNKNOWN orientation behaves the same as 9144 * {@code ComponentOrientation.LEFT_TO_RIGHT}. 9145 * <p> 9146 * To set the orientation of a single component, use this method. 9147 * To set the orientation of an entire component 9148 * hierarchy, use 9149 * {@link #applyComponentOrientation applyComponentOrientation}. 9150 * <p> 9151 * This method changes layout-related information, and therefore, 9152 * invalidates the component hierarchy. 9153 * 9154 * @param o the orientation to be set 9155 * 9156 * @see ComponentOrientation 9157 * @see #invalidate 9158 * 9159 * @author Laura Werner, IBM 9160 */ 9161 public void setComponentOrientation(ComponentOrientation o) { 9162 ComponentOrientation oldValue = componentOrientation; 9163 componentOrientation = o; 9164 9165 // This is a bound property, so report the change to 9166 // any registered listeners. (Cheap if there are none.) 9167 firePropertyChange("componentOrientation", oldValue, o); 9168 9169 // This could change the preferred size of the Component. 9170 invalidateIfValid(); 9171 } 9172 9173 /** 9174 * Retrieves the language-sensitive orientation that is to be used to order 9175 * the elements or text within this component. {@code LayoutManager} 9176 * and {@code Component} 9177 * subclasses that wish to respect orientation should call this method to 9178 * get the component's orientation before performing layout or drawing. 9179 * 9180 * @return the orientation to order the elements or text 9181 * @see ComponentOrientation 9182 * 9183 * @author Laura Werner, IBM 9184 */ 9185 public ComponentOrientation getComponentOrientation() { 9186 return componentOrientation; 9187 } 9188 9189 /** 9190 * Sets the {@code ComponentOrientation} property of this component 9191 * and all components contained within it. 9192 * <p> 9193 * This method changes layout-related information, and therefore, 9194 * invalidates the component hierarchy. 9195 * 9196 * 9197 * @param orientation the new component orientation of this component and 9198 * the components contained within it. 9199 * @exception NullPointerException if {@code orientation} is null. 9200 * @see #setComponentOrientation 9201 * @see #getComponentOrientation 9202 * @see #invalidate 9203 * @since 1.4 9204 */ 9205 public void applyComponentOrientation(ComponentOrientation orientation) { 9206 if (orientation == null) { 9207 throw new NullPointerException(); 9208 } 9209 setComponentOrientation(orientation); 9210 } 9211 9212 final boolean canBeFocusOwner() { 9213 // It is enabled, visible, focusable. 9214 if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) { 9215 return true; 9216 } 9217 return false; 9218 } 9219 9220 /** 9221 * Checks that this component meets the prerequisites to be focus owner: 9222 * - it is enabled, visible, focusable 9223 * - it's parents are all enabled and showing 9224 * - top-level window is focusable 9225 * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts 9226 * this component as focus owner 9227 * @since 1.5 9228 */ 9229 final boolean canBeFocusOwnerRecursively() { 9230 // - it is enabled, visible, focusable 9231 if (!canBeFocusOwner()) { 9232 return false; 9233 } 9234 9235 // - it's parents are all enabled and showing 9236 synchronized(getTreeLock()) { 9237 if (parent != null) { 9238 return parent.canContainFocusOwner(this); 9239 } 9240 } 9241 return true; 9242 } 9243 9244 /** 9245 * Fix the location of the HW component in a LW container hierarchy. 9246 */ 9247 final void relocateComponent() { 9248 synchronized (getTreeLock()) { 9249 if (peer == null) { 9250 return; 9251 } 9252 int nativeX = x; 9253 int nativeY = y; 9254 for (Component cont = getContainer(); 9255 cont != null && cont.isLightweight(); 9256 cont = cont.getContainer()) 9257 { 9258 nativeX += cont.x; 9259 nativeY += cont.y; 9260 } 9261 peer.setBounds(nativeX, nativeY, width, height, 9262 ComponentPeer.SET_LOCATION); 9263 } 9264 } 9265 9266 /** 9267 * Returns the {@code Window} ancestor of the component. 9268 * @return Window ancestor of the component or component by itself if it is Window; 9269 * null, if component is not a part of window hierarchy 9270 */ 9271 Window getContainingWindow() { 9272 return SunToolkit.getContainingWindow(this); 9273 } 9274 9275 /** 9276 * Initialize JNI field and method IDs 9277 */ 9278 private static native void initIDs(); 9279 9280 /* 9281 * --- Accessibility Support --- 9282 * 9283 * Component will contain all of the methods in interface Accessible, 9284 * though it won't actually implement the interface - that will be up 9285 * to the individual objects which extend Component. 9286 */ 9287 9288 /** 9289 * The {@code AccessibleContext} associated with this {@code Component}. 9290 */ 9291 protected AccessibleContext accessibleContext = null; 9292 9293 /** 9294 * Gets the {@code AccessibleContext} associated 9295 * with this {@code Component}. 9296 * The method implemented by this base 9297 * class returns null. Classes that extend {@code Component} 9298 * should implement this method to return the 9299 * {@code AccessibleContext} associated with the subclass. 9300 * 9301 * 9302 * @return the {@code AccessibleContext} of this 9303 * {@code Component} 9304 * @since 1.3 9305 */ 9306 public AccessibleContext getAccessibleContext() { 9307 return accessibleContext; 9308 } 9309 9310 /** 9311 * Inner class of Component used to provide default support for 9312 * accessibility. This class is not meant to be used directly by 9313 * application developers, but is instead meant only to be 9314 * subclassed by component developers. 9315 * <p> 9316 * The class used to obtain the accessible role for this object. 9317 * @since 1.3 9318 */ 9319 protected abstract class AccessibleAWTComponent extends AccessibleContext 9320 implements Serializable, AccessibleComponent { 9321 9322 private static final long serialVersionUID = 642321655757800191L; 9323 9324 /** 9325 * Though the class is abstract, this should be called by 9326 * all sub-classes. 9327 */ 9328 protected AccessibleAWTComponent() { 9329 } 9330 9331 /** 9332 * Number of PropertyChangeListener objects registered. It's used 9333 * to add/remove ComponentListener and FocusListener to track 9334 * target Component's state. 9335 */ 9336 private transient volatile int propertyListenersCount = 0; 9337 9338 /** 9339 * A component listener to track show/hide/resize events 9340 * and convert them to PropertyChange events. 9341 */ 9342 protected ComponentListener accessibleAWTComponentHandler = null; 9343 9344 /** 9345 * A listener to track focus events 9346 * and convert them to PropertyChange events. 9347 */ 9348 protected FocusListener accessibleAWTFocusHandler = null; 9349 9350 /** 9351 * Fire PropertyChange listener, if one is registered, 9352 * when shown/hidden.. 9353 * @since 1.3 9354 */ 9355 protected class AccessibleAWTComponentHandler implements ComponentListener, Serializable { 9356 private static final long serialVersionUID = -1009684107426231869L; 9357 9358 public void componentHidden(ComponentEvent e) { 9359 if (accessibleContext != null) { 9360 accessibleContext.firePropertyChange( 9361 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9362 AccessibleState.VISIBLE, null); 9363 } 9364 } 9365 9366 public void componentShown(ComponentEvent e) { 9367 if (accessibleContext != null) { 9368 accessibleContext.firePropertyChange( 9369 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9370 null, AccessibleState.VISIBLE); 9371 } 9372 } 9373 9374 public void componentMoved(ComponentEvent e) { 9375 } 9376 9377 public void componentResized(ComponentEvent e) { 9378 } 9379 } // inner class AccessibleAWTComponentHandler 9380 9381 9382 /** 9383 * Fire PropertyChange listener, if one is registered, 9384 * when focus events happen 9385 * @since 1.3 9386 */ 9387 protected class AccessibleAWTFocusHandler implements FocusListener, Serializable { 9388 private static final long serialVersionUID = 3150908257351582233L; 9389 9390 public void focusGained(FocusEvent event) { 9391 if (accessibleContext != null) { 9392 accessibleContext.firePropertyChange( 9393 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9394 null, AccessibleState.FOCUSED); 9395 } 9396 } 9397 public void focusLost(FocusEvent event) { 9398 if (accessibleContext != null) { 9399 accessibleContext.firePropertyChange( 9400 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9401 AccessibleState.FOCUSED, null); 9402 } 9403 } 9404 } // inner class AccessibleAWTFocusHandler 9405 9406 9407 /** 9408 * Adds a {@code PropertyChangeListener} to the listener list. 9409 * 9410 * @param listener the property change listener to be added 9411 */ 9412 public void addPropertyChangeListener(PropertyChangeListener listener) { 9413 if (accessibleAWTComponentHandler == null) { 9414 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler(); 9415 } 9416 if (accessibleAWTFocusHandler == null) { 9417 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler(); 9418 } 9419 if (propertyListenersCount++ == 0) { 9420 Component.this.addComponentListener(accessibleAWTComponentHandler); 9421 Component.this.addFocusListener(accessibleAWTFocusHandler); 9422 } 9423 super.addPropertyChangeListener(listener); 9424 } 9425 9426 /** 9427 * Remove a PropertyChangeListener from the listener list. 9428 * This removes a PropertyChangeListener that was registered 9429 * for all properties. 9430 * 9431 * @param listener The PropertyChangeListener to be removed 9432 */ 9433 public void removePropertyChangeListener(PropertyChangeListener listener) { 9434 if (--propertyListenersCount == 0) { 9435 Component.this.removeComponentListener(accessibleAWTComponentHandler); 9436 Component.this.removeFocusListener(accessibleAWTFocusHandler); 9437 } 9438 super.removePropertyChangeListener(listener); 9439 } 9440 9441 // AccessibleContext methods 9442 // 9443 /** 9444 * Gets the accessible name of this object. This should almost never 9445 * return {@code java.awt.Component.getName()}, 9446 * as that generally isn't a localized name, 9447 * and doesn't have meaning for the user. If the 9448 * object is fundamentally a text object (e.g. a menu item), the 9449 * accessible name should be the text of the object (e.g. "save"). 9450 * If the object has a tooltip, the tooltip text may also be an 9451 * appropriate String to return. 9452 * 9453 * @return the localized name of the object -- can be 9454 * {@code null} if this 9455 * object does not have a name 9456 * @see javax.accessibility.AccessibleContext#setAccessibleName 9457 */ 9458 public String getAccessibleName() { 9459 return accessibleName; 9460 } 9461 9462 /** 9463 * Gets the accessible description of this object. This should be 9464 * a concise, localized description of what this object is - what 9465 * is its meaning to the user. If the object has a tooltip, the 9466 * tooltip text may be an appropriate string to return, assuming 9467 * it contains a concise description of the object (instead of just 9468 * the name of the object - e.g. a "Save" icon on a toolbar that 9469 * had "save" as the tooltip text shouldn't return the tooltip 9470 * text as the description, but something like "Saves the current 9471 * text document" instead). 9472 * 9473 * @return the localized description of the object -- can be 9474 * {@code null} if this object does not have a description 9475 * @see javax.accessibility.AccessibleContext#setAccessibleDescription 9476 */ 9477 public String getAccessibleDescription() { 9478 return accessibleDescription; 9479 } 9480 9481 /** 9482 * Gets the role of this object. 9483 * 9484 * @return an instance of {@code AccessibleRole} 9485 * describing the role of the object 9486 * @see javax.accessibility.AccessibleRole 9487 */ 9488 public AccessibleRole getAccessibleRole() { 9489 return AccessibleRole.AWT_COMPONENT; 9490 } 9491 9492 /** 9493 * Gets the state of this object. 9494 * 9495 * @return an instance of {@code AccessibleStateSet} 9496 * containing the current state set of the object 9497 * @see javax.accessibility.AccessibleState 9498 */ 9499 public AccessibleStateSet getAccessibleStateSet() { 9500 return Component.this.getAccessibleStateSet(); 9501 } 9502 9503 /** 9504 * Gets the {@code Accessible} parent of this object. 9505 * If the parent of this object implements {@code Accessible}, 9506 * this method should simply return {@code getParent}. 9507 * 9508 * @return the {@code Accessible} parent of this 9509 * object -- can be {@code null} if this 9510 * object does not have an {@code Accessible} parent 9511 */ 9512 public Accessible getAccessibleParent() { 9513 if (accessibleParent != null) { 9514 return accessibleParent; 9515 } else { 9516 Container parent = getParent(); 9517 if (parent instanceof Accessible) { 9518 return (Accessible) parent; 9519 } 9520 } 9521 return null; 9522 } 9523 9524 /** 9525 * Gets the index of this object in its accessible parent. 9526 * 9527 * @return the index of this object in its parent; or -1 if this 9528 * object does not have an accessible parent 9529 * @see #getAccessibleParent 9530 */ 9531 public int getAccessibleIndexInParent() { 9532 return Component.this.getAccessibleIndexInParent(); 9533 } 9534 9535 /** 9536 * Returns the number of accessible children in the object. If all 9537 * of the children of this object implement {@code Accessible}, 9538 * then this method should return the number of children of this object. 9539 * 9540 * @return the number of accessible children in the object 9541 */ 9542 public int getAccessibleChildrenCount() { 9543 return 0; // Components don't have children 9544 } 9545 9546 /** 9547 * Returns the nth {@code Accessible} child of the object. 9548 * 9549 * @param i zero-based index of child 9550 * @return the nth {@code Accessible} child of the object 9551 */ 9552 public Accessible getAccessibleChild(int i) { 9553 return null; // Components don't have children 9554 } 9555 9556 /** 9557 * Returns the locale of this object. 9558 * 9559 * @return the locale of this object 9560 */ 9561 public Locale getLocale() { 9562 return Component.this.getLocale(); 9563 } 9564 9565 /** 9566 * Gets the {@code AccessibleComponent} associated 9567 * with this object if one exists. 9568 * Otherwise return {@code null}. 9569 * 9570 * @return the component 9571 */ 9572 public AccessibleComponent getAccessibleComponent() { 9573 return this; 9574 } 9575 9576 9577 // AccessibleComponent methods 9578 // 9579 /** 9580 * Gets the background color of this object. 9581 * 9582 * @return the background color, if supported, of the object; 9583 * otherwise, {@code null} 9584 */ 9585 public Color getBackground() { 9586 return Component.this.getBackground(); 9587 } 9588 9589 /** 9590 * Sets the background color of this object. 9591 * (For transparency, see {@code isOpaque}.) 9592 * 9593 * @param c the new {@code Color} for the background 9594 * @see Component#isOpaque 9595 */ 9596 public void setBackground(Color c) { 9597 Component.this.setBackground(c); 9598 } 9599 9600 /** 9601 * Gets the foreground color of this object. 9602 * 9603 * @return the foreground color, if supported, of the object; 9604 * otherwise, {@code null} 9605 */ 9606 public Color getForeground() { 9607 return Component.this.getForeground(); 9608 } 9609 9610 /** 9611 * Sets the foreground color of this object. 9612 * 9613 * @param c the new {@code Color} for the foreground 9614 */ 9615 public void setForeground(Color c) { 9616 Component.this.setForeground(c); 9617 } 9618 9619 /** 9620 * Gets the {@code Cursor} of this object. 9621 * 9622 * @return the {@code Cursor}, if supported, 9623 * of the object; otherwise, {@code null} 9624 */ 9625 public Cursor getCursor() { 9626 return Component.this.getCursor(); 9627 } 9628 9629 /** 9630 * Sets the {@code Cursor} of this object. 9631 * <p> 9632 * The method may have no visual effect if the Java platform 9633 * implementation and/or the native system do not support 9634 * changing the mouse cursor shape. 9635 * @param cursor the new {@code Cursor} for the object 9636 */ 9637 public void setCursor(Cursor cursor) { 9638 Component.this.setCursor(cursor); 9639 } 9640 9641 /** 9642 * Gets the {@code Font} of this object. 9643 * 9644 * @return the {@code Font}, if supported, 9645 * for the object; otherwise, {@code null} 9646 */ 9647 public Font getFont() { 9648 return Component.this.getFont(); 9649 } 9650 9651 /** 9652 * Sets the {@code Font} of this object. 9653 * 9654 * @param f the new {@code Font} for the object 9655 */ 9656 public void setFont(Font f) { 9657 Component.this.setFont(f); 9658 } 9659 9660 /** 9661 * Gets the {@code FontMetrics} of this object. 9662 * 9663 * @param f the {@code Font} 9664 * @return the {@code FontMetrics}, if supported, 9665 * the object; otherwise, {@code null} 9666 * @see #getFont 9667 */ 9668 public FontMetrics getFontMetrics(Font f) { 9669 if (f == null) { 9670 return null; 9671 } else { 9672 return Component.this.getFontMetrics(f); 9673 } 9674 } 9675 9676 /** 9677 * Determines if the object is enabled. 9678 * 9679 * @return true if object is enabled; otherwise, false 9680 */ 9681 public boolean isEnabled() { 9682 return Component.this.isEnabled(); 9683 } 9684 9685 /** 9686 * Sets the enabled state of the object. 9687 * 9688 * @param b if true, enables this object; otherwise, disables it 9689 */ 9690 public void setEnabled(boolean b) { 9691 boolean old = Component.this.isEnabled(); 9692 Component.this.setEnabled(b); 9693 if (b != old) { 9694 if (accessibleContext != null) { 9695 if (b) { 9696 accessibleContext.firePropertyChange( 9697 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9698 null, AccessibleState.ENABLED); 9699 } else { 9700 accessibleContext.firePropertyChange( 9701 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9702 AccessibleState.ENABLED, null); 9703 } 9704 } 9705 } 9706 } 9707 9708 /** 9709 * Determines if the object is visible. Note: this means that the 9710 * object intends to be visible; however, it may not in fact be 9711 * showing on the screen because one of the objects that this object 9712 * is contained by is not visible. To determine if an object is 9713 * showing on the screen, use {@code isShowing}. 9714 * 9715 * @return true if object is visible; otherwise, false 9716 */ 9717 public boolean isVisible() { 9718 return Component.this.isVisible(); 9719 } 9720 9721 /** 9722 * Sets the visible state of the object. 9723 * 9724 * @param b if true, shows this object; otherwise, hides it 9725 */ 9726 public void setVisible(boolean b) { 9727 boolean old = Component.this.isVisible(); 9728 Component.this.setVisible(b); 9729 if (b != old) { 9730 if (accessibleContext != null) { 9731 if (b) { 9732 accessibleContext.firePropertyChange( 9733 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9734 null, AccessibleState.VISIBLE); 9735 } else { 9736 accessibleContext.firePropertyChange( 9737 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9738 AccessibleState.VISIBLE, null); 9739 } 9740 } 9741 } 9742 } 9743 9744 /** 9745 * Determines if the object is showing. This is determined by checking 9746 * the visibility of the object and ancestors of the object. Note: 9747 * this will return true even if the object is obscured by another 9748 * (for example, it happens to be underneath a menu that was pulled 9749 * down). 9750 * 9751 * @return true if object is showing; otherwise, false 9752 */ 9753 public boolean isShowing() { 9754 return Component.this.isShowing(); 9755 } 9756 9757 /** 9758 * Checks whether the specified point is within this object's bounds, 9759 * where the point's x and y coordinates are defined to be relative to 9760 * the coordinate system of the object. 9761 * 9762 * @param p the {@code Point} relative to the 9763 * coordinate system of the object 9764 * @return true if object contains {@code Point}; otherwise false 9765 */ 9766 public boolean contains(Point p) { 9767 return Component.this.contains(p); 9768 } 9769 9770 /** 9771 * Returns the location of the object on the screen. 9772 * 9773 * @return location of object on screen -- can be 9774 * {@code null} if this object is not on the screen 9775 */ 9776 public Point getLocationOnScreen() { 9777 synchronized (Component.this.getTreeLock()) { 9778 if (Component.this.isShowing()) { 9779 return Component.this.getLocationOnScreen(); 9780 } else { 9781 return null; 9782 } 9783 } 9784 } 9785 9786 /** 9787 * Gets the location of the object relative to the parent in the form 9788 * of a point specifying the object's top-left corner in the screen's 9789 * coordinate space. 9790 * 9791 * @return an instance of Point representing the top-left corner of 9792 * the object's bounds in the coordinate space of the screen; 9793 * {@code null} if this object or its parent are not on the screen 9794 */ 9795 public Point getLocation() { 9796 return Component.this.getLocation(); 9797 } 9798 9799 /** 9800 * Sets the location of the object relative to the parent. 9801 * @param p the coordinates of the object 9802 */ 9803 public void setLocation(Point p) { 9804 Component.this.setLocation(p); 9805 } 9806 9807 /** 9808 * Gets the bounds of this object in the form of a Rectangle object. 9809 * The bounds specify this object's width, height, and location 9810 * relative to its parent. 9811 * 9812 * @return a rectangle indicating this component's bounds; 9813 * {@code null} if this object is not on the screen 9814 */ 9815 public Rectangle getBounds() { 9816 return Component.this.getBounds(); 9817 } 9818 9819 /** 9820 * Sets the bounds of this object in the form of a 9821 * {@code Rectangle} object. 9822 * The bounds specify this object's width, height, and location 9823 * relative to its parent. 9824 * 9825 * @param r a rectangle indicating this component's bounds 9826 */ 9827 public void setBounds(Rectangle r) { 9828 Component.this.setBounds(r); 9829 } 9830 9831 /** 9832 * Returns the size of this object in the form of a 9833 * {@code Dimension} object. The height field of the 9834 * {@code Dimension} object contains this object's 9835 * height, and the width field of the {@code Dimension} 9836 * object contains this object's width. 9837 * 9838 * @return a {@code Dimension} object that indicates 9839 * the size of this component; {@code null} if 9840 * this object is not on the screen 9841 */ 9842 public Dimension getSize() { 9843 return Component.this.getSize(); 9844 } 9845 9846 /** 9847 * Resizes this object so that it has width and height. 9848 * 9849 * @param d the dimension specifying the new size of the object 9850 */ 9851 public void setSize(Dimension d) { 9852 Component.this.setSize(d); 9853 } 9854 9855 /** 9856 * Returns the {@code Accessible} child, 9857 * if one exists, contained at the local 9858 * coordinate {@code Point}. Otherwise returns 9859 * {@code null}. 9860 * 9861 * @param p the point defining the top-left corner of 9862 * the {@code Accessible}, given in the 9863 * coordinate space of the object's parent 9864 * @return the {@code Accessible}, if it exists, 9865 * at the specified location; else {@code null} 9866 */ 9867 public Accessible getAccessibleAt(Point p) { 9868 return null; // Components don't have children 9869 } 9870 9871 /** 9872 * Returns whether this object can accept focus or not. 9873 * 9874 * @return true if object can accept focus; otherwise false 9875 */ 9876 public boolean isFocusTraversable() { 9877 return Component.this.isFocusTraversable(); 9878 } 9879 9880 /** 9881 * Requests focus for this object. 9882 */ 9883 public void requestFocus() { 9884 Component.this.requestFocus(); 9885 } 9886 9887 /** 9888 * Adds the specified focus listener to receive focus events from this 9889 * component. 9890 * 9891 * @param l the focus listener 9892 */ 9893 public void addFocusListener(FocusListener l) { 9894 Component.this.addFocusListener(l); 9895 } 9896 9897 /** 9898 * Removes the specified focus listener so it no longer receives focus 9899 * events from this component. 9900 * 9901 * @param l the focus listener 9902 */ 9903 public void removeFocusListener(FocusListener l) { 9904 Component.this.removeFocusListener(l); 9905 } 9906 9907 } // inner class AccessibleAWTComponent 9908 9909 9910 /** 9911 * Gets the index of this object in its accessible parent. 9912 * If this object does not have an accessible parent, returns 9913 * -1. 9914 * 9915 * @return the index of this object in its accessible parent 9916 */ 9917 int getAccessibleIndexInParent() { 9918 synchronized (getTreeLock()) { 9919 9920 AccessibleContext accContext = getAccessibleContext(); 9921 if (accContext == null) { 9922 return -1; 9923 } 9924 9925 Accessible parent = accContext.getAccessibleParent(); 9926 if (parent == null) { 9927 return -1; 9928 } 9929 9930 accContext = parent.getAccessibleContext(); 9931 for (int i = 0; i < accContext.getAccessibleChildrenCount(); i++) { 9932 if (this.equals(accContext.getAccessibleChild(i))) { 9933 return i; 9934 } 9935 } 9936 9937 return -1; 9938 } 9939 } 9940 9941 /** 9942 * Gets the current state set of this object. 9943 * 9944 * @return an instance of {@code AccessibleStateSet} 9945 * containing the current state set of the object 9946 * @see AccessibleState 9947 */ 9948 AccessibleStateSet getAccessibleStateSet() { 9949 synchronized (getTreeLock()) { 9950 AccessibleStateSet states = new AccessibleStateSet(); 9951 if (this.isEnabled()) { 9952 states.add(AccessibleState.ENABLED); 9953 } 9954 if (this.isFocusTraversable()) { 9955 states.add(AccessibleState.FOCUSABLE); 9956 } 9957 if (this.isVisible()) { 9958 states.add(AccessibleState.VISIBLE); 9959 } 9960 if (this.isShowing()) { 9961 states.add(AccessibleState.SHOWING); 9962 } 9963 if (this.isFocusOwner()) { 9964 states.add(AccessibleState.FOCUSED); 9965 } 9966 if (this instanceof Accessible) { 9967 AccessibleContext ac = ((Accessible) this).getAccessibleContext(); 9968 if (ac != null) { 9969 Accessible ap = ac.getAccessibleParent(); 9970 if (ap != null) { 9971 AccessibleContext pac = ap.getAccessibleContext(); 9972 if (pac != null) { 9973 AccessibleSelection as = pac.getAccessibleSelection(); 9974 if (as != null) { 9975 states.add(AccessibleState.SELECTABLE); 9976 int i = ac.getAccessibleIndexInParent(); 9977 if (i >= 0) { 9978 if (as.isAccessibleChildSelected(i)) { 9979 states.add(AccessibleState.SELECTED); 9980 } 9981 } 9982 } 9983 } 9984 } 9985 } 9986 } 9987 if (Component.isInstanceOf(this, "javax.swing.JComponent")) { 9988 if (((javax.swing.JComponent) this).isOpaque()) { 9989 states.add(AccessibleState.OPAQUE); 9990 } 9991 } 9992 return states; 9993 } 9994 } 9995 9996 /** 9997 * Checks that the given object is instance of the given class. 9998 * @param obj Object to be checked 9999 * @param className The name of the class. Must be fully-qualified class name. 10000 * @return true, if this object is instanceof given class, 10001 * false, otherwise, or if obj or className is null 10002 */ 10003 static boolean isInstanceOf(Object obj, String className) { 10004 if (obj == null) return false; 10005 if (className == null) return false; 10006 10007 Class<?> cls = obj.getClass(); 10008 while (cls != null) { 10009 if (cls.getName().equals(className)) { 10010 return true; 10011 } 10012 cls = cls.getSuperclass(); 10013 } 10014 return false; 10015 } 10016 10017 10018 // ************************** MIXING CODE ******************************* 10019 10020 /** 10021 * Check whether we can trust the current bounds of the component. 10022 * The return value of false indicates that the container of the 10023 * component is invalid, and therefore needs to be laid out, which would 10024 * probably mean changing the bounds of its children. 10025 * Null-layout of the container or absence of the container mean 10026 * the bounds of the component are final and can be trusted. 10027 */ 10028 final boolean areBoundsValid() { 10029 Container cont = getContainer(); 10030 return cont == null || cont.isValid() || cont.getLayout() == null; 10031 } 10032 10033 /** 10034 * Applies the shape to the component 10035 * @param shape Shape to be applied to the component 10036 */ 10037 void applyCompoundShape(Region shape) { 10038 checkTreeLock(); 10039 10040 if (!areBoundsValid()) { 10041 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10042 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10043 } 10044 return; 10045 } 10046 10047 if (!isLightweight()) { 10048 ComponentPeer peer = this.peer; 10049 if (peer != null) { 10050 // The Region class has some optimizations. That's why 10051 // we should manually check whether it's empty and 10052 // substitute the object ourselves. Otherwise we end up 10053 // with some incorrect Region object with loX being 10054 // greater than the hiX for instance. 10055 if (shape.isEmpty()) { 10056 shape = Region.EMPTY_REGION; 10057 } 10058 10059 10060 // Note: the shape is not really copied/cloned. We create 10061 // the Region object ourselves, so there's no any possibility 10062 // to modify the object outside of the mixing code. 10063 // Nullifying compoundShape means that the component has normal shape 10064 // (or has no shape at all). 10065 if (shape.equals(getNormalShape())) { 10066 if (this.compoundShape == null) { 10067 return; 10068 } 10069 this.compoundShape = null; 10070 peer.applyShape(null); 10071 } else { 10072 if (shape.equals(getAppliedShape())) { 10073 return; 10074 } 10075 this.compoundShape = shape; 10076 Point compAbsolute = getLocationOnWindow(); 10077 if (mixingLog.isLoggable(PlatformLogger.Level.FINER)) { 10078 mixingLog.fine("this = " + this + 10079 "; compAbsolute=" + compAbsolute + "; shape=" + shape); 10080 } 10081 peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y)); 10082 } 10083 } 10084 } 10085 } 10086 10087 /** 10088 * Returns the shape previously set with applyCompoundShape(). 10089 * If the component is LW or no shape was applied yet, 10090 * the method returns the normal shape. 10091 */ 10092 private Region getAppliedShape() { 10093 checkTreeLock(); 10094 //XXX: if we allow LW components to have a shape, this must be changed 10095 return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape; 10096 } 10097 10098 Point getLocationOnWindow() { 10099 checkTreeLock(); 10100 Point curLocation = getLocation(); 10101 10102 for (Container parent = getContainer(); 10103 parent != null && !(parent instanceof Window); 10104 parent = parent.getContainer()) 10105 { 10106 curLocation.x += parent.getX(); 10107 curLocation.y += parent.getY(); 10108 } 10109 10110 return curLocation; 10111 } 10112 10113 /** 10114 * Returns the full shape of the component located in window coordinates 10115 */ 10116 final Region getNormalShape() { 10117 checkTreeLock(); 10118 //XXX: we may take into account a user-specified shape for this component 10119 Point compAbsolute = getLocationOnWindow(); 10120 return 10121 Region.getInstanceXYWH( 10122 compAbsolute.x, 10123 compAbsolute.y, 10124 getWidth(), 10125 getHeight() 10126 ); 10127 } 10128 10129 /** 10130 * Returns the "opaque shape" of the component. 10131 * 10132 * The opaque shape of a lightweight components is the actual shape that 10133 * needs to be cut off of the heavyweight components in order to mix this 10134 * lightweight component correctly with them. 10135 * 10136 * The method is overriden in the java.awt.Container to handle non-opaque 10137 * containers containing opaque children. 10138 * 10139 * See 6637655 for details. 10140 */ 10141 Region getOpaqueShape() { 10142 checkTreeLock(); 10143 if (mixingCutoutRegion != null) { 10144 return mixingCutoutRegion; 10145 } else { 10146 return getNormalShape(); 10147 } 10148 } 10149 10150 final int getSiblingIndexAbove() { 10151 checkTreeLock(); 10152 Container parent = getContainer(); 10153 if (parent == null) { 10154 return -1; 10155 } 10156 10157 int nextAbove = parent.getComponentZOrder(this) - 1; 10158 10159 return nextAbove < 0 ? -1 : nextAbove; 10160 } 10161 10162 final ComponentPeer getHWPeerAboveMe() { 10163 checkTreeLock(); 10164 10165 Container cont = getContainer(); 10166 int indexAbove = getSiblingIndexAbove(); 10167 10168 while (cont != null) { 10169 for (int i = indexAbove; i > -1; i--) { 10170 Component comp = cont.getComponent(i); 10171 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) { 10172 return comp.peer; 10173 } 10174 } 10175 // traversing the hierarchy up to the closest HW container; 10176 // further traversing may return a component that is not actually 10177 // a native sibling of this component and this kind of z-order 10178 // request may not be allowed by the underlying system (6852051). 10179 if (!cont.isLightweight()) { 10180 break; 10181 } 10182 10183 indexAbove = cont.getSiblingIndexAbove(); 10184 cont = cont.getContainer(); 10185 } 10186 10187 return null; 10188 } 10189 10190 final int getSiblingIndexBelow() { 10191 checkTreeLock(); 10192 Container parent = getContainer(); 10193 if (parent == null) { 10194 return -1; 10195 } 10196 10197 int nextBelow = parent.getComponentZOrder(this) + 1; 10198 10199 return nextBelow >= parent.getComponentCount() ? -1 : nextBelow; 10200 } 10201 10202 final boolean isNonOpaqueForMixing() { 10203 return mixingCutoutRegion != null && 10204 mixingCutoutRegion.isEmpty(); 10205 } 10206 10207 private Region calculateCurrentShape() { 10208 checkTreeLock(); 10209 Region s = getNormalShape(); 10210 10211 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10212 mixingLog.fine("this = " + this + "; normalShape=" + s); 10213 } 10214 10215 if (getContainer() != null) { 10216 Component comp = this; 10217 Container cont = comp.getContainer(); 10218 10219 while (cont != null) { 10220 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) { 10221 /* It is assumed that: 10222 * 10223 * getComponent(getContainer().getComponentZOrder(comp)) == comp 10224 * 10225 * The assumption has been made according to the current 10226 * implementation of the Container class. 10227 */ 10228 Component c = cont.getComponent(index); 10229 if (c.isLightweight() && c.isShowing()) { 10230 s = s.getDifference(c.getOpaqueShape()); 10231 } 10232 } 10233 10234 if (cont.isLightweight()) { 10235 s = s.getIntersection(cont.getNormalShape()); 10236 } else { 10237 break; 10238 } 10239 10240 comp = cont; 10241 cont = cont.getContainer(); 10242 } 10243 } 10244 10245 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10246 mixingLog.fine("currentShape=" + s); 10247 } 10248 10249 return s; 10250 } 10251 10252 void applyCurrentShape() { 10253 checkTreeLock(); 10254 if (!areBoundsValid()) { 10255 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10256 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10257 } 10258 return; // Because applyCompoundShape() ignores such components anyway 10259 } 10260 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10261 mixingLog.fine("this = " + this); 10262 } 10263 applyCompoundShape(calculateCurrentShape()); 10264 } 10265 10266 final void subtractAndApplyShape(Region s) { 10267 checkTreeLock(); 10268 10269 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10270 mixingLog.fine("this = " + this + "; s=" + s); 10271 } 10272 10273 applyCompoundShape(getAppliedShape().getDifference(s)); 10274 } 10275 10276 private void applyCurrentShapeBelowMe() { 10277 checkTreeLock(); 10278 Container parent = getContainer(); 10279 if (parent != null && parent.isShowing()) { 10280 // First, reapply shapes of my siblings 10281 parent.recursiveApplyCurrentShape(getSiblingIndexBelow()); 10282 10283 // Second, if my container is non-opaque, reapply shapes of siblings of my container 10284 Container parent2 = parent.getContainer(); 10285 while (!parent.isOpaque() && parent2 != null) { 10286 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow()); 10287 10288 parent = parent2; 10289 parent2 = parent.getContainer(); 10290 } 10291 } 10292 } 10293 10294 final void subtractAndApplyShapeBelowMe() { 10295 checkTreeLock(); 10296 Container parent = getContainer(); 10297 if (parent != null && isShowing()) { 10298 Region opaqueShape = getOpaqueShape(); 10299 10300 // First, cut my siblings 10301 parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow()); 10302 10303 // Second, if my container is non-opaque, cut siblings of my container 10304 Container parent2 = parent.getContainer(); 10305 while (!parent.isOpaque() && parent2 != null) { 10306 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow()); 10307 10308 parent = parent2; 10309 parent2 = parent.getContainer(); 10310 } 10311 } 10312 } 10313 10314 void mixOnShowing() { 10315 synchronized (getTreeLock()) { 10316 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10317 mixingLog.fine("this = " + this); 10318 } 10319 if (!isMixingNeeded()) { 10320 return; 10321 } 10322 if (isLightweight()) { 10323 subtractAndApplyShapeBelowMe(); 10324 } else { 10325 applyCurrentShape(); 10326 } 10327 } 10328 } 10329 10330 void mixOnHiding(boolean isLightweight) { 10331 // We cannot be sure that the peer exists at this point, so we need the argument 10332 // to find out whether the hiding component is (well, actually was) a LW or a HW. 10333 synchronized (getTreeLock()) { 10334 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10335 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight); 10336 } 10337 if (!isMixingNeeded()) { 10338 return; 10339 } 10340 if (isLightweight) { 10341 applyCurrentShapeBelowMe(); 10342 } 10343 } 10344 } 10345 10346 void mixOnReshaping() { 10347 synchronized (getTreeLock()) { 10348 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10349 mixingLog.fine("this = " + this); 10350 } 10351 if (!isMixingNeeded()) { 10352 return; 10353 } 10354 if (isLightweight()) { 10355 applyCurrentShapeBelowMe(); 10356 } else { 10357 applyCurrentShape(); 10358 } 10359 } 10360 } 10361 10362 void mixOnZOrderChanging(int oldZorder, int newZorder) { 10363 synchronized (getTreeLock()) { 10364 boolean becameHigher = newZorder < oldZorder; 10365 Container parent = getContainer(); 10366 10367 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10368 mixingLog.fine("this = " + this + 10369 "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent); 10370 } 10371 if (!isMixingNeeded()) { 10372 return; 10373 } 10374 if (isLightweight()) { 10375 if (becameHigher) { 10376 if (parent != null && isShowing()) { 10377 parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder); 10378 } 10379 } else { 10380 if (parent != null) { 10381 parent.recursiveApplyCurrentShape(oldZorder, newZorder); 10382 } 10383 } 10384 } else { 10385 if (becameHigher) { 10386 applyCurrentShape(); 10387 } else { 10388 if (parent != null) { 10389 Region shape = getAppliedShape(); 10390 10391 for (int index = oldZorder; index < newZorder; index++) { 10392 Component c = parent.getComponent(index); 10393 if (c.isLightweight() && c.isShowing()) { 10394 shape = shape.getDifference(c.getOpaqueShape()); 10395 } 10396 } 10397 applyCompoundShape(shape); 10398 } 10399 } 10400 } 10401 } 10402 } 10403 10404 void mixOnValidating() { 10405 // This method gets overriden in the Container. Obviously, a plain 10406 // non-container components don't need to handle validation. 10407 } 10408 10409 final boolean isMixingNeeded() { 10410 if (SunToolkit.getSunAwtDisableMixing()) { 10411 if (mixingLog.isLoggable(PlatformLogger.Level.FINEST)) { 10412 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing"); 10413 } 10414 return false; 10415 } 10416 if (!areBoundsValid()) { 10417 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10418 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10419 } 10420 return false; 10421 } 10422 Window window = getContainingWindow(); 10423 if (window != null) { 10424 if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) { 10425 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10426 mixingLog.fine("containing window = " + window + 10427 "; has h/w descendants = " + window.hasHeavyweightDescendants() + 10428 "; has l/w descendants = " + window.hasLightweightDescendants() + 10429 "; disposing = " + window.isDisposing()); 10430 } 10431 return false; 10432 } 10433 } else { 10434 if (mixingLog.isLoggable(PlatformLogger.Level.FINE)) { 10435 mixingLog.fine("this = " + this + "; containing window is null"); 10436 } 10437 return false; 10438 } 10439 return true; 10440 } 10441 10442 /** 10443 * Sets a 'mixing-cutout' shape for this lightweight component. 10444 * 10445 * This method is used exclusively for the purposes of the 10446 * Heavyweight/Lightweight Components Mixing feature and will 10447 * have no effect if applied to a heavyweight component. 10448 * 10449 * By default a lightweight component is treated as an opaque rectangle for 10450 * the purposes of the Heavyweight/Lightweight Components Mixing feature. 10451 * This method enables developers to set an arbitrary shape to be cut out 10452 * from heavyweight components positioned underneath the lightweight 10453 * component in the z-order. 10454 * <p> 10455 * The {@code shape} argument may have the following values: 10456 * <ul> 10457 * <li>{@code null} - reverts the default cutout shape (the rectangle equal 10458 * to the component's {@code getBounds()}) 10459 * <li><i>empty-shape</i> - does not cut out anything from heavyweight 10460 * components. This makes this lightweight component effectively 10461 * transparent. Note that descendants of the lightweight component still 10462 * affect the shapes of heavyweight components. An example of an 10463 * <i>empty-shape</i> is {@code new Rectangle()}. 10464 * <li><i>non-empty-shape</i> - the given shape will be cut out from 10465 * heavyweight components. 10466 * </ul> 10467 * <p> 10468 * The most common example when the 'mixing-cutout' shape is needed is a 10469 * glass pane component. The {@link JRootPane#setGlassPane} method 10470 * automatically sets the <i>empty-shape</i> as the 'mixing-cutout' shape 10471 * for the given glass pane component. If a developer needs some other 10472 * 'mixing-cutout' shape for the glass pane (which is rare), this must be 10473 * changed manually after installing the glass pane to the root pane. 10474 * 10475 * @param shape the new 'mixing-cutout' shape 10476 * @since 9 10477 */ 10478 public void setMixingCutoutShape(Shape shape) { 10479 Region region = shape == null ? null : Region.getInstance(shape, null); 10480 10481 synchronized (getTreeLock()) { 10482 boolean needShowing = false; 10483 boolean needHiding = false; 10484 10485 if (!isNonOpaqueForMixing()) { 10486 needHiding = true; 10487 } 10488 10489 mixingCutoutRegion = region; 10490 10491 if (!isNonOpaqueForMixing()) { 10492 needShowing = true; 10493 } 10494 10495 if (isMixingNeeded()) { 10496 if (needHiding) { 10497 mixOnHiding(isLightweight()); 10498 } 10499 if (needShowing) { 10500 mixOnShowing(); 10501 } 10502 } 10503 } 10504 } 10505 10506 // ****************** END OF MIXING CODE ******************************** 10507 10508 // Note that the method is overriden in the Window class, 10509 // a window doesn't need to be updated in the Z-order. 10510 void updateZOrder() { 10511 peer.setZOrder(getHWPeerAboveMe()); 10512 } 10513 10514 }