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