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