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