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