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