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