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