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