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