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