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