1 /* 2 * Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.awt; 26 27 import java.io.PrintStream; 28 import java.io.PrintWriter; 29 import java.util.Vector; 30 import java.util.Locale; 31 import java.util.EventListener; 32 import java.util.Iterator; 33 import java.util.HashSet; 34 import java.util.Map; 35 import java.util.Set; 36 import java.util.Collections; 37 import java.awt.peer.ComponentPeer; 38 import java.awt.peer.ContainerPeer; 39 import java.awt.peer.LightweightPeer; 40 import java.awt.image.BufferStrategy; 41 import java.awt.image.ImageObserver; 42 import java.awt.image.ImageProducer; 43 import java.awt.image.ColorModel; 44 import java.awt.image.VolatileImage; 45 import java.awt.event.*; 46 import java.io.Serializable; 47 import java.io.ObjectOutputStream; 48 import java.io.ObjectInputStream; 49 import java.io.IOException; 50 import java.beans.PropertyChangeListener; 51 import java.beans.PropertyChangeSupport; 52 import java.beans.Transient; 53 import java.awt.event.InputMethodListener; 54 import java.awt.event.InputMethodEvent; 55 import java.awt.im.InputContext; 56 import java.awt.im.InputMethodRequests; 57 import java.awt.dnd.DropTarget; 58 import java.lang.reflect.InvocationTargetException; 59 import java.lang.reflect.Method; 60 import java.security.AccessController; 61 import java.security.PrivilegedAction; 62 import java.security.AccessControlContext; 63 import javax.accessibility.*; 64 import java.applet.Applet; 65 66 import sun.security.action.GetPropertyAction; 67 import sun.awt.AppContext; 68 import sun.awt.AWTAccessor; 69 import sun.awt.ConstrainableGraphics; 70 import sun.awt.SubRegionShowable; 71 import sun.awt.SunToolkit; 72 import sun.awt.WindowClosingListener; 73 import sun.awt.CausedFocusEvent; 74 import sun.awt.EmbeddedFrame; 75 import sun.awt.dnd.SunDropTargetEvent; 76 import sun.awt.im.CompositionArea; 77 import sun.font.FontManager; 78 import sun.font.FontManagerFactory; 79 import sun.font.SunFontManager; 80 import sun.java2d.SunGraphics2D; 81 import sun.java2d.pipe.Region; 82 import sun.awt.image.VSyncedBSManager; 83 import sun.java2d.pipe.hw.ExtendedBufferCapabilities; 84 import static sun.java2d.pipe.hw.ExtendedBufferCapabilities.VSyncType.*; 85 import sun.awt.RequestFocusController; 86 import sun.java2d.SunGraphicsEnvironment; 87 import sun.util.logging.PlatformLogger; 88 89 /** 90 * A <em>component</em> is an object having a graphical representation 91 * that can be displayed on the screen and that can interact with the 92 * user. Examples of components are the buttons, checkboxes, and scrollbars 93 * of a typical graphical user interface. <p> 94 * The <code>Component</code> class is the abstract superclass of 95 * the nonmenu-related Abstract Window Toolkit components. Class 96 * <code>Component</code> can also be extended directly to create a 97 * lightweight component. A lightweight component is a component that is 98 * not associated with a native window. On the contrary, a heavyweight 99 * component is associated with a native window. The {@link #isLightweight()} 100 * method may be used to distinguish between the two kinds of the components. 101 * <p> 102 * Lightweight and heavyweight components may be mixed in a single component 103 * hierarchy. However, for correct operating of such a mixed hierarchy of 104 * components, the whole hierarchy must be valid. When the hierarchy gets 105 * invalidated, like after changing the bounds of components, or 106 * adding/removing components to/from containers, the whole hierarchy must be 107 * validated afterwards by means of the {@link Container#validate()} method 108 * invoked on the top-most invalid container of the hierarchy. 109 * <p> 110 * <h3>Serialization</h3> 111 * It is important to note that only AWT listeners which conform 112 * to the <code>Serializable</code> protocol will be saved when 113 * the object is stored. If an AWT object has listeners that 114 * aren't marked serializable, they will be dropped at 115 * <code>writeObject</code> time. Developers will need, as always, 116 * to consider the implications of making an object serializable. 117 * One situation to watch out for is this: 118 * <pre> 119 * import java.awt.*; 120 * import java.awt.event.*; 121 * import java.io.Serializable; 122 * 123 * class MyApp implements ActionListener, Serializable 124 * { 125 * BigObjectThatShouldNotBeSerializedWithAButton bigOne; 126 * Button aButton = new Button(); 127 * 128 * MyApp() 129 * { 130 * // Oops, now aButton has a listener with a reference 131 * // to bigOne! 132 * aButton.addActionListener(this); 133 * } 134 * 135 * public void actionPerformed(ActionEvent e) 136 * { 137 * System.out.println("Hello There"); 138 * } 139 * } 140 * </pre> 141 * In this example, serializing <code>aButton</code> by itself 142 * will cause <code>MyApp</code> and everything it refers to 143 * to be serialized as well. The problem is that the listener 144 * is serializable by coincidence, not by design. To separate 145 * the decisions about <code>MyApp</code> and the 146 * <code>ActionListener</code> being serializable one can use a 147 * nested class, as in the following example: 148 * <pre> 149 * import java.awt.*; 150 * import java.awt.event.*; 151 * import java.io.Serializable; 152 * 153 * class MyApp implements java.io.Serializable 154 * { 155 * BigObjectThatShouldNotBeSerializedWithAButton bigOne; 156 * Button aButton = new Button(); 157 * 158 * static class MyActionListener implements ActionListener 159 * { 160 * public void actionPerformed(ActionEvent e) 161 * { 162 * System.out.println("Hello There"); 163 * } 164 * } 165 * 166 * MyApp() 167 * { 168 * aButton.addActionListener(new MyActionListener()); 169 * } 170 * } 171 * </pre> 172 * <p> 173 * <b>Note</b>: For more information on the paint mechanisms utilitized 174 * by AWT and Swing, including information on how to write the most 175 * efficient painting code, see 176 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 177 * <p> 178 * For details on the focus subsystem, see 179 * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html"> 180 * How to Use the Focus Subsystem</a>, 181 * a section in <em>The Java Tutorial</em>, and the 182 * <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 183 * for more information. 184 * 185 * @author Arthur van Hoff 186 * @author Sami Shaio 187 */ 188 public abstract class Component implements ImageObserver, MenuContainer, 189 Serializable 190 { 191 192 private static final PlatformLogger log = PlatformLogger.getLogger("java.awt.Component"); 193 private static final PlatformLogger eventLog = PlatformLogger.getLogger("java.awt.event.Component"); 194 private static final PlatformLogger focusLog = PlatformLogger.getLogger("java.awt.focus.Component"); 195 private static final PlatformLogger mixingLog = PlatformLogger.getLogger("java.awt.mixing.Component"); 196 197 /** 198 * The peer of the component. The peer implements the component's 199 * behavior. The peer is set when the <code>Component</code> is 200 * added to a container that also is a peer. 201 * @see #addNotify 202 * @see #removeNotify 203 */ 204 transient ComponentPeer peer; 205 206 /** 207 * The parent of the object. It may be <code>null</code> 208 * for top-level components. 209 * @see #getParent 210 */ 211 transient Container parent; 212 213 /** 214 * The <code>AppContext</code> of the component. Applets/Plugin may 215 * change the AppContext. 216 */ 217 transient AppContext appContext; 218 219 /** 220 * The x position of the component in the parent's coordinate system. 221 * 222 * @serial 223 * @see #getLocation 224 */ 225 int x; 226 227 /** 228 * The y position of the component in the parent's coordinate system. 229 * 230 * @serial 231 * @see #getLocation 232 */ 233 int y; 234 235 /** 236 * The width of the component. 237 * 238 * @serial 239 * @see #getSize 240 */ 241 int width; 242 243 /** 244 * The height of the component. 245 * 246 * @serial 247 * @see #getSize 248 */ 249 int height; 250 251 /** 252 * The foreground color for this component. 253 * <code>foreground</code> can be <code>null</code>. 254 * 255 * @serial 256 * @see #getForeground 257 * @see #setForeground 258 */ 259 Color foreground; 260 261 /** 262 * The background color for this component. 263 * <code>background</code> can be <code>null</code>. 264 * 265 * @serial 266 * @see #getBackground 267 * @see #setBackground 268 */ 269 Color background; 270 271 /** 272 * The font used by this component. 273 * The <code>font</code> can be <code>null</code>. 274 * 275 * @serial 276 * @see #getFont 277 * @see #setFont 278 */ 279 Font font; 280 281 /** 282 * The font which the peer is currently using. 283 * (<code>null</code> if no peer exists.) 284 */ 285 Font peerFont; 286 287 /** 288 * The cursor displayed when pointer is over this component. 289 * This value can be <code>null</code>. 290 * 291 * @serial 292 * @see #getCursor 293 * @see #setCursor 294 */ 295 Cursor cursor; 296 297 /** 298 * The locale for the component. 299 * 300 * @serial 301 * @see #getLocale 302 * @see #setLocale 303 */ 304 Locale locale; 305 306 /** 307 * A reference to a <code>GraphicsConfiguration</code> object 308 * used to describe the characteristics of a graphics 309 * destination. 310 * This value can be <code>null</code>. 311 * 312 * @since 1.3 313 * @serial 314 * @see GraphicsConfiguration 315 * @see #getGraphicsConfiguration 316 */ 317 private transient GraphicsConfiguration graphicsConfig = null; 318 319 /** 320 * A reference to a <code>BufferStrategy</code> object 321 * used to manipulate the buffers on this component. 322 * 323 * @since 1.4 324 * @see java.awt.image.BufferStrategy 325 * @see #getBufferStrategy() 326 */ 327 transient BufferStrategy bufferStrategy = null; 328 329 /** 330 * True when the object should ignore all repaint events. 331 * 332 * @since 1.4 333 * @serial 334 * @see #setIgnoreRepaint 335 * @see #getIgnoreRepaint 336 */ 337 boolean ignoreRepaint = false; 338 339 /** 340 * True when the object is visible. An object that is not 341 * visible is not drawn on the screen. 342 * 343 * @serial 344 * @see #isVisible 345 * @see #setVisible 346 */ 347 boolean visible = true; 348 349 /** 350 * True when the object is enabled. An object that is not 351 * enabled does not interact with the user. 352 * 353 * @serial 354 * @see #isEnabled 355 * @see #setEnabled 356 */ 357 boolean enabled = true; 358 359 /** 360 * True when the object is valid. An invalid object needs to 361 * be layed out. This flag is set to false when the object 362 * size is changed. 363 * 364 * @serial 365 * @see #isValid 366 * @see #validate 367 * @see #invalidate 368 */ 369 private volatile boolean valid = false; 370 371 /** 372 * The <code>DropTarget</code> associated with this component. 373 * 374 * @since 1.2 375 * @serial 376 * @see #setDropTarget 377 * @see #getDropTarget 378 */ 379 DropTarget dropTarget; 380 381 /** 382 * @serial 383 * @see #add 384 */ 385 Vector<PopupMenu> popups; 386 387 /** 388 * A component's name. 389 * This field can be <code>null</code>. 390 * 391 * @serial 392 * @see #getName 393 * @see #setName(String) 394 */ 395 private String name; 396 397 /** 398 * A bool to determine whether the name has 399 * been set explicitly. <code>nameExplicitlySet</code> will 400 * be false if the name has not been set and 401 * true if it has. 402 * 403 * @serial 404 * @see #getName 405 * @see #setName(String) 406 */ 407 private boolean nameExplicitlySet = false; 408 409 /** 410 * Indicates whether this Component can be focused. 411 * 412 * @serial 413 * @see #setFocusable 414 * @see #isFocusable 415 * @since 1.4 416 */ 417 private boolean focusable = true; 418 419 private static final int FOCUS_TRAVERSABLE_UNKNOWN = 0; 420 private static final int FOCUS_TRAVERSABLE_DEFAULT = 1; 421 private static final int FOCUS_TRAVERSABLE_SET = 2; 422 423 /** 424 * Tracks whether this Component is relying on default focus travesability. 425 * 426 * @serial 427 * @since 1.4 428 */ 429 private int isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; 430 431 /** 432 * The focus traversal keys. These keys will generate focus traversal 433 * behavior for Components for which focus traversal keys are enabled. If a 434 * value of null is specified for a traversal key, this Component inherits 435 * that traversal key from its parent. If all ancestors of this Component 436 * have null specified for that traversal key, then the current 437 * KeyboardFocusManager's default traversal key is used. 438 * 439 * @serial 440 * @see #setFocusTraversalKeys 441 * @see #getFocusTraversalKeys 442 * @since 1.4 443 */ 444 Set<AWTKeyStroke>[] focusTraversalKeys; 445 446 private static final String[] focusTraversalKeyPropertyNames = { 447 "forwardFocusTraversalKeys", 448 "backwardFocusTraversalKeys", 449 "upCycleFocusTraversalKeys", 450 "downCycleFocusTraversalKeys" 451 }; 452 453 /** 454 * Indicates whether focus traversal keys are enabled for this Component. 455 * Components for which focus traversal keys are disabled receive key 456 * events for focus traversal keys. Components for which focus traversal 457 * keys are enabled do not see these events; instead, the events are 458 * automatically converted to traversal operations. 459 * 460 * @serial 461 * @see #setFocusTraversalKeysEnabled 462 * @see #getFocusTraversalKeysEnabled 463 * @since 1.4 464 */ 465 private boolean focusTraversalKeysEnabled = true; 466 467 /** 468 * The locking object for AWT component-tree and layout operations. 469 * 470 * @see #getTreeLock 471 */ 472 static final Object LOCK = new AWTTreeLock(); 473 static class AWTTreeLock {} 474 475 /* 476 * The component's AccessControlContext. 477 */ 478 private transient volatile AccessControlContext acc = 479 AccessController.getContext(); 480 481 /** 482 * Minimum size. 483 * (This field perhaps should have been transient). 484 * 485 * @serial 486 */ 487 Dimension minSize; 488 489 /** 490 * Whether or not setMinimumSize has been invoked with a non-null value. 491 */ 492 boolean minSizeSet; 493 494 /** 495 * Preferred size. 496 * (This field perhaps should have been transient). 497 * 498 * @serial 499 */ 500 Dimension prefSize; 501 502 /** 503 * Whether or not setPreferredSize has been invoked with a non-null value. 504 */ 505 boolean prefSizeSet; 506 507 /** 508 * Maximum size 509 * 510 * @serial 511 */ 512 Dimension maxSize; 513 514 /** 515 * Whether or not setMaximumSize has been invoked with a non-null value. 516 */ 517 boolean maxSizeSet; 518 519 /** 520 * The orientation for this component. 521 * @see #getComponentOrientation 522 * @see #setComponentOrientation 523 */ 524 transient ComponentOrientation componentOrientation 525 = ComponentOrientation.UNKNOWN; 526 527 /** 528 * <code>newEventsOnly</code> will be true if the event is 529 * one of the event types enabled for the component. 530 * It will then allow for normal processing to 531 * continue. If it is false the event is passed 532 * to the component's parent and up the ancestor 533 * tree until the event has been consumed. 534 * 535 * @serial 536 * @see #dispatchEvent 537 */ 538 boolean newEventsOnly = false; 539 transient ComponentListener componentListener; 540 transient FocusListener focusListener; 541 transient HierarchyListener hierarchyListener; 542 transient HierarchyBoundsListener hierarchyBoundsListener; 543 transient KeyListener keyListener; 544 transient MouseListener mouseListener; 545 transient MouseMotionListener mouseMotionListener; 546 transient MouseWheelListener mouseWheelListener; 547 transient InputMethodListener inputMethodListener; 548 549 transient RuntimeException windowClosingException = null; 550 551 /** Internal, constants for serialization */ 552 final static String actionListenerK = "actionL"; 553 final static String adjustmentListenerK = "adjustmentL"; 554 final static String componentListenerK = "componentL"; 555 final static String containerListenerK = "containerL"; 556 final static String focusListenerK = "focusL"; 557 final static String itemListenerK = "itemL"; 558 final static String keyListenerK = "keyL"; 559 final static String mouseListenerK = "mouseL"; 560 final static String mouseMotionListenerK = "mouseMotionL"; 561 final static String mouseWheelListenerK = "mouseWheelL"; 562 final static String textListenerK = "textL"; 563 final static String ownedWindowK = "ownedL"; 564 final static String windowListenerK = "windowL"; 565 final static String inputMethodListenerK = "inputMethodL"; 566 final static String hierarchyListenerK = "hierarchyL"; 567 final static String hierarchyBoundsListenerK = "hierarchyBoundsL"; 568 final static String windowStateListenerK = "windowStateL"; 569 final static String windowFocusListenerK = "windowFocusL"; 570 571 /** 572 * The <code>eventMask</code> is ONLY set by subclasses via 573 * <code>enableEvents</code>. 574 * The mask should NOT be set when listeners are registered 575 * so that we can distinguish the difference between when 576 * listeners request events and subclasses request them. 577 * One bit is used to indicate whether input methods are 578 * enabled; this bit is set by <code>enableInputMethods</code> and is 579 * on by default. 580 * 581 * @serial 582 * @see #enableInputMethods 583 * @see AWTEvent 584 */ 585 long eventMask = AWTEvent.INPUT_METHODS_ENABLED_MASK; 586 587 /** 588 * Static properties for incremental drawing. 589 * @see #imageUpdate 590 */ 591 static boolean isInc; 592 static int incRate; 593 static { 594 /* ensure that the necessary native libraries are loaded */ 595 Toolkit.loadLibraries(); 596 /* initialize JNI field and method ids */ 597 if (!GraphicsEnvironment.isHeadless()) { 598 initIDs(); 599 } 600 601 String s = java.security.AccessController.doPrivileged( 602 new GetPropertyAction("awt.image.incrementaldraw")); 603 isInc = (s == null || s.equals("true")); 604 605 s = java.security.AccessController.doPrivileged( 606 new GetPropertyAction("awt.image.redrawrate")); 607 incRate = (s != null) ? Integer.parseInt(s) : 100; 608 } 609 610 /** 611 * Ease-of-use constant for <code>getAlignmentY()</code>. 612 * Specifies an alignment to the top of the component. 613 * @see #getAlignmentY 614 */ 615 public static final float TOP_ALIGNMENT = 0.0f; 616 617 /** 618 * Ease-of-use constant for <code>getAlignmentY</code> and 619 * <code>getAlignmentX</code>. Specifies an alignment to 620 * the center of the component 621 * @see #getAlignmentX 622 * @see #getAlignmentY 623 */ 624 public static final float CENTER_ALIGNMENT = 0.5f; 625 626 /** 627 * Ease-of-use constant for <code>getAlignmentY</code>. 628 * Specifies an alignment to the bottom of the component. 629 * @see #getAlignmentY 630 */ 631 public static final float BOTTOM_ALIGNMENT = 1.0f; 632 633 /** 634 * Ease-of-use constant for <code>getAlignmentX</code>. 635 * Specifies an alignment to the left side of the component. 636 * @see #getAlignmentX 637 */ 638 public static final float LEFT_ALIGNMENT = 0.0f; 639 640 /** 641 * Ease-of-use constant for <code>getAlignmentX</code>. 642 * Specifies an alignment to the right side of the component. 643 * @see #getAlignmentX 644 */ 645 public static final float RIGHT_ALIGNMENT = 1.0f; 646 647 /* 648 * JDK 1.1 serialVersionUID 649 */ 650 private static final long serialVersionUID = -7644114512714619750L; 651 652 /** 653 * If any <code>PropertyChangeListeners</code> have been registered, 654 * the <code>changeSupport</code> field describes them. 655 * 656 * @serial 657 * @since 1.2 658 * @see #addPropertyChangeListener 659 * @see #removePropertyChangeListener 660 * @see #firePropertyChange 661 */ 662 private PropertyChangeSupport changeSupport; 663 664 /* 665 * In some cases using "this" as an object to synchronize by 666 * can lead to a deadlock if client code also uses synchronization 667 * by a component object. For every such situation revealed we should 668 * consider possibility of replacing "this" with the package private 669 * objectLock object introduced below. So far there're 3 issues known: 670 * - CR 6708322 (the getName/setName methods); 671 * - CR 6608764 (the PropertyChangeListener machinery); 672 * - CR 7108598 (the Container.paint/KeyboardFocusManager.clearMostRecentFocusOwner methods). 673 * 674 * Note: this field is considered final, though readObject() prohibits 675 * initializing final fields. 676 */ 677 private transient Object objectLock = new Object(); 678 Object getObjectLock() { 679 return objectLock; 680 } 681 682 /* 683 * Returns the acc this component was constructed with. 684 */ 685 final AccessControlContext getAccessControlContext() { 686 if (acc == null) { 687 throw new SecurityException("Component is missing AccessControlContext"); 688 } 689 return acc; 690 } 691 692 boolean isPacked = false; 693 694 /** 695 * Pseudoparameter for direct Geometry API (setLocation, setBounds setSize 696 * to signal setBounds what's changing. Should be used under TreeLock. 697 * This is only needed due to the inability to change the cross-calling 698 * order of public and deprecated methods. 699 */ 700 private int boundsOp = ComponentPeer.DEFAULT_OPERATION; 701 702 /** 703 * Enumeration of the common ways the baseline of a component can 704 * change as the size changes. The baseline resize behavior is 705 * primarily for layout managers that need to know how the 706 * position of the baseline changes as the component size changes. 707 * In general the baseline resize behavior will be valid for sizes 708 * greater than or equal to the minimum size (the actual minimum 709 * size; not a developer specified minimum size). For sizes 710 * smaller than the minimum size the baseline may change in a way 711 * other than the baseline resize behavior indicates. Similarly, 712 * as the size approaches <code>Integer.MAX_VALUE</code> and/or 713 * <code>Short.MAX_VALUE</code> the baseline may change in a way 714 * other than the baseline resize behavior indicates. 715 * 716 * @see #getBaselineResizeBehavior 717 * @see #getBaseline(int,int) 718 * @since 1.6 719 */ 720 public enum BaselineResizeBehavior { 721 /** 722 * Indicates the baseline remains fixed relative to the 723 * y-origin. That is, <code>getBaseline</code> returns 724 * the same value regardless of the height or width. For example, a 725 * <code>JLabel</code> containing non-empty text with a 726 * vertical alignment of <code>TOP</code> should have a 727 * baseline type of <code>CONSTANT_ASCENT</code>. 728 */ 729 CONSTANT_ASCENT, 730 731 /** 732 * Indicates the baseline remains fixed relative to the height 733 * and does not change as the width is varied. That is, for 734 * any height H the difference between H and 735 * <code>getBaseline(w, H)</code> is the same. For example, a 736 * <code>JLabel</code> containing non-empty text with a 737 * vertical alignment of <code>BOTTOM</code> should have a 738 * baseline type of <code>CONSTANT_DESCENT</code>. 739 */ 740 CONSTANT_DESCENT, 741 742 /** 743 * Indicates the baseline remains a fixed distance from 744 * the center of the component. That is, for any height H the 745 * difference between <code>getBaseline(w, H)</code> and 746 * <code>H / 2</code> is the same (plus or minus one depending upon 747 * rounding error). 748 * <p> 749 * Because of possible rounding errors it is recommended 750 * you ask for the baseline with two consecutive heights and use 751 * the return value to determine if you need to pad calculations 752 * by 1. The following shows how to calculate the baseline for 753 * any height: 754 * <pre> 755 * Dimension preferredSize = component.getPreferredSize(); 756 * int baseline = getBaseline(preferredSize.width, 757 * preferredSize.height); 758 * int nextBaseline = getBaseline(preferredSize.width, 759 * preferredSize.height + 1); 760 * // Amount to add to height when calculating where baseline 761 * // lands for a particular height: 762 * int padding = 0; 763 * // Where the baseline is relative to the mid point 764 * int baselineOffset = baseline - height / 2; 765 * if (preferredSize.height % 2 == 0 && 766 * baseline != nextBaseline) { 767 * padding = 1; 768 * } 769 * else if (preferredSize.height % 2 == 1 && 770 * baseline == nextBaseline) { 771 * baselineOffset--; 772 * padding = 1; 773 * } 774 * // The following calculates where the baseline lands for 775 * // the height z: 776 * int calculatedBaseline = (z + padding) / 2 + baselineOffset; 777 * </pre> 778 */ 779 CENTER_OFFSET, 780 781 /** 782 * Indicates the baseline resize behavior can not be expressed using 783 * any of the other constants. This may also indicate the baseline 784 * varies with the width of the component. This is also returned 785 * by components that do not have a baseline. 786 */ 787 OTHER 788 } 789 790 /* 791 * The shape set with the applyCompoundShape() method. It uncludes the result 792 * of the HW/LW mixing related shape computation. It may also include 793 * the user-specified shape of the component. 794 * The 'null' value means the component has normal shape (or has no shape at all) 795 * and applyCompoundShape() will skip the following shape identical to normal. 796 */ 797 private transient Region compoundShape = null; 798 799 /* 800 * Represents the shape of this lightweight component to be cut out from 801 * heavyweight components should they intersect. Possible values: 802 * 1. null - consider the shape rectangular 803 * 2. EMPTY_REGION - nothing gets cut out (children still get cut out) 804 * 3. non-empty - this shape gets cut out. 805 */ 806 private transient Region mixingCutoutRegion = null; 807 808 /* 809 * Indicates whether addNotify() is complete 810 * (i.e. the peer is created). 811 */ 812 private transient boolean isAddNotifyComplete = false; 813 814 /** 815 * Should only be used in subclass getBounds to check that part of bounds 816 * is actualy changing 817 */ 818 int getBoundsOp() { 819 assert Thread.holdsLock(getTreeLock()); 820 return boundsOp; 821 } 822 823 void setBoundsOp(int op) { 824 assert Thread.holdsLock(getTreeLock()); 825 if (op == ComponentPeer.RESET_OPERATION) { 826 boundsOp = ComponentPeer.DEFAULT_OPERATION; 827 } else 828 if (boundsOp == ComponentPeer.DEFAULT_OPERATION) { 829 boundsOp = op; 830 } 831 } 832 833 // Whether this Component has had the background erase flag 834 // specified via SunToolkit.disableBackgroundErase(). This is 835 // needed in order to make this function work on X11 platforms, 836 // where currently there is no chance to interpose on the creation 837 // of the peer and therefore the call to XSetBackground. 838 transient boolean backgroundEraseDisabled; 839 840 static { 841 AWTAccessor.setComponentAccessor(new AWTAccessor.ComponentAccessor() { 842 public void setBackgroundEraseDisabled(Component comp, boolean disabled) { 843 comp.backgroundEraseDisabled = disabled; 844 } 845 public boolean getBackgroundEraseDisabled(Component comp) { 846 return comp.backgroundEraseDisabled; 847 } 848 public Rectangle getBounds(Component comp) { 849 return new Rectangle(comp.x, comp.y, comp.width, comp.height); 850 } 851 public void setMixingCutoutShape(Component comp, Shape shape) { 852 Region region = shape == null ? null : 853 Region.getInstance(shape, null); 854 855 synchronized (comp.getTreeLock()) { 856 boolean needShowing = false; 857 boolean needHiding = false; 858 859 if (!comp.isNonOpaqueForMixing()) { 860 needHiding = true; 861 } 862 863 comp.mixingCutoutRegion = region; 864 865 if (!comp.isNonOpaqueForMixing()) { 866 needShowing = true; 867 } 868 869 if (comp.isMixingNeeded()) { 870 if (needHiding) { 871 comp.mixOnHiding(comp.isLightweight()); 872 } 873 if (needShowing) { 874 comp.mixOnShowing(); 875 } 876 } 877 } 878 } 879 880 public void setGraphicsConfiguration(Component comp, 881 GraphicsConfiguration gc) 882 { 883 comp.setGraphicsConfiguration(gc); 884 } 885 public boolean requestFocus(Component comp, CausedFocusEvent.Cause cause) { 886 return comp.requestFocus(cause); 887 } 888 public boolean canBeFocusOwner(Component comp) { 889 return comp.canBeFocusOwner(); 890 } 891 892 public boolean isVisible(Component comp) { 893 return comp.isVisible_NoClientCode(); 894 } 895 public void setRequestFocusController 896 (RequestFocusController requestController) 897 { 898 Component.setRequestFocusController(requestController); 899 } 900 public AppContext getAppContext(Component comp) { 901 return comp.appContext; 902 } 903 public void setAppContext(Component comp, AppContext appContext) { 904 comp.appContext = appContext; 905 } 906 public Container getParent(Component comp) { 907 return comp.getParent_NoClientCode(); 908 } 909 public void setParent(Component comp, Container parent) { 910 comp.parent = parent; 911 } 912 public void setSize(Component comp, int width, int height) { 913 comp.width = width; 914 comp.height = height; 915 } 916 public Point getLocation(Component comp) { 917 return comp.location_NoClientCode(); 918 } 919 public void setLocation(Component comp, int x, int y) { 920 comp.x = x; 921 comp.y = y; 922 } 923 public boolean isEnabled(Component comp) { 924 return comp.isEnabledImpl(); 925 } 926 public boolean isDisplayable(Component comp) { 927 return comp.peer != null; 928 } 929 public Cursor getCursor(Component comp) { 930 return comp.getCursor_NoClientCode(); 931 } 932 public ComponentPeer getPeer(Component comp) { 933 return comp.peer; 934 } 935 public void setPeer(Component comp, ComponentPeer peer) { 936 comp.peer = peer; 937 } 938 public boolean isLightweight(Component comp) { 939 return (comp.peer instanceof LightweightPeer); 940 } 941 public boolean getIgnoreRepaint(Component comp) { 942 return comp.ignoreRepaint; 943 } 944 public int getWidth(Component comp) { 945 return comp.width; 946 } 947 public int getHeight(Component comp) { 948 return comp.height; 949 } 950 public int getX(Component comp) { 951 return comp.x; 952 } 953 public int getY(Component comp) { 954 return comp.y; 955 } 956 public Color getForeground(Component comp) { 957 return comp.foreground; 958 } 959 public Color getBackground(Component comp) { 960 return comp.background; 961 } 962 public void setBackground(Component comp, Color background) { 963 comp.background = background; 964 } 965 public Font getFont(Component comp) { 966 return comp.getFont_NoClientCode(); 967 } 968 public void processEvent(Component comp, AWTEvent e) { 969 comp.processEvent(e); 970 } 971 972 public AccessControlContext getAccessControlContext(Component comp) { 973 return comp.getAccessControlContext(); 974 } 975 }); 976 } 977 978 /** 979 * Constructs a new component. Class <code>Component</code> can be 980 * extended directly to create a lightweight component that does not 981 * utilize an opaque native window. A lightweight component must be 982 * hosted by a native container somewhere higher up in the component 983 * tree (for example, by a <code>Frame</code> object). 984 */ 985 protected Component() { 986 appContext = AppContext.getAppContext(); 987 } 988 989 @SuppressWarnings({"rawtypes", "unchecked"}) 990 void initializeFocusTraversalKeys() { 991 focusTraversalKeys = new Set[3]; 992 } 993 994 /** 995 * Constructs a name for this component. Called by <code>getName</code> 996 * when the name is <code>null</code>. 997 */ 998 String constructComponentName() { 999 return null; // For strict compliance with prior platform versions, a Component 1000 // that doesn't set its name should return null from 1001 // getName() 1002 } 1003 1004 /** 1005 * Gets the name of the component. 1006 * @return this component's name 1007 * @see #setName 1008 * @since JDK1.1 1009 */ 1010 public String getName() { 1011 if (name == null && !nameExplicitlySet) { 1012 synchronized(getObjectLock()) { 1013 if (name == null && !nameExplicitlySet) 1014 name = constructComponentName(); 1015 } 1016 } 1017 return name; 1018 } 1019 1020 /** 1021 * Sets the name of the component to the specified string. 1022 * @param name the string that is to be this 1023 * component's name 1024 * @see #getName 1025 * @since JDK1.1 1026 */ 1027 public void setName(String name) { 1028 String oldName; 1029 synchronized(getObjectLock()) { 1030 oldName = this.name; 1031 this.name = name; 1032 nameExplicitlySet = true; 1033 } 1034 firePropertyChange("name", oldName, name); 1035 } 1036 1037 /** 1038 * Gets the parent of this component. 1039 * @return the parent container of this component 1040 * @since JDK1.0 1041 */ 1042 public Container getParent() { 1043 return getParent_NoClientCode(); 1044 } 1045 1046 // NOTE: This method may be called by privileged threads. 1047 // This functionality is implemented in a package-private method 1048 // to insure that it cannot be overridden by client subclasses. 1049 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 1050 final Container getParent_NoClientCode() { 1051 return parent; 1052 } 1053 1054 // This method is overriden in the Window class to return null, 1055 // because the parent field of the Window object contains 1056 // the owner of the window, not its parent. 1057 Container getContainer() { 1058 return getParent(); 1059 } 1060 1061 /** 1062 * @deprecated As of JDK version 1.1, 1063 * programs should not directly manipulate peers; 1064 * replaced by <code>boolean isDisplayable()</code>. 1065 */ 1066 @Deprecated 1067 public ComponentPeer getPeer() { 1068 return peer; 1069 } 1070 1071 /** 1072 * Associate a <code>DropTarget</code> with this component. 1073 * The <code>Component</code> will receive drops only if it 1074 * is enabled. 1075 * 1076 * @see #isEnabled 1077 * @param dt The DropTarget 1078 */ 1079 1080 public synchronized void setDropTarget(DropTarget dt) { 1081 if (dt == dropTarget || (dropTarget != null && dropTarget.equals(dt))) 1082 return; 1083 1084 DropTarget old; 1085 1086 if ((old = dropTarget) != null) { 1087 if (peer != null) dropTarget.removeNotify(peer); 1088 1089 DropTarget t = dropTarget; 1090 1091 dropTarget = null; 1092 1093 try { 1094 t.setComponent(null); 1095 } catch (IllegalArgumentException iae) { 1096 // ignore it. 1097 } 1098 } 1099 1100 // if we have a new one, and we have a peer, add it! 1101 1102 if ((dropTarget = dt) != null) { 1103 try { 1104 dropTarget.setComponent(this); 1105 if (peer != null) dropTarget.addNotify(peer); 1106 } catch (IllegalArgumentException iae) { 1107 if (old != null) { 1108 try { 1109 old.setComponent(this); 1110 if (peer != null) dropTarget.addNotify(peer); 1111 } catch (IllegalArgumentException iae1) { 1112 // ignore it! 1113 } 1114 } 1115 } 1116 } 1117 } 1118 1119 /** 1120 * Gets the <code>DropTarget</code> associated with this 1121 * <code>Component</code>. 1122 */ 1123 1124 public synchronized DropTarget getDropTarget() { return dropTarget; } 1125 1126 /** 1127 * Gets the <code>GraphicsConfiguration</code> associated with this 1128 * <code>Component</code>. 1129 * If the <code>Component</code> has not been assigned a specific 1130 * <code>GraphicsConfiguration</code>, 1131 * the <code>GraphicsConfiguration</code> of the 1132 * <code>Component</code> object's top-level container is 1133 * returned. 1134 * If the <code>Component</code> has been created, but not yet added 1135 * to a <code>Container</code>, this method returns <code>null</code>. 1136 * 1137 * @return the <code>GraphicsConfiguration</code> used by this 1138 * <code>Component</code> or <code>null</code> 1139 * @since 1.3 1140 */ 1141 public GraphicsConfiguration getGraphicsConfiguration() { 1142 synchronized(getTreeLock()) { 1143 return getGraphicsConfiguration_NoClientCode(); 1144 } 1145 } 1146 1147 final GraphicsConfiguration getGraphicsConfiguration_NoClientCode() { 1148 return graphicsConfig; 1149 } 1150 1151 void setGraphicsConfiguration(GraphicsConfiguration gc) { 1152 synchronized(getTreeLock()) { 1153 if (updateGraphicsData(gc)) { 1154 removeNotify(); 1155 addNotify(); 1156 } 1157 } 1158 } 1159 1160 boolean updateGraphicsData(GraphicsConfiguration gc) { 1161 checkTreeLock(); 1162 1163 if (graphicsConfig == gc) { 1164 return false; 1165 } 1166 1167 graphicsConfig = gc; 1168 1169 ComponentPeer peer = getPeer(); 1170 if (peer != null) { 1171 return peer.updateGraphicsData(gc); 1172 } 1173 return false; 1174 } 1175 1176 /** 1177 * Checks that this component's <code>GraphicsDevice</code> 1178 * <code>idString</code> matches the string argument. 1179 */ 1180 void checkGD(String stringID) { 1181 if (graphicsConfig != null) { 1182 if (!graphicsConfig.getDevice().getIDstring().equals(stringID)) { 1183 throw new IllegalArgumentException( 1184 "adding a container to a container on a different GraphicsDevice"); 1185 } 1186 } 1187 } 1188 1189 /** 1190 * Gets this component's locking object (the object that owns the thread 1191 * synchronization monitor) for AWT component-tree and layout 1192 * operations. 1193 * @return this component's locking object 1194 */ 1195 public final Object getTreeLock() { 1196 return LOCK; 1197 } 1198 1199 final void checkTreeLock() { 1200 if (!Thread.holdsLock(getTreeLock())) { 1201 throw new IllegalStateException("This function should be called while holding treeLock"); 1202 } 1203 } 1204 1205 /** 1206 * Gets the toolkit of this component. Note that 1207 * the frame that contains a component controls which 1208 * toolkit is used by that component. Therefore if the component 1209 * is moved from one frame to another, the toolkit it uses may change. 1210 * @return the toolkit of this component 1211 * @since JDK1.0 1212 */ 1213 public Toolkit getToolkit() { 1214 return getToolkitImpl(); 1215 } 1216 1217 /* 1218 * This is called by the native code, so client code can't 1219 * be called on the toolkit thread. 1220 */ 1221 final Toolkit getToolkitImpl() { 1222 ComponentPeer peer = this.peer; 1223 if ((peer != null) && ! (peer instanceof LightweightPeer)){ 1224 return peer.getToolkit(); 1225 } 1226 Container parent = this.parent; 1227 if (parent != null) { 1228 return parent.getToolkitImpl(); 1229 } 1230 return Toolkit.getDefaultToolkit(); 1231 } 1232 1233 /** 1234 * Determines whether this component is valid. A component is valid 1235 * when it is correctly sized and positioned within its parent 1236 * container and all its children are also valid. 1237 * In order to account for peers' size requirements, components are invalidated 1238 * before they are first shown on the screen. By the time the parent container 1239 * is fully realized, all its components will be valid. 1240 * @return <code>true</code> if the component is valid, <code>false</code> 1241 * otherwise 1242 * @see #validate 1243 * @see #invalidate 1244 * @since JDK1.0 1245 */ 1246 public boolean isValid() { 1247 return (peer != null) && valid; 1248 } 1249 1250 /** 1251 * Determines whether this component is displayable. A component is 1252 * displayable when it is connected to a native screen resource. 1253 * <p> 1254 * A component is made displayable either when it is added to 1255 * a displayable containment hierarchy or when its containment 1256 * hierarchy is made displayable. 1257 * A containment hierarchy is made displayable when its ancestor 1258 * window is either packed or made visible. 1259 * <p> 1260 * A component is made undisplayable either when it is removed from 1261 * a displayable containment hierarchy or when its containment hierarchy 1262 * is made undisplayable. A containment hierarchy is made 1263 * undisplayable when its ancestor window is disposed. 1264 * 1265 * @return <code>true</code> if the component is displayable, 1266 * <code>false</code> otherwise 1267 * @see Container#add(Component) 1268 * @see Window#pack 1269 * @see Window#show 1270 * @see Container#remove(Component) 1271 * @see Window#dispose 1272 * @since 1.2 1273 */ 1274 public boolean isDisplayable() { 1275 return getPeer() != null; 1276 } 1277 1278 /** 1279 * Determines whether this component should be visible when its 1280 * parent is visible. Components are 1281 * initially visible, with the exception of top level components such 1282 * as <code>Frame</code> objects. 1283 * @return <code>true</code> if the component is visible, 1284 * <code>false</code> otherwise 1285 * @see #setVisible 1286 * @since JDK1.0 1287 */ 1288 @Transient 1289 public boolean isVisible() { 1290 return isVisible_NoClientCode(); 1291 } 1292 final boolean isVisible_NoClientCode() { 1293 return visible; 1294 } 1295 1296 /** 1297 * Determines whether this component will be displayed on the screen. 1298 * @return <code>true</code> if the component and all of its ancestors 1299 * until a toplevel window or null parent are visible, 1300 * <code>false</code> otherwise 1301 */ 1302 boolean isRecursivelyVisible() { 1303 return visible && (parent == null || parent.isRecursivelyVisible()); 1304 } 1305 1306 /** 1307 * Translates absolute coordinates into coordinates in the coordinate 1308 * space of this component. 1309 */ 1310 Point pointRelativeToComponent(Point absolute) { 1311 Point compCoords = getLocationOnScreen(); 1312 return new Point(absolute.x - compCoords.x, 1313 absolute.y - compCoords.y); 1314 } 1315 1316 /** 1317 * Assuming that mouse location is stored in PointerInfo passed 1318 * to this method, it finds a Component that is in the same 1319 * Window as this Component and is located under the mouse pointer. 1320 * If no such Component exists, null is returned. 1321 * NOTE: this method should be called under the protection of 1322 * tree lock, as it is done in Component.getMousePosition() and 1323 * Container.getMousePosition(boolean). 1324 */ 1325 Component findUnderMouseInWindow(PointerInfo pi) { 1326 if (!isShowing()) { 1327 return null; 1328 } 1329 Window win = getContainingWindow(); 1330 if (!Toolkit.getDefaultToolkit().getMouseInfoPeer().isWindowUnderMouse(win)) { 1331 return null; 1332 } 1333 final boolean INCLUDE_DISABLED = true; 1334 Point relativeToWindow = win.pointRelativeToComponent(pi.getLocation()); 1335 Component inTheSameWindow = win.findComponentAt(relativeToWindow.x, 1336 relativeToWindow.y, 1337 INCLUDE_DISABLED); 1338 return inTheSameWindow; 1339 } 1340 1341 /** 1342 * Returns the position of the mouse pointer in this <code>Component</code>'s 1343 * coordinate space if the <code>Component</code> is directly under the mouse 1344 * pointer, otherwise returns <code>null</code>. 1345 * If the <code>Component</code> is not showing on the screen, this method 1346 * returns <code>null</code> even if the mouse pointer is above the area 1347 * where the <code>Component</code> would be displayed. 1348 * If the <code>Component</code> is partially or fully obscured by other 1349 * <code>Component</code>s or native windows, this method returns a non-null 1350 * value only if the mouse pointer is located above the unobscured part of the 1351 * <code>Component</code>. 1352 * <p> 1353 * For <code>Container</code>s it returns a non-null value if the mouse is 1354 * above the <code>Container</code> itself or above any of its descendants. 1355 * Use {@link Container#getMousePosition(boolean)} if you need to exclude children. 1356 * <p> 1357 * Sometimes the exact mouse coordinates are not important, and the only thing 1358 * that matters is whether a specific <code>Component</code> is under the mouse 1359 * pointer. If the return value of this method is <code>null</code>, mouse 1360 * pointer is not directly above the <code>Component</code>. 1361 * 1362 * @exception HeadlessException if GraphicsEnvironment.isHeadless() returns true 1363 * @see #isShowing 1364 * @see Container#getMousePosition 1365 * @return mouse coordinates relative to this <code>Component</code>, or null 1366 * @since 1.5 1367 */ 1368 public Point getMousePosition() throws HeadlessException { 1369 if (GraphicsEnvironment.isHeadless()) { 1370 throw new HeadlessException(); 1371 } 1372 1373 PointerInfo pi = java.security.AccessController.doPrivileged( 1374 new java.security.PrivilegedAction<PointerInfo>() { 1375 public PointerInfo run() { 1376 return MouseInfo.getPointerInfo(); 1377 } 1378 } 1379 ); 1380 1381 synchronized (getTreeLock()) { 1382 Component inTheSameWindow = findUnderMouseInWindow(pi); 1383 if (!isSameOrAncestorOf(inTheSameWindow, true)) { 1384 return null; 1385 } 1386 return pointRelativeToComponent(pi.getLocation()); 1387 } 1388 } 1389 1390 /** 1391 * Overridden in Container. Must be called under TreeLock. 1392 */ 1393 boolean isSameOrAncestorOf(Component comp, boolean allowChildren) { 1394 return comp == this; 1395 } 1396 1397 /** 1398 * Determines whether this component is showing on screen. This means 1399 * that the component must be visible, and it must be in a container 1400 * that is visible and showing. 1401 * <p> 1402 * <strong>Note:</strong> sometimes there is no way to detect whether the 1403 * {@code Component} is actually visible to the user. This can happen when: 1404 * <ul> 1405 * <li>the component has been added to a visible {@code ScrollPane} but 1406 * the {@code Component} is not currently in the scroll pane's view port. 1407 * <li>the {@code Component} is obscured by another {@code Component} or 1408 * {@code Container}. 1409 * </ul> 1410 * @return <code>true</code> if the component is showing, 1411 * <code>false</code> otherwise 1412 * @see #setVisible 1413 * @since JDK1.0 1414 */ 1415 public boolean isShowing() { 1416 if (visible && (peer != null)) { 1417 Container parent = this.parent; 1418 return (parent == null) || parent.isShowing(); 1419 } 1420 return false; 1421 } 1422 1423 /** 1424 * Determines whether this component is enabled. An enabled component 1425 * can respond to user input and generate events. Components are 1426 * enabled initially by default. A component may be enabled or disabled by 1427 * calling its <code>setEnabled</code> method. 1428 * @return <code>true</code> if the component is enabled, 1429 * <code>false</code> otherwise 1430 * @see #setEnabled 1431 * @since JDK1.0 1432 */ 1433 public boolean isEnabled() { 1434 return isEnabledImpl(); 1435 } 1436 1437 /* 1438 * This is called by the native code, so client code can't 1439 * be called on the toolkit thread. 1440 */ 1441 final boolean isEnabledImpl() { 1442 return enabled; 1443 } 1444 1445 /** 1446 * Enables or disables this component, depending on the value of the 1447 * parameter <code>b</code>. An enabled component can respond to user 1448 * input and generate events. Components are enabled initially by default. 1449 * 1450 * <p>Note: Disabling a lightweight component does not prevent it from 1451 * receiving MouseEvents. 1452 * <p>Note: Disabling a heavyweight container prevents all components 1453 * in this container from receiving any input events. But disabling a 1454 * lightweight container affects only this container. 1455 * 1456 * @param b If <code>true</code>, this component is 1457 * enabled; otherwise this component is disabled 1458 * @see #isEnabled 1459 * @see #isLightweight 1460 * @since JDK1.1 1461 */ 1462 public void setEnabled(boolean b) { 1463 enable(b); 1464 } 1465 1466 /** 1467 * @deprecated As of JDK version 1.1, 1468 * replaced by <code>setEnabled(boolean)</code>. 1469 */ 1470 @Deprecated 1471 public void enable() { 1472 if (!enabled) { 1473 synchronized (getTreeLock()) { 1474 enabled = true; 1475 ComponentPeer peer = this.peer; 1476 if (peer != null) { 1477 peer.setEnabled(true); 1478 if (visible) { 1479 updateCursorImmediately(); 1480 } 1481 } 1482 } 1483 if (accessibleContext != null) { 1484 accessibleContext.firePropertyChange( 1485 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1486 null, AccessibleState.ENABLED); 1487 } 1488 } 1489 } 1490 1491 /** 1492 * @deprecated As of JDK version 1.1, 1493 * replaced by <code>setEnabled(boolean)</code>. 1494 */ 1495 @Deprecated 1496 public void enable(boolean b) { 1497 if (b) { 1498 enable(); 1499 } else { 1500 disable(); 1501 } 1502 } 1503 1504 /** 1505 * @deprecated As of JDK version 1.1, 1506 * replaced by <code>setEnabled(boolean)</code>. 1507 */ 1508 @Deprecated 1509 public void disable() { 1510 if (enabled) { 1511 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1512 synchronized (getTreeLock()) { 1513 enabled = false; 1514 // A disabled lw container is allowed to contain a focus owner. 1515 if ((isFocusOwner() || (containsFocus() && !isLightweight())) && 1516 KeyboardFocusManager.isAutoFocusTransferEnabled()) 1517 { 1518 // Don't clear the global focus owner. If transferFocus 1519 // fails, we want the focus to stay on the disabled 1520 // Component so that keyboard traversal, et. al. still 1521 // makes sense to the user. 1522 transferFocus(false); 1523 } 1524 ComponentPeer peer = this.peer; 1525 if (peer != null) { 1526 peer.setEnabled(false); 1527 if (visible) { 1528 updateCursorImmediately(); 1529 } 1530 } 1531 } 1532 if (accessibleContext != null) { 1533 accessibleContext.firePropertyChange( 1534 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 1535 null, AccessibleState.ENABLED); 1536 } 1537 } 1538 } 1539 1540 /** 1541 * Returns true if this component is painted to an offscreen image 1542 * ("buffer") that's copied to the screen later. Component 1543 * subclasses that support double buffering should override this 1544 * method to return true if double buffering is enabled. 1545 * 1546 * @return false by default 1547 */ 1548 public boolean isDoubleBuffered() { 1549 return false; 1550 } 1551 1552 /** 1553 * Enables or disables input method support for this component. If input 1554 * method support is enabled and the component also processes key events, 1555 * incoming events are offered to 1556 * the current input method and will only be processed by the component or 1557 * dispatched to its listeners if the input method does not consume them. 1558 * By default, input method support is enabled. 1559 * 1560 * @param enable true to enable, false to disable 1561 * @see #processKeyEvent 1562 * @since 1.2 1563 */ 1564 public void enableInputMethods(boolean enable) { 1565 if (enable) { 1566 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) 1567 return; 1568 1569 // If this component already has focus, then activate the 1570 // input method by dispatching a synthesized focus gained 1571 // event. 1572 if (isFocusOwner()) { 1573 InputContext inputContext = getInputContext(); 1574 if (inputContext != null) { 1575 FocusEvent focusGainedEvent = 1576 new FocusEvent(this, FocusEvent.FOCUS_GAINED); 1577 inputContext.dispatchEvent(focusGainedEvent); 1578 } 1579 } 1580 1581 eventMask |= AWTEvent.INPUT_METHODS_ENABLED_MASK; 1582 } else { 1583 if ((eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0) { 1584 InputContext inputContext = getInputContext(); 1585 if (inputContext != null) { 1586 inputContext.endComposition(); 1587 inputContext.removeNotify(this); 1588 } 1589 } 1590 eventMask &= ~AWTEvent.INPUT_METHODS_ENABLED_MASK; 1591 } 1592 } 1593 1594 /** 1595 * Shows or hides this component depending on the value of parameter 1596 * <code>b</code>. 1597 * <p> 1598 * This method changes layout-related information, and therefore, 1599 * invalidates the component hierarchy. 1600 * 1601 * @param b if <code>true</code>, shows this component; 1602 * otherwise, hides this component 1603 * @see #isVisible 1604 * @see #invalidate 1605 * @since JDK1.1 1606 */ 1607 public void setVisible(boolean b) { 1608 show(b); 1609 } 1610 1611 /** 1612 * @deprecated As of JDK version 1.1, 1613 * replaced by <code>setVisible(boolean)</code>. 1614 */ 1615 @Deprecated 1616 public void show() { 1617 if (!visible) { 1618 synchronized (getTreeLock()) { 1619 visible = true; 1620 mixOnShowing(); 1621 ComponentPeer peer = this.peer; 1622 if (peer != null) { 1623 peer.setVisible(true); 1624 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1625 this, parent, 1626 HierarchyEvent.SHOWING_CHANGED, 1627 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1628 if (peer instanceof LightweightPeer) { 1629 repaint(); 1630 } 1631 updateCursorImmediately(); 1632 } 1633 1634 if (componentListener != null || 1635 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1636 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1637 ComponentEvent e = new ComponentEvent(this, 1638 ComponentEvent.COMPONENT_SHOWN); 1639 Toolkit.getEventQueue().postEvent(e); 1640 } 1641 } 1642 Container parent = this.parent; 1643 if (parent != null) { 1644 parent.invalidate(); 1645 } 1646 } 1647 } 1648 1649 /** 1650 * @deprecated As of JDK version 1.1, 1651 * replaced by <code>setVisible(boolean)</code>. 1652 */ 1653 @Deprecated 1654 public void show(boolean b) { 1655 if (b) { 1656 show(); 1657 } else { 1658 hide(); 1659 } 1660 } 1661 1662 boolean containsFocus() { 1663 return isFocusOwner(); 1664 } 1665 1666 void clearMostRecentFocusOwnerOnHide() { 1667 KeyboardFocusManager.clearMostRecentFocusOwner(this); 1668 } 1669 1670 void clearCurrentFocusCycleRootOnHide() { 1671 /* do nothing */ 1672 } 1673 1674 /** 1675 * @deprecated As of JDK version 1.1, 1676 * replaced by <code>setVisible(boolean)</code>. 1677 */ 1678 @Deprecated 1679 public void hide() { 1680 isPacked = false; 1681 1682 if (visible) { 1683 clearCurrentFocusCycleRootOnHide(); 1684 clearMostRecentFocusOwnerOnHide(); 1685 synchronized (getTreeLock()) { 1686 visible = false; 1687 mixOnHiding(isLightweight()); 1688 if (containsFocus() && KeyboardFocusManager.isAutoFocusTransferEnabled()) { 1689 transferFocus(true); 1690 } 1691 ComponentPeer peer = this.peer; 1692 if (peer != null) { 1693 peer.setVisible(false); 1694 createHierarchyEvents(HierarchyEvent.HIERARCHY_CHANGED, 1695 this, parent, 1696 HierarchyEvent.SHOWING_CHANGED, 1697 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_EVENT_MASK)); 1698 if (peer instanceof LightweightPeer) { 1699 repaint(); 1700 } 1701 updateCursorImmediately(); 1702 } 1703 if (componentListener != null || 1704 (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 || 1705 Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) { 1706 ComponentEvent e = new ComponentEvent(this, 1707 ComponentEvent.COMPONENT_HIDDEN); 1708 Toolkit.getEventQueue().postEvent(e); 1709 } 1710 } 1711 Container parent = this.parent; 1712 if (parent != null) { 1713 parent.invalidate(); 1714 } 1715 } 1716 } 1717 1718 /** 1719 * Gets the foreground color of this component. 1720 * @return this component's foreground color; if this component does 1721 * not have a foreground color, the foreground color of its parent 1722 * is returned 1723 * @see #setForeground 1724 * @since JDK1.0 1725 * @beaninfo 1726 * bound: true 1727 */ 1728 @Transient 1729 public Color getForeground() { 1730 Color foreground = this.foreground; 1731 if (foreground != null) { 1732 return foreground; 1733 } 1734 Container parent = this.parent; 1735 return (parent != null) ? parent.getForeground() : null; 1736 } 1737 1738 /** 1739 * Sets the foreground color of this component. 1740 * @param c the color to become this component's 1741 * foreground color; if this parameter is <code>null</code> 1742 * then this component will inherit 1743 * the foreground color of its parent 1744 * @see #getForeground 1745 * @since JDK1.0 1746 */ 1747 public void setForeground(Color c) { 1748 Color oldColor = foreground; 1749 ComponentPeer peer = this.peer; 1750 foreground = c; 1751 if (peer != null) { 1752 c = getForeground(); 1753 if (c != null) { 1754 peer.setForeground(c); 1755 } 1756 } 1757 // This is a bound property, so report the change to 1758 // any registered listeners. (Cheap if there are none.) 1759 firePropertyChange("foreground", oldColor, c); 1760 } 1761 1762 /** 1763 * Returns whether the foreground color has been explicitly set for this 1764 * Component. If this method returns <code>false</code>, this Component is 1765 * inheriting its foreground color from an ancestor. 1766 * 1767 * @return <code>true</code> if the foreground color has been explicitly 1768 * set for this Component; <code>false</code> otherwise. 1769 * @since 1.4 1770 */ 1771 public boolean isForegroundSet() { 1772 return (foreground != null); 1773 } 1774 1775 /** 1776 * Gets the background color of this component. 1777 * @return this component's background color; if this component does 1778 * not have a background color, 1779 * the background color of its parent is returned 1780 * @see #setBackground 1781 * @since JDK1.0 1782 */ 1783 @Transient 1784 public Color getBackground() { 1785 Color background = this.background; 1786 if (background != null) { 1787 return background; 1788 } 1789 Container parent = this.parent; 1790 return (parent != null) ? parent.getBackground() : null; 1791 } 1792 1793 /** 1794 * Sets the background color of this component. 1795 * <p> 1796 * The background color affects each component differently and the 1797 * parts of the component that are affected by the background color 1798 * may differ between operating systems. 1799 * 1800 * @param c the color to become this component's color; 1801 * if this parameter is <code>null</code>, then this 1802 * component will inherit the background color of its parent 1803 * @see #getBackground 1804 * @since JDK1.0 1805 * @beaninfo 1806 * bound: true 1807 */ 1808 public void setBackground(Color c) { 1809 Color oldColor = background; 1810 ComponentPeer peer = this.peer; 1811 background = c; 1812 if (peer != null) { 1813 c = getBackground(); 1814 if (c != null) { 1815 peer.setBackground(c); 1816 } 1817 } 1818 // This is a bound property, so report the change to 1819 // any registered listeners. (Cheap if there are none.) 1820 firePropertyChange("background", oldColor, c); 1821 } 1822 1823 /** 1824 * Returns whether the background color has been explicitly set for this 1825 * Component. If this method returns <code>false</code>, this Component is 1826 * inheriting its background color from an ancestor. 1827 * 1828 * @return <code>true</code> if the background color has been explicitly 1829 * set for this Component; <code>false</code> otherwise. 1830 * @since 1.4 1831 */ 1832 public boolean isBackgroundSet() { 1833 return (background != null); 1834 } 1835 1836 /** 1837 * Gets the font of this component. 1838 * @return this component's font; if a font has not been set 1839 * for this component, the font of its parent is returned 1840 * @see #setFont 1841 * @since JDK1.0 1842 */ 1843 @Transient 1844 public Font getFont() { 1845 return getFont_NoClientCode(); 1846 } 1847 1848 // NOTE: This method may be called by privileged threads. 1849 // This functionality is implemented in a package-private method 1850 // to insure that it cannot be overridden by client subclasses. 1851 // DO NOT INVOKE CLIENT CODE ON THIS THREAD! 1852 final Font getFont_NoClientCode() { 1853 Font font = this.font; 1854 if (font != null) { 1855 return font; 1856 } 1857 Container parent = this.parent; 1858 return (parent != null) ? parent.getFont_NoClientCode() : null; 1859 } 1860 1861 /** 1862 * Sets the font of this component. 1863 * <p> 1864 * This method changes layout-related information, and therefore, 1865 * invalidates the component hierarchy. 1866 * 1867 * @param f the font to become this component's font; 1868 * if this parameter is <code>null</code> then this 1869 * component will inherit the font of its parent 1870 * @see #getFont 1871 * @see #invalidate 1872 * @since JDK1.0 1873 * @beaninfo 1874 * bound: true 1875 */ 1876 public void setFont(Font f) { 1877 Font oldFont, newFont; 1878 synchronized(getTreeLock()) { 1879 synchronized (this) { 1880 oldFont = font; 1881 newFont = font = f; 1882 } 1883 ComponentPeer peer = this.peer; 1884 if (peer != null) { 1885 f = getFont(); 1886 if (f != null) { 1887 peer.setFont(f); 1888 peerFont = f; 1889 } 1890 } 1891 } 1892 // This is a bound property, so report the change to 1893 // any registered listeners. (Cheap if there are none.) 1894 firePropertyChange("font", oldFont, newFont); 1895 1896 // This could change the preferred size of the Component. 1897 // Fix for 6213660. Should compare old and new fonts and do not 1898 // call invalidate() if they are equal. 1899 if (f != oldFont && (oldFont == null || 1900 !oldFont.equals(f))) { 1901 invalidateIfValid(); 1902 } 1903 } 1904 1905 /** 1906 * Returns whether the font has been explicitly set for this Component. If 1907 * this method returns <code>false</code>, this Component is inheriting its 1908 * font from an ancestor. 1909 * 1910 * @return <code>true</code> if the font has been explicitly set for this 1911 * Component; <code>false</code> otherwise. 1912 * @since 1.4 1913 */ 1914 public boolean isFontSet() { 1915 return (font != null); 1916 } 1917 1918 /** 1919 * Gets the locale of this component. 1920 * @return this component's locale; if this component does not 1921 * have a locale, the locale of its parent is returned 1922 * @see #setLocale 1923 * @exception IllegalComponentStateException if the <code>Component</code> 1924 * does not have its own locale and has not yet been added to 1925 * a containment hierarchy such that the locale can be determined 1926 * from the containing parent 1927 * @since JDK1.1 1928 */ 1929 public Locale getLocale() { 1930 Locale locale = this.locale; 1931 if (locale != null) { 1932 return locale; 1933 } 1934 Container parent = this.parent; 1935 1936 if (parent == null) { 1937 throw new IllegalComponentStateException("This component must have a parent in order to determine its locale"); 1938 } else { 1939 return parent.getLocale(); 1940 } 1941 } 1942 1943 /** 1944 * Sets the locale of this component. This is a bound property. 1945 * <p> 1946 * This method changes layout-related information, and therefore, 1947 * invalidates the component hierarchy. 1948 * 1949 * @param l the locale to become this component's locale 1950 * @see #getLocale 1951 * @see #invalidate 1952 * @since JDK1.1 1953 */ 1954 public void setLocale(Locale l) { 1955 Locale oldValue = locale; 1956 locale = l; 1957 1958 // This is a bound property, so report the change to 1959 // any registered listeners. (Cheap if there are none.) 1960 firePropertyChange("locale", oldValue, l); 1961 1962 // This could change the preferred size of the Component. 1963 invalidateIfValid(); 1964 } 1965 1966 /** 1967 * Gets the instance of <code>ColorModel</code> used to display 1968 * the component on the output device. 1969 * @return the color model used by this component 1970 * @see java.awt.image.ColorModel 1971 * @see java.awt.peer.ComponentPeer#getColorModel() 1972 * @see Toolkit#getColorModel() 1973 * @since JDK1.0 1974 */ 1975 public ColorModel getColorModel() { 1976 ComponentPeer peer = this.peer; 1977 if ((peer != null) && ! (peer instanceof LightweightPeer)) { 1978 return peer.getColorModel(); 1979 } else if (GraphicsEnvironment.isHeadless()) { 1980 return ColorModel.getRGBdefault(); 1981 } // else 1982 return getToolkit().getColorModel(); 1983 } 1984 1985 /** 1986 * Gets the location of this component in the form of a 1987 * point specifying the component's top-left corner. 1988 * The location will be relative to the parent's coordinate space. 1989 * <p> 1990 * Due to the asynchronous nature of native event handling, this 1991 * method can return outdated values (for instance, after several calls 1992 * of <code>setLocation()</code> in rapid succession). For this 1993 * reason, the recommended method of obtaining a component's position is 1994 * within <code>java.awt.event.ComponentListener.componentMoved()</code>, 1995 * which is called after the operating system has finished moving the 1996 * component. 1997 * </p> 1998 * @return an instance of <code>Point</code> representing 1999 * the top-left corner of the component's bounds in 2000 * the coordinate space of the component's parent 2001 * @see #setLocation 2002 * @see #getLocationOnScreen 2003 * @since JDK1.1 2004 */ 2005 public Point getLocation() { 2006 return location(); 2007 } 2008 2009 /** 2010 * Gets the location of this component in the form of a point 2011 * specifying the component's top-left corner in the screen's 2012 * coordinate space. 2013 * @return an instance of <code>Point</code> representing 2014 * the top-left corner of the component's bounds in the 2015 * coordinate space of the screen 2016 * @throws <code>IllegalComponentStateException</code> if the 2017 * component is not showing on the screen 2018 * @see #setLocation 2019 * @see #getLocation 2020 */ 2021 public Point getLocationOnScreen() { 2022 synchronized (getTreeLock()) { 2023 return getLocationOnScreen_NoTreeLock(); 2024 } 2025 } 2026 2027 /* 2028 * a package private version of getLocationOnScreen 2029 * used by GlobalCursormanager to update cursor 2030 */ 2031 final Point getLocationOnScreen_NoTreeLock() { 2032 2033 if (peer != null && isShowing()) { 2034 if (peer instanceof LightweightPeer) { 2035 // lightweight component location needs to be translated 2036 // relative to a native component. 2037 Container host = getNativeContainer(); 2038 Point pt = host.peer.getLocationOnScreen(); 2039 for(Component c = this; c != host; c = c.getParent()) { 2040 pt.x += c.x; 2041 pt.y += c.y; 2042 } 2043 return pt; 2044 } else { 2045 Point pt = peer.getLocationOnScreen(); 2046 return pt; 2047 } 2048 } else { 2049 throw new IllegalComponentStateException("component must be showing on the screen to determine its location"); 2050 } 2051 } 2052 2053 2054 /** 2055 * @deprecated As of JDK version 1.1, 2056 * replaced by <code>getLocation()</code>. 2057 */ 2058 @Deprecated 2059 public Point location() { 2060 return location_NoClientCode(); 2061 } 2062 2063 private Point location_NoClientCode() { 2064 return new Point(x, y); 2065 } 2066 2067 /** 2068 * Moves this component to a new location. The top-left corner of 2069 * the new location is specified by the <code>x</code> and <code>y</code> 2070 * parameters in the coordinate space of this component's parent. 2071 * <p> 2072 * This method changes layout-related information, and therefore, 2073 * invalidates the component hierarchy. 2074 * 2075 * @param x the <i>x</i>-coordinate of the new location's 2076 * top-left corner in the parent's coordinate space 2077 * @param y the <i>y</i>-coordinate of the new location's 2078 * top-left corner in the parent's coordinate space 2079 * @see #getLocation 2080 * @see #setBounds 2081 * @see #invalidate 2082 * @since JDK1.1 2083 */ 2084 public void setLocation(int x, int y) { 2085 move(x, y); 2086 } 2087 2088 /** 2089 * @deprecated As of JDK version 1.1, 2090 * replaced by <code>setLocation(int, int)</code>. 2091 */ 2092 @Deprecated 2093 public void move(int x, int y) { 2094 synchronized(getTreeLock()) { 2095 setBoundsOp(ComponentPeer.SET_LOCATION); 2096 setBounds(x, y, width, height); 2097 } 2098 } 2099 2100 /** 2101 * Moves this component to a new location. The top-left corner of 2102 * the new location is specified by point <code>p</code>. Point 2103 * <code>p</code> is given in the parent's coordinate space. 2104 * <p> 2105 * This method changes layout-related information, and therefore, 2106 * invalidates the component hierarchy. 2107 * 2108 * @param p the point defining the top-left corner 2109 * of the new location, given in the coordinate space of this 2110 * component's parent 2111 * @see #getLocation 2112 * @see #setBounds 2113 * @see #invalidate 2114 * @since JDK1.1 2115 */ 2116 public void setLocation(Point p) { 2117 setLocation(p.x, p.y); 2118 } 2119 2120 /** 2121 * Returns the size of this component in the form of a 2122 * <code>Dimension</code> object. The <code>height</code> 2123 * field of the <code>Dimension</code> object contains 2124 * this component's height, and the <code>width</code> 2125 * field of the <code>Dimension</code> object contains 2126 * this component's width. 2127 * @return a <code>Dimension</code> object that indicates the 2128 * size of this component 2129 * @see #setSize 2130 * @since JDK1.1 2131 */ 2132 public Dimension getSize() { 2133 return size(); 2134 } 2135 2136 /** 2137 * @deprecated As of JDK version 1.1, 2138 * replaced by <code>getSize()</code>. 2139 */ 2140 @Deprecated 2141 public Dimension size() { 2142 return new Dimension(width, height); 2143 } 2144 2145 /** 2146 * Resizes this component so that it has width <code>width</code> 2147 * and height <code>height</code>. 2148 * <p> 2149 * This method changes layout-related information, and therefore, 2150 * invalidates the component hierarchy. 2151 * 2152 * @param width the new width of this component in pixels 2153 * @param height the new height of this component in pixels 2154 * @see #getSize 2155 * @see #setBounds 2156 * @see #invalidate 2157 * @since JDK1.1 2158 */ 2159 public void setSize(int width, int height) { 2160 resize(width, height); 2161 } 2162 2163 /** 2164 * @deprecated As of JDK version 1.1, 2165 * replaced by <code>setSize(int, int)</code>. 2166 */ 2167 @Deprecated 2168 public void resize(int width, int height) { 2169 synchronized(getTreeLock()) { 2170 setBoundsOp(ComponentPeer.SET_SIZE); 2171 setBounds(x, y, width, height); 2172 } 2173 } 2174 2175 /** 2176 * Resizes this component so that it has width <code>d.width</code> 2177 * and height <code>d.height</code>. 2178 * <p> 2179 * This method changes layout-related information, and therefore, 2180 * invalidates the component hierarchy. 2181 * 2182 * @param d the dimension specifying the new size 2183 * of this component 2184 * @throws NullPointerException if {@code d} is {@code null} 2185 * @see #setSize 2186 * @see #setBounds 2187 * @see #invalidate 2188 * @since JDK1.1 2189 */ 2190 public void setSize(Dimension d) { 2191 resize(d); 2192 } 2193 2194 /** 2195 * @deprecated As of JDK version 1.1, 2196 * replaced by <code>setSize(Dimension)</code>. 2197 */ 2198 @Deprecated 2199 public void resize(Dimension d) { 2200 setSize(d.width, d.height); 2201 } 2202 2203 /** 2204 * Gets the bounds of this component in the form of a 2205 * <code>Rectangle</code> object. The bounds specify this 2206 * component's width, height, and location relative to 2207 * its parent. 2208 * @return a rectangle indicating this component's bounds 2209 * @see #setBounds 2210 * @see #getLocation 2211 * @see #getSize 2212 */ 2213 public Rectangle getBounds() { 2214 return bounds(); 2215 } 2216 2217 /** 2218 * @deprecated As of JDK version 1.1, 2219 * replaced by <code>getBounds()</code>. 2220 */ 2221 @Deprecated 2222 public Rectangle bounds() { 2223 return new Rectangle(x, y, width, height); 2224 } 2225 2226 /** 2227 * Moves and resizes this component. The new location of the top-left 2228 * corner is specified by <code>x</code> and <code>y</code>, and the 2229 * new size is specified by <code>width</code> and <code>height</code>. 2230 * <p> 2231 * This method changes layout-related information, and therefore, 2232 * invalidates the component hierarchy. 2233 * 2234 * @param x the new <i>x</i>-coordinate of this component 2235 * @param y the new <i>y</i>-coordinate of this component 2236 * @param width the new <code>width</code> of this component 2237 * @param height the new <code>height</code> of this 2238 * component 2239 * @see #getBounds 2240 * @see #setLocation(int, int) 2241 * @see #setLocation(Point) 2242 * @see #setSize(int, int) 2243 * @see #setSize(Dimension) 2244 * @see #invalidate 2245 * @since JDK1.1 2246 */ 2247 public void setBounds(int x, int y, int width, int height) { 2248 reshape(x, y, width, height); 2249 } 2250 2251 /** 2252 * @deprecated As of JDK version 1.1, 2253 * replaced by <code>setBounds(int, int, int, int)</code>. 2254 */ 2255 @Deprecated 2256 public void reshape(int x, int y, int width, int height) { 2257 synchronized (getTreeLock()) { 2258 try { 2259 setBoundsOp(ComponentPeer.SET_BOUNDS); 2260 boolean resized = (this.width != width) || (this.height != height); 2261 boolean moved = (this.x != x) || (this.y != y); 2262 if (!resized && !moved) { 2263 return; 2264 } 2265 int oldX = this.x; 2266 int oldY = this.y; 2267 int oldWidth = this.width; 2268 int oldHeight = this.height; 2269 this.x = x; 2270 this.y = y; 2271 this.width = width; 2272 this.height = height; 2273 2274 if (resized) { 2275 isPacked = false; 2276 } 2277 2278 boolean needNotify = true; 2279 mixOnReshaping(); 2280 if (peer != null) { 2281 // LightwightPeer is an empty stub so can skip peer.reshape 2282 if (!(peer instanceof LightweightPeer)) { 2283 reshapeNativePeer(x, y, width, height, getBoundsOp()); 2284 // Check peer actualy changed coordinates 2285 resized = (oldWidth != this.width) || (oldHeight != this.height); 2286 moved = (oldX != this.x) || (oldY != this.y); 2287 // fix for 5025858: do not send ComponentEvents for toplevel 2288 // windows here as it is done from peer or native code when 2289 // the window is really resized or moved, otherwise some 2290 // events may be sent twice 2291 if (this instanceof Window) { 2292 needNotify = false; 2293 } 2294 } 2295 if (resized) { 2296 invalidate(); 2297 } 2298 if (parent != null) { 2299 parent.invalidateIfValid(); 2300 } 2301 } 2302 if (needNotify) { 2303 notifyNewBounds(resized, moved); 2304 } 2305 repaintParentIfNeeded(oldX, oldY, oldWidth, oldHeight); 2306 } finally { 2307 setBoundsOp(ComponentPeer.RESET_OPERATION); 2308 } 2309 } 2310 } 2311 2312 private void repaintParentIfNeeded(int oldX, int oldY, int oldWidth, 2313 int oldHeight) 2314 { 2315 if (parent != null && peer instanceof LightweightPeer && isShowing()) { 2316 // Have the parent redraw the area this component occupied. 2317 parent.repaint(oldX, oldY, oldWidth, oldHeight); 2318 // Have the parent redraw the area this component *now* occupies. 2319 repaint(); 2320 } 2321 } 2322 2323 private void reshapeNativePeer(int x, int y, int width, int height, int op) { 2324 // native peer might be offset by more than direct 2325 // parent since parent might be lightweight. 2326 int nativeX = x; 2327 int nativeY = y; 2328 for (Component c = parent; 2329 (c != null) && (c.peer instanceof LightweightPeer); 2330 c = c.parent) 2331 { 2332 nativeX += c.x; 2333 nativeY += c.y; 2334 } 2335 peer.setBounds(nativeX, nativeY, width, height, op); 2336 } 2337 2338 @SuppressWarnings("deprecation") 2339 private void notifyNewBounds(boolean resized, boolean moved) { 2340 if (componentListener != null 2341 || (eventMask & AWTEvent.COMPONENT_EVENT_MASK) != 0 2342 || Toolkit.enabledOnToolkit(AWTEvent.COMPONENT_EVENT_MASK)) 2343 { 2344 if (resized) { 2345 ComponentEvent e = new ComponentEvent(this, 2346 ComponentEvent.COMPONENT_RESIZED); 2347 Toolkit.getEventQueue().postEvent(e); 2348 } 2349 if (moved) { 2350 ComponentEvent e = new ComponentEvent(this, 2351 ComponentEvent.COMPONENT_MOVED); 2352 Toolkit.getEventQueue().postEvent(e); 2353 } 2354 } else { 2355 if (this instanceof Container && ((Container)this).countComponents() > 0) { 2356 boolean enabledOnToolkit = 2357 Toolkit.enabledOnToolkit(AWTEvent.HIERARCHY_BOUNDS_EVENT_MASK); 2358 if (resized) { 2359 2360 ((Container)this).createChildHierarchyEvents( 2361 HierarchyEvent.ANCESTOR_RESIZED, 0, enabledOnToolkit); 2362 } 2363 if (moved) { 2364 ((Container)this).createChildHierarchyEvents( 2365 HierarchyEvent.ANCESTOR_MOVED, 0, enabledOnToolkit); 2366 } 2367 } 2368 } 2369 } 2370 2371 /** 2372 * Moves and resizes this component to conform to the new 2373 * bounding rectangle <code>r</code>. This component's new 2374 * position is specified by <code>r.x</code> and <code>r.y</code>, 2375 * and its new size is specified by <code>r.width</code> and 2376 * <code>r.height</code> 2377 * <p> 2378 * This method changes layout-related information, and therefore, 2379 * invalidates the component hierarchy. 2380 * 2381 * @param r the new bounding rectangle for this component 2382 * @throws NullPointerException if {@code r} is {@code null} 2383 * @see #getBounds 2384 * @see #setLocation(int, int) 2385 * @see #setLocation(Point) 2386 * @see #setSize(int, int) 2387 * @see #setSize(Dimension) 2388 * @see #invalidate 2389 * @since JDK1.1 2390 */ 2391 public void setBounds(Rectangle r) { 2392 setBounds(r.x, r.y, r.width, r.height); 2393 } 2394 2395 2396 /** 2397 * Returns the current x coordinate of the components origin. 2398 * This method is preferable to writing 2399 * <code>component.getBounds().x</code>, 2400 * or <code>component.getLocation().x</code> because it doesn't 2401 * cause any heap allocations. 2402 * 2403 * @return the current x coordinate of the components origin 2404 * @since 1.2 2405 */ 2406 public int getX() { 2407 return x; 2408 } 2409 2410 2411 /** 2412 * Returns the current y coordinate of the components origin. 2413 * This method is preferable to writing 2414 * <code>component.getBounds().y</code>, 2415 * or <code>component.getLocation().y</code> because it 2416 * doesn't cause any heap allocations. 2417 * 2418 * @return the current y coordinate of the components origin 2419 * @since 1.2 2420 */ 2421 public int getY() { 2422 return y; 2423 } 2424 2425 2426 /** 2427 * Returns the current width of this component. 2428 * This method is preferable to writing 2429 * <code>component.getBounds().width</code>, 2430 * or <code>component.getSize().width</code> because it 2431 * doesn't cause any heap allocations. 2432 * 2433 * @return the current width of this component 2434 * @since 1.2 2435 */ 2436 public int getWidth() { 2437 return width; 2438 } 2439 2440 2441 /** 2442 * Returns the current height of this component. 2443 * This method is preferable to writing 2444 * <code>component.getBounds().height</code>, 2445 * or <code>component.getSize().height</code> because it 2446 * doesn't cause any heap allocations. 2447 * 2448 * @return the current height of this component 2449 * @since 1.2 2450 */ 2451 public int getHeight() { 2452 return height; 2453 } 2454 2455 /** 2456 * Stores the bounds of this component into "return value" <b>rv</b> and 2457 * return <b>rv</b>. If rv is <code>null</code> a new 2458 * <code>Rectangle</code> is allocated. 2459 * This version of <code>getBounds</code> is useful if the caller 2460 * wants to avoid allocating a new <code>Rectangle</code> object 2461 * on the heap. 2462 * 2463 * @param rv the return value, modified to the components bounds 2464 * @return rv 2465 */ 2466 public Rectangle getBounds(Rectangle rv) { 2467 if (rv == null) { 2468 return new Rectangle(getX(), getY(), getWidth(), getHeight()); 2469 } 2470 else { 2471 rv.setBounds(getX(), getY(), getWidth(), getHeight()); 2472 return rv; 2473 } 2474 } 2475 2476 /** 2477 * Stores the width/height of this component into "return value" <b>rv</b> 2478 * and return <b>rv</b>. If rv is <code>null</code> a new 2479 * <code>Dimension</code> object is allocated. This version of 2480 * <code>getSize</code> is useful if the caller wants to avoid 2481 * allocating a new <code>Dimension</code> object on the heap. 2482 * 2483 * @param rv the return value, modified to the components size 2484 * @return rv 2485 */ 2486 public Dimension getSize(Dimension rv) { 2487 if (rv == null) { 2488 return new Dimension(getWidth(), getHeight()); 2489 } 2490 else { 2491 rv.setSize(getWidth(), getHeight()); 2492 return rv; 2493 } 2494 } 2495 2496 /** 2497 * Stores the x,y origin of this component into "return value" <b>rv</b> 2498 * and return <b>rv</b>. If rv is <code>null</code> a new 2499 * <code>Point</code> is allocated. 2500 * This version of <code>getLocation</code> is useful if the 2501 * caller wants to avoid allocating a new <code>Point</code> 2502 * object on the heap. 2503 * 2504 * @param rv the return value, modified to the components location 2505 * @return rv 2506 */ 2507 public Point getLocation(Point rv) { 2508 if (rv == null) { 2509 return new Point(getX(), getY()); 2510 } 2511 else { 2512 rv.setLocation(getX(), getY()); 2513 return rv; 2514 } 2515 } 2516 2517 /** 2518 * Returns true if this component is completely opaque, returns 2519 * false by default. 2520 * <p> 2521 * An opaque component paints every pixel within its 2522 * rectangular region. A non-opaque component paints only some of 2523 * its pixels, allowing the pixels underneath it to "show through". 2524 * A component that does not fully paint its pixels therefore 2525 * provides a degree of transparency. 2526 * <p> 2527 * Subclasses that guarantee to always completely paint their 2528 * contents should override this method and return true. 2529 * 2530 * @return true if this component is completely opaque 2531 * @see #isLightweight 2532 * @since 1.2 2533 */ 2534 public boolean isOpaque() { 2535 if (getPeer() == null) { 2536 return false; 2537 } 2538 else { 2539 return !isLightweight(); 2540 } 2541 } 2542 2543 2544 /** 2545 * A lightweight component doesn't have a native toolkit peer. 2546 * Subclasses of <code>Component</code> and <code>Container</code>, 2547 * other than the ones defined in this package like <code>Button</code> 2548 * or <code>Scrollbar</code>, are lightweight. 2549 * All of the Swing components are lightweights. 2550 * <p> 2551 * This method will always return <code>false</code> if this component 2552 * is not displayable because it is impossible to determine the 2553 * weight of an undisplayable component. 2554 * 2555 * @return true if this component has a lightweight peer; false if 2556 * it has a native peer or no peer 2557 * @see #isDisplayable 2558 * @since 1.2 2559 */ 2560 public boolean isLightweight() { 2561 return getPeer() instanceof LightweightPeer; 2562 } 2563 2564 2565 /** 2566 * Sets the preferred size of this component to a constant 2567 * value. Subsequent calls to <code>getPreferredSize</code> will always 2568 * return this value. Setting the preferred size to <code>null</code> 2569 * restores the default behavior. 2570 * 2571 * @param preferredSize The new preferred size, or null 2572 * @see #getPreferredSize 2573 * @see #isPreferredSizeSet 2574 * @since 1.5 2575 */ 2576 public void setPreferredSize(Dimension preferredSize) { 2577 Dimension old; 2578 // If the preferred size was set, use it as the old value, otherwise 2579 // use null to indicate we didn't previously have a set preferred 2580 // size. 2581 if (prefSizeSet) { 2582 old = this.prefSize; 2583 } 2584 else { 2585 old = null; 2586 } 2587 this.prefSize = preferredSize; 2588 prefSizeSet = (preferredSize != null); 2589 firePropertyChange("preferredSize", old, preferredSize); 2590 } 2591 2592 2593 /** 2594 * Returns true if the preferred size has been set to a 2595 * non-<code>null</code> value otherwise returns false. 2596 * 2597 * @return true if <code>setPreferredSize</code> has been invoked 2598 * with a non-null value. 2599 * @since 1.5 2600 */ 2601 public boolean isPreferredSizeSet() { 2602 return prefSizeSet; 2603 } 2604 2605 2606 /** 2607 * Gets the preferred size of this component. 2608 * @return a dimension object indicating this component's preferred size 2609 * @see #getMinimumSize 2610 * @see LayoutManager 2611 */ 2612 public Dimension getPreferredSize() { 2613 return preferredSize(); 2614 } 2615 2616 2617 /** 2618 * @deprecated As of JDK version 1.1, 2619 * replaced by <code>getPreferredSize()</code>. 2620 */ 2621 @Deprecated 2622 public Dimension preferredSize() { 2623 /* Avoid grabbing the lock if a reasonable cached size value 2624 * is available. 2625 */ 2626 Dimension dim = prefSize; 2627 if (dim == null || !(isPreferredSizeSet() || isValid())) { 2628 synchronized (getTreeLock()) { 2629 prefSize = (peer != null) ? 2630 peer.getPreferredSize() : 2631 getMinimumSize(); 2632 dim = prefSize; 2633 } 2634 } 2635 return new Dimension(dim); 2636 } 2637 2638 /** 2639 * Sets the minimum size of this component to a constant 2640 * value. Subsequent calls to <code>getMinimumSize</code> will always 2641 * return this value. Setting the minimum size to <code>null</code> 2642 * restores the default behavior. 2643 * 2644 * @param minimumSize the new minimum size of this component 2645 * @see #getMinimumSize 2646 * @see #isMinimumSizeSet 2647 * @since 1.5 2648 */ 2649 public void setMinimumSize(Dimension minimumSize) { 2650 Dimension old; 2651 // If the minimum size was set, use it as the old value, otherwise 2652 // use null to indicate we didn't previously have a set minimum 2653 // size. 2654 if (minSizeSet) { 2655 old = this.minSize; 2656 } 2657 else { 2658 old = null; 2659 } 2660 this.minSize = minimumSize; 2661 minSizeSet = (minimumSize != null); 2662 firePropertyChange("minimumSize", old, minimumSize); 2663 } 2664 2665 /** 2666 * Returns whether or not <code>setMinimumSize</code> has been 2667 * invoked with a non-null value. 2668 * 2669 * @return true if <code>setMinimumSize</code> has been invoked with a 2670 * non-null value. 2671 * @since 1.5 2672 */ 2673 public boolean isMinimumSizeSet() { 2674 return minSizeSet; 2675 } 2676 2677 /** 2678 * Gets the mininimum size of this component. 2679 * @return a dimension object indicating this component's minimum size 2680 * @see #getPreferredSize 2681 * @see LayoutManager 2682 */ 2683 public Dimension getMinimumSize() { 2684 return minimumSize(); 2685 } 2686 2687 /** 2688 * @deprecated As of JDK version 1.1, 2689 * replaced by <code>getMinimumSize()</code>. 2690 */ 2691 @Deprecated 2692 public Dimension minimumSize() { 2693 /* Avoid grabbing the lock if a reasonable cached size value 2694 * is available. 2695 */ 2696 Dimension dim = minSize; 2697 if (dim == null || !(isMinimumSizeSet() || isValid())) { 2698 synchronized (getTreeLock()) { 2699 minSize = (peer != null) ? 2700 peer.getMinimumSize() : 2701 size(); 2702 dim = minSize; 2703 } 2704 } 2705 return new Dimension(dim); 2706 } 2707 2708 /** 2709 * Sets the maximum size of this component to a constant 2710 * value. Subsequent calls to <code>getMaximumSize</code> will always 2711 * return this value. Setting the maximum size to <code>null</code> 2712 * restores the default behavior. 2713 * 2714 * @param maximumSize a <code>Dimension</code> containing the 2715 * desired maximum allowable size 2716 * @see #getMaximumSize 2717 * @see #isMaximumSizeSet 2718 * @since 1.5 2719 */ 2720 public void setMaximumSize(Dimension maximumSize) { 2721 // If the maximum size was set, use it as the old value, otherwise 2722 // use null to indicate we didn't previously have a set maximum 2723 // size. 2724 Dimension old; 2725 if (maxSizeSet) { 2726 old = this.maxSize; 2727 } 2728 else { 2729 old = null; 2730 } 2731 this.maxSize = maximumSize; 2732 maxSizeSet = (maximumSize != null); 2733 firePropertyChange("maximumSize", old, maximumSize); 2734 } 2735 2736 /** 2737 * Returns true if the maximum size has been set to a non-<code>null</code> 2738 * value otherwise returns false. 2739 * 2740 * @return true if <code>maximumSize</code> is non-<code>null</code>, 2741 * false otherwise 2742 * @since 1.5 2743 */ 2744 public boolean isMaximumSizeSet() { 2745 return maxSizeSet; 2746 } 2747 2748 /** 2749 * Gets the maximum size of this component. 2750 * @return a dimension object indicating this component's maximum size 2751 * @see #getMinimumSize 2752 * @see #getPreferredSize 2753 * @see LayoutManager 2754 */ 2755 public Dimension getMaximumSize() { 2756 if (isMaximumSizeSet()) { 2757 return new Dimension(maxSize); 2758 } 2759 return new Dimension(Short.MAX_VALUE, Short.MAX_VALUE); 2760 } 2761 2762 /** 2763 * Returns the alignment along the x axis. This specifies how 2764 * the component would like to be aligned relative to other 2765 * components. The value should be a number between 0 and 1 2766 * where 0 represents alignment along the origin, 1 is aligned 2767 * the furthest away from the origin, 0.5 is centered, etc. 2768 */ 2769 public float getAlignmentX() { 2770 return CENTER_ALIGNMENT; 2771 } 2772 2773 /** 2774 * Returns the alignment along the y axis. This specifies how 2775 * the component would like to be aligned relative to other 2776 * components. The value should be a number between 0 and 1 2777 * where 0 represents alignment along the origin, 1 is aligned 2778 * the furthest away from the origin, 0.5 is centered, etc. 2779 */ 2780 public float getAlignmentY() { 2781 return CENTER_ALIGNMENT; 2782 } 2783 2784 /** 2785 * Returns the baseline. The baseline is measured from the top of 2786 * the component. This method is primarily meant for 2787 * <code>LayoutManager</code>s to align components along their 2788 * baseline. A return value less than 0 indicates this component 2789 * does not have a reasonable baseline and that 2790 * <code>LayoutManager</code>s should not align this component on 2791 * its baseline. 2792 * <p> 2793 * The default implementation returns -1. Subclasses that support 2794 * baseline should override appropriately. If a value >= 0 is 2795 * returned, then the component has a valid baseline for any 2796 * size >= the minimum size and <code>getBaselineResizeBehavior</code> 2797 * can be used to determine how the baseline changes with size. 2798 * 2799 * @param width the width to get the baseline for 2800 * @param height the height to get the baseline for 2801 * @return the baseline or < 0 indicating there is no reasonable 2802 * baseline 2803 * @throws IllegalArgumentException if width or height is < 0 2804 * @see #getBaselineResizeBehavior 2805 * @see java.awt.FontMetrics 2806 * @since 1.6 2807 */ 2808 public int getBaseline(int width, int height) { 2809 if (width < 0 || height < 0) { 2810 throw new IllegalArgumentException( 2811 "Width and height must be >= 0"); 2812 } 2813 return -1; 2814 } 2815 2816 /** 2817 * Returns an enum indicating how the baseline of the component 2818 * changes as the size changes. This method is primarily meant for 2819 * layout managers and GUI builders. 2820 * <p> 2821 * The default implementation returns 2822 * <code>BaselineResizeBehavior.OTHER</code>. Subclasses that have a 2823 * baseline should override appropriately. Subclasses should 2824 * never return <code>null</code>; if the baseline can not be 2825 * calculated return <code>BaselineResizeBehavior.OTHER</code>. Callers 2826 * should first ask for the baseline using 2827 * <code>getBaseline</code> and if a value >= 0 is returned use 2828 * this method. It is acceptable for this method to return a 2829 * value other than <code>BaselineResizeBehavior.OTHER</code> even if 2830 * <code>getBaseline</code> returns a value less than 0. 2831 * 2832 * @return an enum indicating how the baseline changes as the component 2833 * size changes 2834 * @see #getBaseline(int, int) 2835 * @since 1.6 2836 */ 2837 public BaselineResizeBehavior getBaselineResizeBehavior() { 2838 return BaselineResizeBehavior.OTHER; 2839 } 2840 2841 /** 2842 * Prompts the layout manager to lay out this component. This is 2843 * usually called when the component (more specifically, container) 2844 * is validated. 2845 * @see #validate 2846 * @see LayoutManager 2847 */ 2848 public void doLayout() { 2849 layout(); 2850 } 2851 2852 /** 2853 * @deprecated As of JDK version 1.1, 2854 * replaced by <code>doLayout()</code>. 2855 */ 2856 @Deprecated 2857 public void layout() { 2858 } 2859 2860 /** 2861 * Validates this component. 2862 * <p> 2863 * The meaning of the term <i>validating</i> is defined by the ancestors of 2864 * this class. See {@link Container#validate} for more details. 2865 * 2866 * @see #invalidate 2867 * @see #doLayout() 2868 * @see LayoutManager 2869 * @see Container#validate 2870 * @since JDK1.0 2871 */ 2872 public void validate() { 2873 synchronized (getTreeLock()) { 2874 ComponentPeer peer = this.peer; 2875 boolean wasValid = isValid(); 2876 if (!wasValid && peer != null) { 2877 Font newfont = getFont(); 2878 Font oldfont = peerFont; 2879 if (newfont != oldfont && (oldfont == null 2880 || !oldfont.equals(newfont))) { 2881 peer.setFont(newfont); 2882 peerFont = newfont; 2883 } 2884 peer.layout(); 2885 } 2886 valid = true; 2887 if (!wasValid) { 2888 mixOnValidating(); 2889 } 2890 } 2891 } 2892 2893 /** 2894 * Invalidates this component and its ancestors. 2895 * <p> 2896 * By default, all the ancestors of the component up to the top-most 2897 * container of the hierarchy are marked invalid. If the {@code 2898 * java.awt.smartInvalidate} system property is set to {@code true}, 2899 * invalidation stops on the nearest validate root of this component. 2900 * Marking a container <i>invalid</i> indicates that the container needs to 2901 * be laid out. 2902 * <p> 2903 * This method is called automatically when any layout-related information 2904 * changes (e.g. setting the bounds of the component, or adding the 2905 * component to a container). 2906 * <p> 2907 * This method might be called often, so it should work fast. 2908 * 2909 * @see #validate 2910 * @see #doLayout 2911 * @see LayoutManager 2912 * @see java.awt.Container#isValidateRoot 2913 * @since JDK1.0 2914 */ 2915 public void invalidate() { 2916 synchronized (getTreeLock()) { 2917 /* Nullify cached layout and size information. 2918 * For efficiency, propagate invalidate() upwards only if 2919 * some other component hasn't already done so first. 2920 */ 2921 valid = false; 2922 if (!isPreferredSizeSet()) { 2923 prefSize = null; 2924 } 2925 if (!isMinimumSizeSet()) { 2926 minSize = null; 2927 } 2928 if (!isMaximumSizeSet()) { 2929 maxSize = null; 2930 } 2931 invalidateParent(); 2932 } 2933 } 2934 2935 /** 2936 * Invalidates the parent of this component if any. 2937 * 2938 * This method MUST BE invoked under the TreeLock. 2939 */ 2940 void invalidateParent() { 2941 if (parent != null) { 2942 parent.invalidateIfValid(); 2943 } 2944 } 2945 2946 /** Invalidates the component unless it is already invalid. 2947 */ 2948 final void invalidateIfValid() { 2949 if (isValid()) { 2950 invalidate(); 2951 } 2952 } 2953 2954 /** 2955 * Revalidates the component hierarchy up to the nearest validate root. 2956 * <p> 2957 * This method first invalidates the component hierarchy starting from this 2958 * component up to the nearest validate root. Afterwards, the component 2959 * hierarchy is validated starting from the nearest validate root. 2960 * <p> 2961 * This is a convenience method supposed to help application developers 2962 * avoid looking for validate roots manually. Basically, it's equivalent to 2963 * first calling the {@link #invalidate()} method on this component, and 2964 * then calling the {@link #validate()} method on the nearest validate 2965 * root. 2966 * 2967 * @see Container#isValidateRoot 2968 * @since 1.7 2969 */ 2970 public void revalidate() { 2971 synchronized (getTreeLock()) { 2972 invalidate(); 2973 2974 Container root = getContainer(); 2975 if (root == null) { 2976 // There's no parents. Just validate itself. 2977 validate(); 2978 } else { 2979 while (!root.isValidateRoot()) { 2980 if (root.getContainer() == null) { 2981 // If there's no validate roots, we'll validate the 2982 // topmost container 2983 break; 2984 } 2985 2986 root = root.getContainer(); 2987 } 2988 2989 root.validate(); 2990 } 2991 } 2992 } 2993 2994 /** 2995 * Creates a graphics context for this component. This method will 2996 * return <code>null</code> if this component is currently not 2997 * displayable. 2998 * @return a graphics context for this component, or <code>null</code> 2999 * if it has none 3000 * @see #paint 3001 * @since JDK1.0 3002 */ 3003 public Graphics getGraphics() { 3004 if (peer instanceof LightweightPeer) { 3005 // This is for a lightweight component, need to 3006 // translate coordinate spaces and clip relative 3007 // to the parent. 3008 if (parent == null) return null; 3009 Graphics g = parent.getGraphics(); 3010 if (g == null) return null; 3011 if (g instanceof ConstrainableGraphics) { 3012 ((ConstrainableGraphics) g).constrain(x, y, width, height); 3013 } else { 3014 g.translate(x,y); 3015 g.setClip(0, 0, width, height); 3016 } 3017 g.setFont(getFont()); 3018 return g; 3019 } else { 3020 ComponentPeer peer = this.peer; 3021 return (peer != null) ? peer.getGraphics() : null; 3022 } 3023 } 3024 3025 final Graphics getGraphics_NoClientCode() { 3026 ComponentPeer peer = this.peer; 3027 if (peer instanceof LightweightPeer) { 3028 // This is for a lightweight component, need to 3029 // translate coordinate spaces and clip relative 3030 // to the parent. 3031 Container parent = this.parent; 3032 if (parent == null) return null; 3033 Graphics g = parent.getGraphics_NoClientCode(); 3034 if (g == null) return null; 3035 if (g instanceof ConstrainableGraphics) { 3036 ((ConstrainableGraphics) g).constrain(x, y, width, height); 3037 } else { 3038 g.translate(x,y); 3039 g.setClip(0, 0, width, height); 3040 } 3041 g.setFont(getFont_NoClientCode()); 3042 return g; 3043 } else { 3044 return (peer != null) ? peer.getGraphics() : null; 3045 } 3046 } 3047 3048 /** 3049 * Gets the font metrics for the specified font. 3050 * Warning: Since Font metrics are affected by the 3051 * {@link java.awt.font.FontRenderContext FontRenderContext} and 3052 * this method does not provide one, it can return only metrics for 3053 * the default render context which may not match that used when 3054 * rendering on the Component if {@link Graphics2D} functionality is being 3055 * used. Instead metrics can be obtained at rendering time by calling 3056 * {@link Graphics#getFontMetrics()} or text measurement APIs on the 3057 * {@link Font Font} class. 3058 * @param font the font for which font metrics is to be 3059 * obtained 3060 * @return the font metrics for <code>font</code> 3061 * @see #getFont 3062 * @see #getPeer 3063 * @see java.awt.peer.ComponentPeer#getFontMetrics(Font) 3064 * @see Toolkit#getFontMetrics(Font) 3065 * @since JDK1.0 3066 */ 3067 public FontMetrics getFontMetrics(Font font) { 3068 // This is an unsupported hack, but left in for a customer. 3069 // Do not remove. 3070 FontManager fm = FontManagerFactory.getInstance(); 3071 if (fm instanceof SunFontManager 3072 && ((SunFontManager) fm).usePlatformFontMetrics()) { 3073 3074 if (peer != null && 3075 !(peer instanceof LightweightPeer)) { 3076 return peer.getFontMetrics(font); 3077 } 3078 } 3079 return sun.font.FontDesignMetrics.getMetrics(font); 3080 } 3081 3082 /** 3083 * Sets the cursor image to the specified cursor. This cursor 3084 * image is displayed when the <code>contains</code> method for 3085 * this component returns true for the current cursor location, and 3086 * this Component is visible, displayable, and enabled. Setting the 3087 * cursor of a <code>Container</code> causes that cursor to be displayed 3088 * within all of the container's subcomponents, except for those 3089 * that have a non-<code>null</code> cursor. 3090 * <p> 3091 * The method may have no visual effect if the Java platform 3092 * implementation and/or the native system do not support 3093 * changing the mouse cursor shape. 3094 * @param cursor One of the constants defined 3095 * by the <code>Cursor</code> class; 3096 * if this parameter is <code>null</code> 3097 * then this component will inherit 3098 * the cursor of its parent 3099 * @see #isEnabled 3100 * @see #isShowing 3101 * @see #getCursor 3102 * @see #contains 3103 * @see Toolkit#createCustomCursor 3104 * @see Cursor 3105 * @since JDK1.1 3106 */ 3107 public void setCursor(Cursor cursor) { 3108 this.cursor = cursor; 3109 updateCursorImmediately(); 3110 } 3111 3112 /** 3113 * Updates the cursor. May not be invoked from the native 3114 * message pump. 3115 */ 3116 final void updateCursorImmediately() { 3117 if (peer instanceof LightweightPeer) { 3118 Container nativeContainer = getNativeContainer(); 3119 3120 if (nativeContainer == null) return; 3121 3122 ComponentPeer cPeer = nativeContainer.getPeer(); 3123 3124 if (cPeer != null) { 3125 cPeer.updateCursorImmediately(); 3126 } 3127 } else if (peer != null) { 3128 peer.updateCursorImmediately(); 3129 } 3130 } 3131 3132 /** 3133 * Gets the cursor set in the component. If the component does 3134 * not have a cursor set, the cursor of its parent is returned. 3135 * If no cursor is set in the entire hierarchy, 3136 * <code>Cursor.DEFAULT_CURSOR</code> is returned. 3137 * @see #setCursor 3138 * @since JDK1.1 3139 */ 3140 public Cursor getCursor() { 3141 return getCursor_NoClientCode(); 3142 } 3143 3144 final Cursor getCursor_NoClientCode() { 3145 Cursor cursor = this.cursor; 3146 if (cursor != null) { 3147 return cursor; 3148 } 3149 Container parent = this.parent; 3150 if (parent != null) { 3151 return parent.getCursor_NoClientCode(); 3152 } else { 3153 return Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR); 3154 } 3155 } 3156 3157 /** 3158 * Returns whether the cursor has been explicitly set for this Component. 3159 * If this method returns <code>false</code>, this Component is inheriting 3160 * its cursor from an ancestor. 3161 * 3162 * @return <code>true</code> if the cursor has been explicitly set for this 3163 * Component; <code>false</code> otherwise. 3164 * @since 1.4 3165 */ 3166 public boolean isCursorSet() { 3167 return (cursor != null); 3168 } 3169 3170 /** 3171 * Paints this component. 3172 * <p> 3173 * This method is called when the contents of the component should 3174 * be painted; such as when the component is first being shown or 3175 * is damaged and in need of repair. The clip rectangle in the 3176 * <code>Graphics</code> parameter is set to the area 3177 * which needs to be painted. 3178 * Subclasses of <code>Component</code> that override this 3179 * method need not call <code>super.paint(g)</code>. 3180 * <p> 3181 * For performance reasons, <code>Component</code>s with zero width 3182 * or height aren't considered to need painting when they are first shown, 3183 * and also aren't considered to need repair. 3184 * <p> 3185 * <b>Note</b>: For more information on the paint mechanisms utilitized 3186 * by AWT and Swing, including information on how to write the most 3187 * efficient painting code, see 3188 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3189 * 3190 * @param g the graphics context to use for painting 3191 * @see #update 3192 * @since JDK1.0 3193 */ 3194 public void paint(Graphics g) { 3195 } 3196 3197 /** 3198 * Updates this component. 3199 * <p> 3200 * If this component is not a lightweight component, the 3201 * AWT calls the <code>update</code> method in response to 3202 * a call to <code>repaint</code>. You can assume that 3203 * the background is not cleared. 3204 * <p> 3205 * The <code>update</code> method of <code>Component</code> 3206 * calls this component's <code>paint</code> method to redraw 3207 * this component. This method is commonly overridden by subclasses 3208 * which need to do additional work in response to a call to 3209 * <code>repaint</code>. 3210 * Subclasses of Component that override this method should either 3211 * call <code>super.update(g)</code>, or call <code>paint(g)</code> 3212 * directly from their <code>update</code> method. 3213 * <p> 3214 * The origin of the graphics context, its 3215 * (<code>0</code>, <code>0</code>) coordinate point, is the 3216 * top-left corner of this component. The clipping region of the 3217 * graphics context is the bounding rectangle of this component. 3218 * 3219 * <p> 3220 * <b>Note</b>: For more information on the paint mechanisms utilitized 3221 * by AWT and Swing, including information on how to write the most 3222 * efficient painting code, see 3223 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3224 * 3225 * @param g the specified context to use for updating 3226 * @see #paint 3227 * @see #repaint() 3228 * @since JDK1.0 3229 */ 3230 public void update(Graphics g) { 3231 paint(g); 3232 } 3233 3234 /** 3235 * Paints this component and all of its subcomponents. 3236 * <p> 3237 * The origin of the graphics context, its 3238 * (<code>0</code>, <code>0</code>) coordinate point, is the 3239 * top-left corner of this component. The clipping region of the 3240 * graphics context is the bounding rectangle of this component. 3241 * 3242 * @param g the graphics context to use for painting 3243 * @see #paint 3244 * @since JDK1.0 3245 */ 3246 public void paintAll(Graphics g) { 3247 if (isShowing()) { 3248 GraphicsCallback.PeerPaintCallback.getInstance(). 3249 runOneComponent(this, new Rectangle(0, 0, width, height), 3250 g, g.getClip(), 3251 GraphicsCallback.LIGHTWEIGHTS | 3252 GraphicsCallback.HEAVYWEIGHTS); 3253 } 3254 } 3255 3256 /** 3257 * Simulates the peer callbacks into java.awt for painting of 3258 * lightweight Components. 3259 * @param g the graphics context to use for painting 3260 * @see #paintAll 3261 */ 3262 void lightweightPaint(Graphics g) { 3263 paint(g); 3264 } 3265 3266 /** 3267 * Paints all the heavyweight subcomponents. 3268 */ 3269 void paintHeavyweightComponents(Graphics g) { 3270 } 3271 3272 /** 3273 * Repaints this component. 3274 * <p> 3275 * If this component is a lightweight component, this method 3276 * causes a call to this component's <code>paint</code> 3277 * method as soon as possible. Otherwise, this method causes 3278 * a call to this component's <code>update</code> method as soon 3279 * as possible. 3280 * <p> 3281 * <b>Note</b>: For more information on the paint mechanisms utilitized 3282 * by AWT and Swing, including information on how to write the most 3283 * efficient painting code, see 3284 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3285 3286 * 3287 * @see #update(Graphics) 3288 * @since JDK1.0 3289 */ 3290 public void repaint() { 3291 repaint(0, 0, 0, width, height); 3292 } 3293 3294 /** 3295 * Repaints the component. If this component is a lightweight 3296 * component, this results in a call to <code>paint</code> 3297 * within <code>tm</code> milliseconds. 3298 * <p> 3299 * <b>Note</b>: For more information on the paint mechanisms utilitized 3300 * by AWT and Swing, including information on how to write the most 3301 * efficient painting code, see 3302 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3303 * 3304 * @param tm maximum time in milliseconds before update 3305 * @see #paint 3306 * @see #update(Graphics) 3307 * @since JDK1.0 3308 */ 3309 public void repaint(long tm) { 3310 repaint(tm, 0, 0, width, height); 3311 } 3312 3313 /** 3314 * Repaints the specified rectangle of this component. 3315 * <p> 3316 * If this component is a lightweight component, this method 3317 * causes a call to this component's <code>paint</code> method 3318 * as soon as possible. Otherwise, this method causes a call to 3319 * this component's <code>update</code> method as soon as possible. 3320 * <p> 3321 * <b>Note</b>: For more information on the paint mechanisms utilitized 3322 * by AWT and Swing, including information on how to write the most 3323 * efficient painting code, see 3324 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3325 * 3326 * @param x the <i>x</i> coordinate 3327 * @param y the <i>y</i> coordinate 3328 * @param width the width 3329 * @param height the height 3330 * @see #update(Graphics) 3331 * @since JDK1.0 3332 */ 3333 public void repaint(int x, int y, int width, int height) { 3334 repaint(0, x, y, width, height); 3335 } 3336 3337 /** 3338 * Repaints the specified rectangle of this component within 3339 * <code>tm</code> milliseconds. 3340 * <p> 3341 * If this component is a lightweight component, this method causes 3342 * a call to this component's <code>paint</code> method. 3343 * Otherwise, this method causes a call to this component's 3344 * <code>update</code> method. 3345 * <p> 3346 * <b>Note</b>: For more information on the paint mechanisms utilitized 3347 * by AWT and Swing, including information on how to write the most 3348 * efficient painting code, see 3349 * <a href="http://java.sun.com/products/jfc/tsc/articles/painting/index.html">Painting in AWT and Swing</a>. 3350 * 3351 * @param tm maximum time in milliseconds before update 3352 * @param x the <i>x</i> coordinate 3353 * @param y the <i>y</i> coordinate 3354 * @param width the width 3355 * @param height the height 3356 * @see #update(Graphics) 3357 * @since JDK1.0 3358 */ 3359 public void repaint(long tm, int x, int y, int width, int height) { 3360 if (this.peer instanceof LightweightPeer) { 3361 // Needs to be translated to parent coordinates since 3362 // a parent native container provides the actual repaint 3363 // services. Additionally, the request is restricted to 3364 // the bounds of the component. 3365 if (parent != null) { 3366 if (x < 0) { 3367 width += x; 3368 x = 0; 3369 } 3370 if (y < 0) { 3371 height += y; 3372 y = 0; 3373 } 3374 3375 int pwidth = (width > this.width) ? this.width : width; 3376 int pheight = (height > this.height) ? this.height : height; 3377 3378 if (pwidth <= 0 || pheight <= 0) { 3379 return; 3380 } 3381 3382 int px = this.x + x; 3383 int py = this.y + y; 3384 parent.repaint(tm, px, py, pwidth, pheight); 3385 } 3386 } else { 3387 if (isVisible() && (this.peer != null) && 3388 (width > 0) && (height > 0)) { 3389 PaintEvent e = new PaintEvent(this, PaintEvent.UPDATE, 3390 new Rectangle(x, y, width, height)); 3391 Toolkit.getEventQueue().postEvent(e); 3392 } 3393 } 3394 } 3395 3396 /** 3397 * Prints this component. Applications should override this method 3398 * for components that must do special processing before being 3399 * printed or should be printed differently than they are painted. 3400 * <p> 3401 * The default implementation of this method calls the 3402 * <code>paint</code> method. 3403 * <p> 3404 * The origin of the graphics context, its 3405 * (<code>0</code>, <code>0</code>) coordinate point, is the 3406 * top-left corner of this component. The clipping region of the 3407 * graphics context is the bounding rectangle of this component. 3408 * @param g the graphics context to use for printing 3409 * @see #paint(Graphics) 3410 * @since JDK1.0 3411 */ 3412 public void print(Graphics g) { 3413 paint(g); 3414 } 3415 3416 /** 3417 * Prints this component and all of its subcomponents. 3418 * <p> 3419 * The origin of the graphics context, its 3420 * (<code>0</code>, <code>0</code>) coordinate point, is the 3421 * top-left corner of this component. The clipping region of the 3422 * graphics context is the bounding rectangle of this component. 3423 * @param g the graphics context to use for printing 3424 * @see #print(Graphics) 3425 * @since JDK1.0 3426 */ 3427 public void printAll(Graphics g) { 3428 if (isShowing()) { 3429 GraphicsCallback.PeerPrintCallback.getInstance(). 3430 runOneComponent(this, new Rectangle(0, 0, width, height), 3431 g, g.getClip(), 3432 GraphicsCallback.LIGHTWEIGHTS | 3433 GraphicsCallback.HEAVYWEIGHTS); 3434 } 3435 } 3436 3437 /** 3438 * Simulates the peer callbacks into java.awt for printing of 3439 * lightweight Components. 3440 * @param g the graphics context to use for printing 3441 * @see #printAll 3442 */ 3443 void lightweightPrint(Graphics g) { 3444 print(g); 3445 } 3446 3447 /** 3448 * Prints all the heavyweight subcomponents. 3449 */ 3450 void printHeavyweightComponents(Graphics g) { 3451 } 3452 3453 private Insets getInsets_NoClientCode() { 3454 ComponentPeer peer = this.peer; 3455 if (peer instanceof ContainerPeer) { 3456 return (Insets)((ContainerPeer)peer).getInsets().clone(); 3457 } 3458 return new Insets(0, 0, 0, 0); 3459 } 3460 3461 /** 3462 * Repaints the component when the image has changed. 3463 * This <code>imageUpdate</code> method of an <code>ImageObserver</code> 3464 * is called when more information about an 3465 * image which had been previously requested using an asynchronous 3466 * routine such as the <code>drawImage</code> method of 3467 * <code>Graphics</code> becomes available. 3468 * See the definition of <code>imageUpdate</code> for 3469 * more information on this method and its arguments. 3470 * <p> 3471 * The <code>imageUpdate</code> method of <code>Component</code> 3472 * incrementally draws an image on the component as more of the bits 3473 * of the image are available. 3474 * <p> 3475 * If the system property <code>awt.image.incrementaldraw</code> 3476 * is missing or has the value <code>true</code>, the image is 3477 * incrementally drawn. If the system property has any other value, 3478 * then the image is not drawn until it has been completely loaded. 3479 * <p> 3480 * Also, if incremental drawing is in effect, the value of the 3481 * system property <code>awt.image.redrawrate</code> is interpreted 3482 * as an integer to give the maximum redraw rate, in milliseconds. If 3483 * the system property is missing or cannot be interpreted as an 3484 * integer, the redraw rate is once every 100ms. 3485 * <p> 3486 * The interpretation of the <code>x</code>, <code>y</code>, 3487 * <code>width</code>, and <code>height</code> arguments depends on 3488 * the value of the <code>infoflags</code> argument. 3489 * 3490 * @param img the image being observed 3491 * @param infoflags see <code>imageUpdate</code> for more information 3492 * @param x the <i>x</i> coordinate 3493 * @param y the <i>y</i> coordinate 3494 * @param w the width 3495 * @param h the height 3496 * @return <code>false</code> if the infoflags indicate that the 3497 * image is completely loaded; <code>true</code> otherwise. 3498 * 3499 * @see java.awt.image.ImageObserver 3500 * @see Graphics#drawImage(Image, int, int, Color, java.awt.image.ImageObserver) 3501 * @see Graphics#drawImage(Image, int, int, java.awt.image.ImageObserver) 3502 * @see Graphics#drawImage(Image, int, int, int, int, Color, java.awt.image.ImageObserver) 3503 * @see Graphics#drawImage(Image, int, int, int, int, java.awt.image.ImageObserver) 3504 * @see java.awt.image.ImageObserver#imageUpdate(java.awt.Image, int, int, int, int, int) 3505 * @since JDK1.0 3506 */ 3507 public boolean imageUpdate(Image img, int infoflags, 3508 int x, int y, int w, int h) { 3509 int rate = -1; 3510 if ((infoflags & (FRAMEBITS|ALLBITS)) != 0) { 3511 rate = 0; 3512 } else if ((infoflags & SOMEBITS) != 0) { 3513 if (isInc) { 3514 rate = incRate; 3515 if (rate < 0) { 3516 rate = 0; 3517 } 3518 } 3519 } 3520 if (rate >= 0) { 3521 repaint(rate, 0, 0, width, height); 3522 } 3523 return (infoflags & (ALLBITS|ABORT)) == 0; 3524 } 3525 3526 /** 3527 * Creates an image from the specified image producer. 3528 * @param producer the image producer 3529 * @return the image produced 3530 * @since JDK1.0 3531 */ 3532 public Image createImage(ImageProducer producer) { 3533 ComponentPeer peer = this.peer; 3534 if ((peer != null) && ! (peer instanceof LightweightPeer)) { 3535 return peer.createImage(producer); 3536 } 3537 return getToolkit().createImage(producer); 3538 } 3539 3540 /** 3541 * Creates an off-screen drawable image 3542 * to be used for double buffering. 3543 * @param width the specified width 3544 * @param height the specified height 3545 * @return an off-screen drawable image, which can be used for double 3546 * buffering. The return value may be <code>null</code> if the 3547 * component is not displayable. This will always happen if 3548 * <code>GraphicsEnvironment.isHeadless()</code> returns 3549 * <code>true</code>. 3550 * @see #isDisplayable 3551 * @see GraphicsEnvironment#isHeadless 3552 * @since JDK1.0 3553 */ 3554 public Image createImage(int width, int height) { 3555 ComponentPeer peer = this.peer; 3556 if (peer instanceof LightweightPeer) { 3557 if (parent != null) { return parent.createImage(width, height); } 3558 else { return null;} 3559 } else { 3560 return (peer != null) ? peer.createImage(width, height) : null; 3561 } 3562 } 3563 3564 /** 3565 * Creates a volatile off-screen drawable image 3566 * to be used for double buffering. 3567 * @param width the specified width. 3568 * @param height the specified height. 3569 * @return an off-screen drawable image, which can be used for double 3570 * buffering. The return value may be <code>null</code> if the 3571 * component is not displayable. This will always happen if 3572 * <code>GraphicsEnvironment.isHeadless()</code> returns 3573 * <code>true</code>. 3574 * @see java.awt.image.VolatileImage 3575 * @see #isDisplayable 3576 * @see GraphicsEnvironment#isHeadless 3577 * @since 1.4 3578 */ 3579 public VolatileImage createVolatileImage(int width, int height) { 3580 ComponentPeer peer = this.peer; 3581 if (peer instanceof LightweightPeer) { 3582 if (parent != null) { 3583 return parent.createVolatileImage(width, height); 3584 } 3585 else { return null;} 3586 } else { 3587 return (peer != null) ? 3588 peer.createVolatileImage(width, height) : null; 3589 } 3590 } 3591 3592 /** 3593 * Creates a volatile off-screen drawable image, with the given capabilities. 3594 * The contents of this image may be lost at any time due 3595 * to operating system issues, so the image must be managed 3596 * via the <code>VolatileImage</code> interface. 3597 * @param width the specified width. 3598 * @param height the specified height. 3599 * @param caps the image capabilities 3600 * @exception AWTException if an image with the specified capabilities cannot 3601 * be created 3602 * @return a VolatileImage object, which can be used 3603 * to manage surface contents loss and capabilities. 3604 * @see java.awt.image.VolatileImage 3605 * @since 1.4 3606 */ 3607 public VolatileImage createVolatileImage(int width, int height, 3608 ImageCapabilities caps) throws AWTException { 3609 // REMIND : check caps 3610 return createVolatileImage(width, height); 3611 } 3612 3613 /** 3614 * Prepares an image for rendering on this component. The image 3615 * data is downloaded asynchronously in another thread and the 3616 * appropriate screen representation of the image is generated. 3617 * @param image the <code>Image</code> for which to 3618 * prepare a screen representation 3619 * @param observer the <code>ImageObserver</code> object 3620 * to be notified as the image is being prepared 3621 * @return <code>true</code> if the image has already been fully 3622 * prepared; <code>false</code> otherwise 3623 * @since JDK1.0 3624 */ 3625 public boolean prepareImage(Image image, ImageObserver observer) { 3626 return prepareImage(image, -1, -1, observer); 3627 } 3628 3629 /** 3630 * Prepares an image for rendering on this component at the 3631 * specified width and height. 3632 * <p> 3633 * The image data is downloaded asynchronously in another thread, 3634 * and an appropriately scaled screen representation of the image is 3635 * generated. 3636 * @param image the instance of <code>Image</code> 3637 * for which to prepare a screen representation 3638 * @param width the width of the desired screen representation 3639 * @param height the height of the desired screen representation 3640 * @param observer the <code>ImageObserver</code> object 3641 * to be notified as the image is being prepared 3642 * @return <code>true</code> if the image has already been fully 3643 * prepared; <code>false</code> otherwise 3644 * @see java.awt.image.ImageObserver 3645 * @since JDK1.0 3646 */ 3647 public boolean prepareImage(Image image, int width, int height, 3648 ImageObserver observer) { 3649 ComponentPeer peer = this.peer; 3650 if (peer instanceof LightweightPeer) { 3651 return (parent != null) 3652 ? parent.prepareImage(image, width, height, observer) 3653 : getToolkit().prepareImage(image, width, height, observer); 3654 } else { 3655 return (peer != null) 3656 ? peer.prepareImage(image, width, height, observer) 3657 : getToolkit().prepareImage(image, width, height, observer); 3658 } 3659 } 3660 3661 /** 3662 * Returns the status of the construction of a screen representation 3663 * of the specified image. 3664 * <p> 3665 * This method does not cause the image to begin loading. An 3666 * application must use the <code>prepareImage</code> method 3667 * to force the loading of an image. 3668 * <p> 3669 * Information on the flags returned by this method can be found 3670 * with the discussion of the <code>ImageObserver</code> interface. 3671 * @param image the <code>Image</code> object whose status 3672 * is being checked 3673 * @param observer the <code>ImageObserver</code> 3674 * object to be notified as the image is being prepared 3675 * @return the bitwise inclusive <b>OR</b> of 3676 * <code>ImageObserver</code> flags indicating what 3677 * information about the image is currently available 3678 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) 3679 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) 3680 * @see java.awt.image.ImageObserver 3681 * @since JDK1.0 3682 */ 3683 public int checkImage(Image image, ImageObserver observer) { 3684 return checkImage(image, -1, -1, observer); 3685 } 3686 3687 /** 3688 * Returns the status of the construction of a screen representation 3689 * of the specified image. 3690 * <p> 3691 * This method does not cause the image to begin loading. An 3692 * application must use the <code>prepareImage</code> method 3693 * to force the loading of an image. 3694 * <p> 3695 * The <code>checkImage</code> method of <code>Component</code> 3696 * calls its peer's <code>checkImage</code> method to calculate 3697 * the flags. If this component does not yet have a peer, the 3698 * component's toolkit's <code>checkImage</code> method is called 3699 * instead. 3700 * <p> 3701 * Information on the flags returned by this method can be found 3702 * with the discussion of the <code>ImageObserver</code> interface. 3703 * @param image the <code>Image</code> object whose status 3704 * is being checked 3705 * @param width the width of the scaled version 3706 * whose status is to be checked 3707 * @param height the height of the scaled version 3708 * whose status is to be checked 3709 * @param observer the <code>ImageObserver</code> object 3710 * to be notified as the image is being prepared 3711 * @return the bitwise inclusive <b>OR</b> of 3712 * <code>ImageObserver</code> flags indicating what 3713 * information about the image is currently available 3714 * @see #prepareImage(Image, int, int, java.awt.image.ImageObserver) 3715 * @see Toolkit#checkImage(Image, int, int, java.awt.image.ImageObserver) 3716 * @see java.awt.image.ImageObserver 3717 * @since JDK1.0 3718 */ 3719 public int checkImage(Image image, int width, int height, 3720 ImageObserver observer) { 3721 ComponentPeer peer = this.peer; 3722 if (peer instanceof LightweightPeer) { 3723 return (parent != null) 3724 ? parent.checkImage(image, width, height, observer) 3725 : getToolkit().checkImage(image, width, height, observer); 3726 } else { 3727 return (peer != null) 3728 ? peer.checkImage(image, width, height, observer) 3729 : getToolkit().checkImage(image, width, height, observer); 3730 } 3731 } 3732 3733 /** 3734 * Creates a new strategy for multi-buffering on this component. 3735 * Multi-buffering is useful for rendering performance. This method 3736 * attempts to create the best strategy available with the number of 3737 * buffers supplied. It will always create a <code>BufferStrategy</code> 3738 * with that number of buffers. 3739 * A page-flipping strategy is attempted first, then a blitting strategy 3740 * using accelerated buffers. Finally, an unaccelerated blitting 3741 * strategy is used. 3742 * <p> 3743 * Each time this method is called, 3744 * the existing buffer strategy for this component is discarded. 3745 * @param numBuffers number of buffers to create, including the front buffer 3746 * @exception IllegalArgumentException if numBuffers is less than 1. 3747 * @exception IllegalStateException if the component is not displayable 3748 * @see #isDisplayable 3749 * @see Window#getBufferStrategy() 3750 * @see Canvas#getBufferStrategy() 3751 * @since 1.4 3752 */ 3753 void createBufferStrategy(int numBuffers) { 3754 BufferCapabilities bufferCaps; 3755 if (numBuffers > 1) { 3756 // Try to create a page-flipping strategy 3757 bufferCaps = new BufferCapabilities(new ImageCapabilities(true), 3758 new ImageCapabilities(true), 3759 BufferCapabilities.FlipContents.UNDEFINED); 3760 try { 3761 createBufferStrategy(numBuffers, bufferCaps); 3762 return; // Success 3763 } catch (AWTException e) { 3764 // Failed 3765 } 3766 } 3767 // Try a blitting (but still accelerated) strategy 3768 bufferCaps = new BufferCapabilities(new ImageCapabilities(true), 3769 new ImageCapabilities(true), 3770 null); 3771 try { 3772 createBufferStrategy(numBuffers, bufferCaps); 3773 return; // Success 3774 } catch (AWTException e) { 3775 // Failed 3776 } 3777 // Try an unaccelerated blitting strategy 3778 bufferCaps = new BufferCapabilities(new ImageCapabilities(false), 3779 new ImageCapabilities(false), 3780 null); 3781 try { 3782 createBufferStrategy(numBuffers, bufferCaps); 3783 return; // Success 3784 } catch (AWTException e) { 3785 // Code should never reach here (an unaccelerated blitting 3786 // strategy should always work) 3787 throw new InternalError("Could not create a buffer strategy", e); 3788 } 3789 } 3790 3791 /** 3792 * Creates a new strategy for multi-buffering on this component with the 3793 * required buffer capabilities. This is useful, for example, if only 3794 * accelerated memory or page flipping is desired (as specified by the 3795 * buffer capabilities). 3796 * <p> 3797 * Each time this method 3798 * is called, <code>dispose</code> will be invoked on the existing 3799 * <code>BufferStrategy</code>. 3800 * @param numBuffers number of buffers to create 3801 * @param caps the required capabilities for creating the buffer strategy; 3802 * cannot be <code>null</code> 3803 * @exception AWTException if the capabilities supplied could not be 3804 * supported or met; this may happen, for example, if there is not enough 3805 * accelerated memory currently available, or if page flipping is specified 3806 * but not possible. 3807 * @exception IllegalArgumentException if numBuffers is less than 1, or if 3808 * caps is <code>null</code> 3809 * @see Window#getBufferStrategy() 3810 * @see Canvas#getBufferStrategy() 3811 * @since 1.4 3812 */ 3813 void createBufferStrategy(int numBuffers, 3814 BufferCapabilities caps) throws AWTException { 3815 // Check arguments 3816 if (numBuffers < 1) { 3817 throw new IllegalArgumentException( 3818 "Number of buffers must be at least 1"); 3819 } 3820 if (caps == null) { 3821 throw new IllegalArgumentException("No capabilities specified"); 3822 } 3823 // Destroy old buffers 3824 if (bufferStrategy != null) { 3825 bufferStrategy.dispose(); 3826 } 3827 if (numBuffers == 1) { 3828 bufferStrategy = new SingleBufferStrategy(caps); 3829 } else { 3830 SunGraphicsEnvironment sge = (SunGraphicsEnvironment) 3831 GraphicsEnvironment.getLocalGraphicsEnvironment(); 3832 if (!caps.isPageFlipping() && sge.isFlipStrategyPreferred(peer)) { 3833 caps = new ProxyCapabilities(caps); 3834 } 3835 // assert numBuffers > 1; 3836 if (caps.isPageFlipping()) { 3837 bufferStrategy = new FlipSubRegionBufferStrategy(numBuffers, caps); 3838 } else { 3839 bufferStrategy = new BltSubRegionBufferStrategy(numBuffers, caps); 3840 } 3841 } 3842 } 3843 3844 /** 3845 * This is a proxy capabilities class used when a FlipBufferStrategy 3846 * is created instead of the requested Blit strategy. 3847 * 3848 * @see sun.awt.SunGraphicsEnvironment#isFlipStrategyPreferred(ComponentPeer) 3849 */ 3850 private class ProxyCapabilities extends ExtendedBufferCapabilities { 3851 private BufferCapabilities orig; 3852 private ProxyCapabilities(BufferCapabilities orig) { 3853 super(orig.getFrontBufferCapabilities(), 3854 orig.getBackBufferCapabilities(), 3855 orig.getFlipContents() == 3856 BufferCapabilities.FlipContents.BACKGROUND ? 3857 BufferCapabilities.FlipContents.BACKGROUND : 3858 BufferCapabilities.FlipContents.COPIED); 3859 this.orig = orig; 3860 } 3861 } 3862 3863 /** 3864 * @return the buffer strategy used by this component 3865 * @see Window#createBufferStrategy 3866 * @see Canvas#createBufferStrategy 3867 * @since 1.4 3868 */ 3869 BufferStrategy getBufferStrategy() { 3870 return bufferStrategy; 3871 } 3872 3873 /** 3874 * @return the back buffer currently used by this component's 3875 * BufferStrategy. If there is no BufferStrategy or no 3876 * back buffer, this method returns null. 3877 */ 3878 Image getBackBuffer() { 3879 if (bufferStrategy != null) { 3880 if (bufferStrategy instanceof BltBufferStrategy) { 3881 BltBufferStrategy bltBS = (BltBufferStrategy)bufferStrategy; 3882 return bltBS.getBackBuffer(); 3883 } else if (bufferStrategy instanceof FlipBufferStrategy) { 3884 FlipBufferStrategy flipBS = (FlipBufferStrategy)bufferStrategy; 3885 return flipBS.getBackBuffer(); 3886 } 3887 } 3888 return null; 3889 } 3890 3891 /** 3892 * Inner class for flipping buffers on a component. That component must 3893 * be a <code>Canvas</code> or <code>Window</code>. 3894 * @see Canvas 3895 * @see Window 3896 * @see java.awt.image.BufferStrategy 3897 * @author Michael Martak 3898 * @since 1.4 3899 */ 3900 protected class FlipBufferStrategy extends BufferStrategy { 3901 /** 3902 * The number of buffers 3903 */ 3904 protected int numBuffers; // = 0 3905 /** 3906 * The buffering capabilities 3907 */ 3908 protected BufferCapabilities caps; // = null 3909 /** 3910 * The drawing buffer 3911 */ 3912 protected Image drawBuffer; // = null 3913 /** 3914 * The drawing buffer as a volatile image 3915 */ 3916 protected VolatileImage drawVBuffer; // = null 3917 /** 3918 * Whether or not the drawing buffer has been recently restored from 3919 * a lost state. 3920 */ 3921 protected boolean validatedContents; // = false 3922 /** 3923 * Size of the back buffers. (Note: these fields were added in 6.0 3924 * but kept package-private to avoid exposing them in the spec. 3925 * None of these fields/methods really should have been marked 3926 * protected when they were introduced in 1.4, but now we just have 3927 * to live with that decision.) 3928 */ 3929 int width; 3930 int height; 3931 3932 /** 3933 * Creates a new flipping buffer strategy for this component. 3934 * The component must be a <code>Canvas</code> or <code>Window</code>. 3935 * @see Canvas 3936 * @see Window 3937 * @param numBuffers the number of buffers 3938 * @param caps the capabilities of the buffers 3939 * @exception AWTException if the capabilities supplied could not be 3940 * supported or met 3941 * @exception ClassCastException if the component is not a canvas or 3942 * window. 3943 * @exception IllegalStateException if the component has no peer 3944 * @exception IllegalArgumentException if {@code numBuffers} is less than two, 3945 * or if {@code BufferCapabilities.isPageFlipping} is not 3946 * {@code true}. 3947 * @see #createBuffers(int, BufferCapabilities) 3948 */ 3949 protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps) 3950 throws AWTException 3951 { 3952 if (!(Component.this instanceof Window) && 3953 !(Component.this instanceof Canvas)) 3954 { 3955 throw new ClassCastException( 3956 "Component must be a Canvas or Window"); 3957 } 3958 this.numBuffers = numBuffers; 3959 this.caps = caps; 3960 createBuffers(numBuffers, caps); 3961 } 3962 3963 /** 3964 * Creates one or more complex, flipping buffers with the given 3965 * capabilities. 3966 * @param numBuffers number of buffers to create; must be greater than 3967 * one 3968 * @param caps the capabilities of the buffers. 3969 * <code>BufferCapabilities.isPageFlipping</code> must be 3970 * <code>true</code>. 3971 * @exception AWTException if the capabilities supplied could not be 3972 * supported or met 3973 * @exception IllegalStateException if the component has no peer 3974 * @exception IllegalArgumentException if numBuffers is less than two, 3975 * or if <code>BufferCapabilities.isPageFlipping</code> is not 3976 * <code>true</code>. 3977 * @see java.awt.BufferCapabilities#isPageFlipping() 3978 */ 3979 protected void createBuffers(int numBuffers, BufferCapabilities caps) 3980 throws AWTException 3981 { 3982 if (numBuffers < 2) { 3983 throw new IllegalArgumentException( 3984 "Number of buffers cannot be less than two"); 3985 } else if (peer == null) { 3986 throw new IllegalStateException( 3987 "Component must have a valid peer"); 3988 } else if (caps == null || !caps.isPageFlipping()) { 3989 throw new IllegalArgumentException( 3990 "Page flipping capabilities must be specified"); 3991 } 3992 3993 // save the current bounds 3994 width = getWidth(); 3995 height = getHeight(); 3996 3997 if (drawBuffer != null) { 3998 // dispose the existing backbuffers 3999 drawBuffer = null; 4000 drawVBuffer = null; 4001 destroyBuffers(); 4002 // ... then recreate the backbuffers 4003 } 4004 4005 if (caps instanceof ExtendedBufferCapabilities) { 4006 ExtendedBufferCapabilities ebc = 4007 (ExtendedBufferCapabilities)caps; 4008 if (ebc.getVSync() == VSYNC_ON) { 4009 // if this buffer strategy is not allowed to be v-synced, 4010 // change the caps that we pass to the peer but keep on 4011 // trying to create v-synced buffers; 4012 // do not throw IAE here in case it is disallowed, see 4013 // ExtendedBufferCapabilities for more info 4014 if (!VSyncedBSManager.vsyncAllowed(this)) { 4015 caps = ebc.derive(VSYNC_DEFAULT); 4016 } 4017 } 4018 } 4019 4020 peer.createBuffers(numBuffers, caps); 4021 updateInternalBuffers(); 4022 } 4023 4024 /** 4025 * Updates internal buffers (both volatile and non-volatile) 4026 * by requesting the back-buffer from the peer. 4027 */ 4028 private void updateInternalBuffers() { 4029 // get the images associated with the draw buffer 4030 drawBuffer = getBackBuffer(); 4031 if (drawBuffer instanceof VolatileImage) { 4032 drawVBuffer = (VolatileImage)drawBuffer; 4033 } else { 4034 drawVBuffer = null; 4035 } 4036 } 4037 4038 /** 4039 * @return direct access to the back buffer, as an image. 4040 * @exception IllegalStateException if the buffers have not yet 4041 * been created 4042 */ 4043 protected Image getBackBuffer() { 4044 if (peer != null) { 4045 return peer.getBackBuffer(); 4046 } else { 4047 throw new IllegalStateException( 4048 "Component must have a valid peer"); 4049 } 4050 } 4051 4052 /** 4053 * Flipping moves the contents of the back buffer to the front buffer, 4054 * either by copying or by moving the video pointer. 4055 * @param flipAction an integer value describing the flipping action 4056 * for the contents of the back buffer. This should be one of the 4057 * values of the <code>BufferCapabilities.FlipContents</code> 4058 * property. 4059 * @exception IllegalStateException if the buffers have not yet 4060 * been created 4061 * @see java.awt.BufferCapabilities#getFlipContents() 4062 */ 4063 protected void flip(BufferCapabilities.FlipContents flipAction) { 4064 if (peer != null) { 4065 Image backBuffer = getBackBuffer(); 4066 if (backBuffer != null) { 4067 peer.flip(0, 0, 4068 backBuffer.getWidth(null), 4069 backBuffer.getHeight(null), flipAction); 4070 } 4071 } else { 4072 throw new IllegalStateException( 4073 "Component must have a valid peer"); 4074 } 4075 } 4076 4077 void flipSubRegion(int x1, int y1, int x2, int y2, 4078 BufferCapabilities.FlipContents flipAction) 4079 { 4080 if (peer != null) { 4081 peer.flip(x1, y1, x2, y2, flipAction); 4082 } else { 4083 throw new IllegalStateException( 4084 "Component must have a valid peer"); 4085 } 4086 } 4087 4088 /** 4089 * Destroys the buffers created through this object 4090 */ 4091 protected void destroyBuffers() { 4092 VSyncedBSManager.releaseVsync(this); 4093 if (peer != null) { 4094 peer.destroyBuffers(); 4095 } else { 4096 throw new IllegalStateException( 4097 "Component must have a valid peer"); 4098 } 4099 } 4100 4101 /** 4102 * @return the buffering capabilities of this strategy 4103 */ 4104 public BufferCapabilities getCapabilities() { 4105 if (caps instanceof ProxyCapabilities) { 4106 return ((ProxyCapabilities)caps).orig; 4107 } else { 4108 return caps; 4109 } 4110 } 4111 4112 /** 4113 * @return the graphics on the drawing buffer. This method may not 4114 * be synchronized for performance reasons; use of this method by multiple 4115 * threads should be handled at the application level. Disposal of the 4116 * graphics object must be handled by the application. 4117 */ 4118 public Graphics getDrawGraphics() { 4119 revalidate(); 4120 return drawBuffer.getGraphics(); 4121 } 4122 4123 /** 4124 * Restore the drawing buffer if it has been lost 4125 */ 4126 protected void revalidate() { 4127 revalidate(true); 4128 } 4129 4130 void revalidate(boolean checkSize) { 4131 validatedContents = false; 4132 4133 if (checkSize && (getWidth() != width || getHeight() != height)) { 4134 // component has been resized; recreate the backbuffers 4135 try { 4136 createBuffers(numBuffers, caps); 4137 } catch (AWTException e) { 4138 // shouldn't be possible 4139 } 4140 validatedContents = true; 4141 } 4142 4143 // get the buffers from the peer every time since they 4144 // might have been replaced in response to a display change event 4145 updateInternalBuffers(); 4146 4147 // now validate the backbuffer 4148 if (drawVBuffer != null) { 4149 GraphicsConfiguration gc = 4150 getGraphicsConfiguration_NoClientCode(); 4151 int returnCode = drawVBuffer.validate(gc); 4152 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 4153 try { 4154 createBuffers(numBuffers, caps); 4155 } catch (AWTException e) { 4156 // shouldn't be possible 4157 } 4158 if (drawVBuffer != null) { 4159 // backbuffers were recreated, so validate again 4160 drawVBuffer.validate(gc); 4161 } 4162 validatedContents = true; 4163 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 4164 validatedContents = true; 4165 } 4166 } 4167 } 4168 4169 /** 4170 * @return whether the drawing buffer was lost since the last call to 4171 * <code>getDrawGraphics</code> 4172 */ 4173 public boolean contentsLost() { 4174 if (drawVBuffer == null) { 4175 return false; 4176 } 4177 return drawVBuffer.contentsLost(); 4178 } 4179 4180 /** 4181 * @return whether the drawing buffer was recently restored from a lost 4182 * state and reinitialized to the default background color (white) 4183 */ 4184 public boolean contentsRestored() { 4185 return validatedContents; 4186 } 4187 4188 /** 4189 * Makes the next available buffer visible by either blitting or 4190 * flipping. 4191 */ 4192 public void show() { 4193 flip(caps.getFlipContents()); 4194 } 4195 4196 /** 4197 * Makes specified region of the the next available buffer visible 4198 * by either blitting or flipping. 4199 */ 4200 void showSubRegion(int x1, int y1, int x2, int y2) { 4201 flipSubRegion(x1, y1, x2, y2, caps.getFlipContents()); 4202 } 4203 4204 /** 4205 * {@inheritDoc} 4206 * @since 1.6 4207 */ 4208 public void dispose() { 4209 if (Component.this.bufferStrategy == this) { 4210 Component.this.bufferStrategy = null; 4211 if (peer != null) { 4212 destroyBuffers(); 4213 } 4214 } 4215 } 4216 4217 } // Inner class FlipBufferStrategy 4218 4219 /** 4220 * Inner class for blitting offscreen surfaces to a component. 4221 * 4222 * @author Michael Martak 4223 * @since 1.4 4224 */ 4225 protected class BltBufferStrategy extends BufferStrategy { 4226 4227 /** 4228 * The buffering capabilities 4229 */ 4230 protected BufferCapabilities caps; // = null 4231 /** 4232 * The back buffers 4233 */ 4234 protected VolatileImage[] backBuffers; // = null 4235 /** 4236 * Whether or not the drawing buffer has been recently restored from 4237 * a lost state. 4238 */ 4239 protected boolean validatedContents; // = false 4240 /** 4241 * Size of the back buffers 4242 */ 4243 protected int width; 4244 protected int height; 4245 4246 /** 4247 * Insets for the hosting Component. The size of the back buffer 4248 * is constrained by these. 4249 */ 4250 private Insets insets; 4251 4252 /** 4253 * Creates a new blt buffer strategy around a component 4254 * @param numBuffers number of buffers to create, including the 4255 * front buffer 4256 * @param caps the capabilities of the buffers 4257 */ 4258 protected BltBufferStrategy(int numBuffers, BufferCapabilities caps) { 4259 this.caps = caps; 4260 createBackBuffers(numBuffers - 1); 4261 } 4262 4263 /** 4264 * {@inheritDoc} 4265 * @since 1.6 4266 */ 4267 public void dispose() { 4268 if (backBuffers != null) { 4269 for (int counter = backBuffers.length - 1; counter >= 0; 4270 counter--) { 4271 if (backBuffers[counter] != null) { 4272 backBuffers[counter].flush(); 4273 backBuffers[counter] = null; 4274 } 4275 } 4276 } 4277 if (Component.this.bufferStrategy == this) { 4278 Component.this.bufferStrategy = null; 4279 } 4280 } 4281 4282 /** 4283 * Creates the back buffers 4284 */ 4285 protected void createBackBuffers(int numBuffers) { 4286 if (numBuffers == 0) { 4287 backBuffers = null; 4288 } else { 4289 // save the current bounds 4290 width = getWidth(); 4291 height = getHeight(); 4292 insets = getInsets_NoClientCode(); 4293 int iWidth = width - insets.left - insets.right; 4294 int iHeight = height - insets.top - insets.bottom; 4295 4296 // It is possible for the component's width and/or height 4297 // to be 0 here. Force the size of the backbuffers to 4298 // be > 0 so that creating the image won't fail. 4299 iWidth = Math.max(1, iWidth); 4300 iHeight = Math.max(1, iHeight); 4301 if (backBuffers == null) { 4302 backBuffers = new VolatileImage[numBuffers]; 4303 } else { 4304 // flush any existing backbuffers 4305 for (int i = 0; i < numBuffers; i++) { 4306 if (backBuffers[i] != null) { 4307 backBuffers[i].flush(); 4308 backBuffers[i] = null; 4309 } 4310 } 4311 } 4312 4313 // create the backbuffers 4314 for (int i = 0; i < numBuffers; i++) { 4315 backBuffers[i] = createVolatileImage(iWidth, iHeight); 4316 } 4317 } 4318 } 4319 4320 /** 4321 * @return the buffering capabilities of this strategy 4322 */ 4323 public BufferCapabilities getCapabilities() { 4324 return caps; 4325 } 4326 4327 /** 4328 * @return the draw graphics 4329 */ 4330 public Graphics getDrawGraphics() { 4331 revalidate(); 4332 Image backBuffer = getBackBuffer(); 4333 if (backBuffer == null) { 4334 return getGraphics(); 4335 } 4336 SunGraphics2D g = (SunGraphics2D)backBuffer.getGraphics(); 4337 g.constrain(-insets.left, -insets.top, 4338 backBuffer.getWidth(null) + insets.left, 4339 backBuffer.getHeight(null) + insets.top); 4340 return g; 4341 } 4342 4343 /** 4344 * @return direct access to the back buffer, as an image. 4345 * If there is no back buffer, returns null. 4346 */ 4347 Image getBackBuffer() { 4348 if (backBuffers != null) { 4349 return backBuffers[backBuffers.length - 1]; 4350 } else { 4351 return null; 4352 } 4353 } 4354 4355 /** 4356 * Makes the next available buffer visible. 4357 */ 4358 public void show() { 4359 showSubRegion(insets.left, insets.top, 4360 width - insets.right, 4361 height - insets.bottom); 4362 } 4363 4364 /** 4365 * Package-private method to present a specific rectangular area 4366 * of this buffer. This class currently shows only the entire 4367 * buffer, by calling showSubRegion() with the full dimensions of 4368 * the buffer. Subclasses (e.g., BltSubRegionBufferStrategy 4369 * and FlipSubRegionBufferStrategy) may have region-specific show 4370 * methods that call this method with actual sub regions of the 4371 * buffer. 4372 */ 4373 void showSubRegion(int x1, int y1, int x2, int y2) { 4374 if (backBuffers == null) { 4375 return; 4376 } 4377 // Adjust location to be relative to client area. 4378 x1 -= insets.left; 4379 x2 -= insets.left; 4380 y1 -= insets.top; 4381 y2 -= insets.top; 4382 Graphics g = getGraphics_NoClientCode(); 4383 if (g == null) { 4384 // Not showing, bail 4385 return; 4386 } 4387 try { 4388 // First image copy is in terms of Frame's coordinates, need 4389 // to translate to client area. 4390 g.translate(insets.left, insets.top); 4391 for (int i = 0; i < backBuffers.length; i++) { 4392 g.drawImage(backBuffers[i], 4393 x1, y1, x2, y2, 4394 x1, y1, x2, y2, 4395 null); 4396 g.dispose(); 4397 g = null; 4398 g = backBuffers[i].getGraphics(); 4399 } 4400 } finally { 4401 if (g != null) { 4402 g.dispose(); 4403 } 4404 } 4405 } 4406 4407 /** 4408 * Restore the drawing buffer if it has been lost 4409 */ 4410 protected void revalidate() { 4411 revalidate(true); 4412 } 4413 4414 void revalidate(boolean checkSize) { 4415 validatedContents = false; 4416 4417 if (backBuffers == null) { 4418 return; 4419 } 4420 4421 if (checkSize) { 4422 Insets insets = getInsets_NoClientCode(); 4423 if (getWidth() != width || getHeight() != height || 4424 !insets.equals(this.insets)) { 4425 // component has been resized; recreate the backbuffers 4426 createBackBuffers(backBuffers.length); 4427 validatedContents = true; 4428 } 4429 } 4430 4431 // now validate the backbuffer 4432 GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode(); 4433 int returnCode = 4434 backBuffers[backBuffers.length - 1].validate(gc); 4435 if (returnCode == VolatileImage.IMAGE_INCOMPATIBLE) { 4436 if (checkSize) { 4437 createBackBuffers(backBuffers.length); 4438 // backbuffers were recreated, so validate again 4439 backBuffers[backBuffers.length - 1].validate(gc); 4440 } 4441 // else case means we're called from Swing on the toolkit 4442 // thread, don't recreate buffers as that'll deadlock 4443 // (creating VolatileImages invokes getting GraphicsConfig 4444 // which grabs treelock). 4445 validatedContents = true; 4446 } else if (returnCode == VolatileImage.IMAGE_RESTORED) { 4447 validatedContents = true; 4448 } 4449 } 4450 4451 /** 4452 * @return whether the drawing buffer was lost since the last call to 4453 * <code>getDrawGraphics</code> 4454 */ 4455 public boolean contentsLost() { 4456 if (backBuffers == null) { 4457 return false; 4458 } else { 4459 return backBuffers[backBuffers.length - 1].contentsLost(); 4460 } 4461 } 4462 4463 /** 4464 * @return whether the drawing buffer was recently restored from a lost 4465 * state and reinitialized to the default background color (white) 4466 */ 4467 public boolean contentsRestored() { 4468 return validatedContents; 4469 } 4470 } // Inner class BltBufferStrategy 4471 4472 /** 4473 * Private class to perform sub-region flipping. 4474 */ 4475 private class FlipSubRegionBufferStrategy extends FlipBufferStrategy 4476 implements SubRegionShowable 4477 { 4478 4479 protected FlipSubRegionBufferStrategy(int numBuffers, 4480 BufferCapabilities caps) 4481 throws AWTException 4482 { 4483 super(numBuffers, caps); 4484 } 4485 4486 public void show(int x1, int y1, int x2, int y2) { 4487 showSubRegion(x1, y1, x2, y2); 4488 } 4489 4490 // This is invoked by Swing on the toolkit thread. 4491 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4492 if (!contentsLost()) { 4493 showSubRegion(x1, y1, x2, y2); 4494 return !contentsLost(); 4495 } 4496 return false; 4497 } 4498 } 4499 4500 /** 4501 * Private class to perform sub-region blitting. Swing will use 4502 * this subclass via the SubRegionShowable interface in order to 4503 * copy only the area changed during a repaint. 4504 * @see javax.swing.BufferStrategyPaintManager 4505 */ 4506 private class BltSubRegionBufferStrategy extends BltBufferStrategy 4507 implements SubRegionShowable 4508 { 4509 4510 protected BltSubRegionBufferStrategy(int numBuffers, 4511 BufferCapabilities caps) 4512 { 4513 super(numBuffers, caps); 4514 } 4515 4516 public void show(int x1, int y1, int x2, int y2) { 4517 showSubRegion(x1, y1, x2, y2); 4518 } 4519 4520 // This method is called by Swing on the toolkit thread. 4521 public boolean showIfNotLost(int x1, int y1, int x2, int y2) { 4522 if (!contentsLost()) { 4523 showSubRegion(x1, y1, x2, y2); 4524 return !contentsLost(); 4525 } 4526 return false; 4527 } 4528 } 4529 4530 /** 4531 * Inner class for flipping buffers on a component. That component must 4532 * be a <code>Canvas</code> or <code>Window</code>. 4533 * @see Canvas 4534 * @see Window 4535 * @see java.awt.image.BufferStrategy 4536 * @author Michael Martak 4537 * @since 1.4 4538 */ 4539 private class SingleBufferStrategy extends BufferStrategy { 4540 4541 private BufferCapabilities caps; 4542 4543 public SingleBufferStrategy(BufferCapabilities caps) { 4544 this.caps = caps; 4545 } 4546 public BufferCapabilities getCapabilities() { 4547 return caps; 4548 } 4549 public Graphics getDrawGraphics() { 4550 return getGraphics(); 4551 } 4552 public boolean contentsLost() { 4553 return false; 4554 } 4555 public boolean contentsRestored() { 4556 return false; 4557 } 4558 public void show() { 4559 // Do nothing 4560 } 4561 } // Inner class SingleBufferStrategy 4562 4563 /** 4564 * Sets whether or not paint messages received from the operating system 4565 * should be ignored. This does not affect paint events generated in 4566 * software by the AWT, unless they are an immediate response to an 4567 * OS-level paint message. 4568 * <p> 4569 * This is useful, for example, if running under full-screen mode and 4570 * better performance is desired, or if page-flipping is used as the 4571 * buffer strategy. 4572 * 4573 * @since 1.4 4574 * @see #getIgnoreRepaint 4575 * @see Canvas#createBufferStrategy 4576 * @see Window#createBufferStrategy 4577 * @see java.awt.image.BufferStrategy 4578 * @see GraphicsDevice#setFullScreenWindow 4579 */ 4580 public void setIgnoreRepaint(boolean ignoreRepaint) { 4581 this.ignoreRepaint = ignoreRepaint; 4582 } 4583 4584 /** 4585 * @return whether or not paint messages received from the operating system 4586 * should be ignored. 4587 * 4588 * @since 1.4 4589 * @see #setIgnoreRepaint 4590 */ 4591 public boolean getIgnoreRepaint() { 4592 return ignoreRepaint; 4593 } 4594 4595 /** 4596 * Checks whether this component "contains" the specified point, 4597 * where <code>x</code> and <code>y</code> are defined to be 4598 * relative to the coordinate system of this component. 4599 * @param x the <i>x</i> coordinate of the point 4600 * @param y the <i>y</i> coordinate of the point 4601 * @see #getComponentAt(int, int) 4602 * @since JDK1.1 4603 */ 4604 public boolean contains(int x, int y) { 4605 return inside(x, y); 4606 } 4607 4608 /** 4609 * @deprecated As of JDK version 1.1, 4610 * replaced by contains(int, int). 4611 */ 4612 @Deprecated 4613 public boolean inside(int x, int y) { 4614 return (x >= 0) && (x < width) && (y >= 0) && (y < height); 4615 } 4616 4617 /** 4618 * Checks whether this component "contains" the specified point, 4619 * where the point's <i>x</i> and <i>y</i> coordinates are defined 4620 * to be relative to the coordinate system of this component. 4621 * @param p the point 4622 * @throws NullPointerException if {@code p} is {@code null} 4623 * @see #getComponentAt(Point) 4624 * @since JDK1.1 4625 */ 4626 public boolean contains(Point p) { 4627 return contains(p.x, p.y); 4628 } 4629 4630 /** 4631 * Determines if this component or one of its immediate 4632 * subcomponents contains the (<i>x</i>, <i>y</i>) location, 4633 * and if so, returns the containing component. This method only 4634 * looks one level deep. If the point (<i>x</i>, <i>y</i>) is 4635 * inside a subcomponent that itself has subcomponents, it does not 4636 * go looking down the subcomponent tree. 4637 * <p> 4638 * The <code>locate</code> method of <code>Component</code> simply 4639 * returns the component itself if the (<i>x</i>, <i>y</i>) 4640 * coordinate location is inside its bounding box, and <code>null</code> 4641 * otherwise. 4642 * @param x the <i>x</i> coordinate 4643 * @param y the <i>y</i> coordinate 4644 * @return the component or subcomponent that contains the 4645 * (<i>x</i>, <i>y</i>) location; 4646 * <code>null</code> if the location 4647 * is outside this component 4648 * @see #contains(int, int) 4649 * @since JDK1.0 4650 */ 4651 public Component getComponentAt(int x, int y) { 4652 return locate(x, y); 4653 } 4654 4655 /** 4656 * @deprecated As of JDK version 1.1, 4657 * replaced by getComponentAt(int, int). 4658 */ 4659 @Deprecated 4660 public Component locate(int x, int y) { 4661 return contains(x, y) ? this : null; 4662 } 4663 4664 /** 4665 * Returns the component or subcomponent that contains the 4666 * specified point. 4667 * @param p the point 4668 * @see java.awt.Component#contains 4669 * @since JDK1.1 4670 */ 4671 public Component getComponentAt(Point p) { 4672 return getComponentAt(p.x, p.y); 4673 } 4674 4675 /** 4676 * @deprecated As of JDK version 1.1, 4677 * replaced by <code>dispatchEvent(AWTEvent e)</code>. 4678 */ 4679 @Deprecated 4680 public void deliverEvent(Event e) { 4681 postEvent(e); 4682 } 4683 4684 /** 4685 * Dispatches an event to this component or one of its sub components. 4686 * Calls <code>processEvent</code> before returning for 1.1-style 4687 * events which have been enabled for the <code>Component</code>. 4688 * @param e the event 4689 */ 4690 public final void dispatchEvent(AWTEvent e) { 4691 dispatchEventImpl(e); 4692 } 4693 4694 @SuppressWarnings("deprecation") 4695 void dispatchEventImpl(AWTEvent e) { 4696 int id = e.getID(); 4697 4698 // Check that this component belongs to this app-context 4699 AppContext compContext = appContext; 4700 if (compContext != null && !compContext.equals(AppContext.getAppContext())) { 4701 if (eventLog.isLoggable(PlatformLogger.FINE)) { 4702 eventLog.fine("Event " + e + " is being dispatched on the wrong AppContext"); 4703 } 4704 } 4705 4706 if (eventLog.isLoggable(PlatformLogger.FINEST)) { 4707 eventLog.finest("{0}", e); 4708 } 4709 4710 /* 4711 * 0. Set timestamp and modifiers of current event. 4712 */ 4713 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 * <p> 7173 * This method may throw a {@code ClassCastException} if any {@code Object} 7174 * in {@code keystrokes} is not an {@code AWTKeyStroke}. 7175 * 7176 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7177 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7178 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7179 * @param keystrokes the Set of AWTKeyStroke for the specified operation 7180 * @see #getFocusTraversalKeys 7181 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 7182 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 7183 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 7184 * @throws IllegalArgumentException if id is not one of 7185 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7186 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7187 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS, or if keystrokes 7188 * contains null, or if any keystroke represents a KEY_TYPED event, 7189 * or if any keystroke already maps to another focus traversal 7190 * operation for this Component 7191 * @since 1.4 7192 * @beaninfo 7193 * bound: true 7194 */ 7195 public void setFocusTraversalKeys(int id, 7196 Set<? extends AWTKeyStroke> keystrokes) 7197 { 7198 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7199 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7200 } 7201 7202 setFocusTraversalKeys_NoIDCheck(id, keystrokes); 7203 } 7204 7205 /** 7206 * Returns the Set of focus traversal keys for a given traversal operation 7207 * for this Component. (See 7208 * <code>setFocusTraversalKeys</code> for a full description of each key.) 7209 * <p> 7210 * If a Set of traversal keys has not been explicitly defined for this 7211 * Component, then this Component's parent's Set is returned. If no Set 7212 * has been explicitly defined for any of this Component's ancestors, then 7213 * the current KeyboardFocusManager's default Set is returned. 7214 * 7215 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7216 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7217 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7218 * @return the Set of AWTKeyStrokes for the specified operation. The Set 7219 * will be unmodifiable, and may be empty. null will never be 7220 * returned. 7221 * @see #setFocusTraversalKeys 7222 * @see KeyboardFocusManager#FORWARD_TRAVERSAL_KEYS 7223 * @see KeyboardFocusManager#BACKWARD_TRAVERSAL_KEYS 7224 * @see KeyboardFocusManager#UP_CYCLE_TRAVERSAL_KEYS 7225 * @throws IllegalArgumentException if id is not one of 7226 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7227 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7228 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7229 * @since 1.4 7230 */ 7231 public Set<AWTKeyStroke> getFocusTraversalKeys(int id) { 7232 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7233 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7234 } 7235 7236 return getFocusTraversalKeys_NoIDCheck(id); 7237 } 7238 7239 // We define these methods so that Container does not need to repeat this 7240 // code. Container cannot call super.<method> because Container allows 7241 // DOWN_CYCLE_TRAVERSAL_KEY while Component does not. The Component method 7242 // would erroneously generate an IllegalArgumentException for 7243 // DOWN_CYCLE_TRAVERSAL_KEY. 7244 final void setFocusTraversalKeys_NoIDCheck(int id, Set<? extends AWTKeyStroke> keystrokes) { 7245 Set<AWTKeyStroke> oldKeys; 7246 7247 synchronized (this) { 7248 if (focusTraversalKeys == null) { 7249 initializeFocusTraversalKeys(); 7250 } 7251 7252 if (keystrokes != null) { 7253 for (AWTKeyStroke keystroke : keystrokes ) { 7254 7255 if (keystroke == null) { 7256 throw new IllegalArgumentException("cannot set null focus traversal key"); 7257 } 7258 7259 if (keystroke.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { 7260 throw new IllegalArgumentException("focus traversal keys cannot map to KEY_TYPED events"); 7261 } 7262 7263 for (int i = 0; i < focusTraversalKeys.length; i++) { 7264 if (i == id) { 7265 continue; 7266 } 7267 7268 if (getFocusTraversalKeys_NoIDCheck(i).contains(keystroke)) 7269 { 7270 throw new IllegalArgumentException("focus traversal keys must be unique for a Component"); 7271 } 7272 } 7273 } 7274 } 7275 7276 oldKeys = focusTraversalKeys[id]; 7277 focusTraversalKeys[id] = (keystrokes != null) 7278 ? Collections.unmodifiableSet(new HashSet<AWTKeyStroke>(keystrokes)) 7279 : null; 7280 } 7281 7282 firePropertyChange(focusTraversalKeyPropertyNames[id], oldKeys, 7283 keystrokes); 7284 } 7285 final Set<AWTKeyStroke> getFocusTraversalKeys_NoIDCheck(int id) { 7286 // Okay to return Set directly because it is an unmodifiable view 7287 Set<AWTKeyStroke> keystrokes = (focusTraversalKeys != null) 7288 ? focusTraversalKeys[id] 7289 : null; 7290 7291 if (keystrokes != null) { 7292 return keystrokes; 7293 } else { 7294 Container parent = this.parent; 7295 if (parent != null) { 7296 return parent.getFocusTraversalKeys(id); 7297 } else { 7298 return KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7299 getDefaultFocusTraversalKeys(id); 7300 } 7301 } 7302 } 7303 7304 /** 7305 * Returns whether the Set of focus traversal keys for the given focus 7306 * traversal operation has been explicitly defined for this Component. If 7307 * this method returns <code>false</code>, this Component is inheriting the 7308 * Set from an ancestor, or from the current KeyboardFocusManager. 7309 * 7310 * @param id one of KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7311 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7312 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7313 * @return <code>true</code> if the the Set of focus traversal keys for the 7314 * given focus traversal operation has been explicitly defined for 7315 * this Component; <code>false</code> otherwise. 7316 * @throws IllegalArgumentException if id is not one of 7317 * KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, 7318 * KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, or 7319 * KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS 7320 * @since 1.4 7321 */ 7322 public boolean areFocusTraversalKeysSet(int id) { 7323 if (id < 0 || id >= KeyboardFocusManager.TRAVERSAL_KEY_LENGTH - 1) { 7324 throw new IllegalArgumentException("invalid focus traversal key identifier"); 7325 } 7326 7327 return (focusTraversalKeys != null && focusTraversalKeys[id] != null); 7328 } 7329 7330 /** 7331 * Sets whether focus traversal keys are enabled for this Component. 7332 * Components for which focus traversal keys are disabled receive key 7333 * events for focus traversal keys. Components for which focus traversal 7334 * keys are enabled do not see these events; instead, the events are 7335 * automatically converted to traversal operations. 7336 * 7337 * @param focusTraversalKeysEnabled whether focus traversal keys are 7338 * enabled for this Component 7339 * @see #getFocusTraversalKeysEnabled 7340 * @see #setFocusTraversalKeys 7341 * @see #getFocusTraversalKeys 7342 * @since 1.4 7343 * @beaninfo 7344 * bound: true 7345 */ 7346 public void setFocusTraversalKeysEnabled(boolean 7347 focusTraversalKeysEnabled) { 7348 boolean oldFocusTraversalKeysEnabled; 7349 synchronized (this) { 7350 oldFocusTraversalKeysEnabled = this.focusTraversalKeysEnabled; 7351 this.focusTraversalKeysEnabled = focusTraversalKeysEnabled; 7352 } 7353 firePropertyChange("focusTraversalKeysEnabled", 7354 oldFocusTraversalKeysEnabled, 7355 focusTraversalKeysEnabled); 7356 } 7357 7358 /** 7359 * Returns whether focus traversal keys are enabled for this Component. 7360 * Components for which focus traversal keys are disabled receive key 7361 * events for focus traversal keys. Components for which focus traversal 7362 * keys are enabled do not see these events; instead, the events are 7363 * automatically converted to traversal operations. 7364 * 7365 * @return whether focus traversal keys are enabled for this Component 7366 * @see #setFocusTraversalKeysEnabled 7367 * @see #setFocusTraversalKeys 7368 * @see #getFocusTraversalKeys 7369 * @since 1.4 7370 */ 7371 public boolean getFocusTraversalKeysEnabled() { 7372 return focusTraversalKeysEnabled; 7373 } 7374 7375 /** 7376 * Requests that this Component get the input focus, and that this 7377 * Component's top-level ancestor become the focused Window. This 7378 * component must be displayable, focusable, visible and all of 7379 * its ancestors (with the exception of the top-level Window) must 7380 * be visible for the request to be granted. Every effort will be 7381 * made to honor the request; however, in some cases it may be 7382 * impossible to do so. Developers must never assume that this 7383 * Component is the focus owner until this Component receives a 7384 * FOCUS_GAINED event. If this request is denied because this 7385 * Component's top-level Window cannot become the focused Window, 7386 * the request will be remembered and will be granted when the 7387 * Window is later focused by the user. 7388 * <p> 7389 * This method cannot be used to set the focus owner to no Component at 7390 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> 7391 * instead. 7392 * <p> 7393 * Because the focus behavior of this method is platform-dependent, 7394 * developers are strongly encouraged to use 7395 * <code>requestFocusInWindow</code> when possible. 7396 * 7397 * <p>Note: Not all focus transfers result from invoking this method. As 7398 * such, a component may receive focus without this or any of the other 7399 * {@code requestFocus} methods of {@code Component} being invoked. 7400 * 7401 * @see #requestFocusInWindow 7402 * @see java.awt.event.FocusEvent 7403 * @see #addFocusListener 7404 * @see #isFocusable 7405 * @see #isDisplayable 7406 * @see KeyboardFocusManager#clearGlobalFocusOwner 7407 * @since JDK1.0 7408 */ 7409 public void requestFocus() { 7410 requestFocusHelper(false, true); 7411 } 7412 7413 boolean requestFocus(CausedFocusEvent.Cause cause) { 7414 return requestFocusHelper(false, true, cause); 7415 } 7416 7417 /** 7418 * Requests that this <code>Component</code> get the input focus, 7419 * and that this <code>Component</code>'s top-level ancestor 7420 * become the focused <code>Window</code>. This component must be 7421 * displayable, focusable, visible and all of its ancestors (with 7422 * the exception of the top-level Window) must be visible for the 7423 * request to be granted. Every effort will be made to honor the 7424 * request; however, in some cases it may be impossible to do 7425 * so. Developers must never assume that this component is the 7426 * focus owner until this component receives a FOCUS_GAINED 7427 * event. If this request is denied because this component's 7428 * top-level window cannot become the focused window, the request 7429 * will be remembered and will be granted when the window is later 7430 * focused by the user. 7431 * <p> 7432 * This method returns a boolean value. If <code>false</code> is returned, 7433 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7434 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7435 * extraordinary event, such as disposal of the component's peer, occurs 7436 * before the request can be granted by the native windowing system. Again, 7437 * while a return value of <code>true</code> indicates that the request is 7438 * likely to succeed, developers must never assume that this component is 7439 * the focus owner until this component receives a FOCUS_GAINED event. 7440 * <p> 7441 * This method cannot be used to set the focus owner to no component at 7442 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> 7443 * instead. 7444 * <p> 7445 * Because the focus behavior of this method is platform-dependent, 7446 * developers are strongly encouraged to use 7447 * <code>requestFocusInWindow</code> when possible. 7448 * <p> 7449 * Every effort will be made to ensure that <code>FocusEvent</code>s 7450 * generated as a 7451 * result of this request will have the specified temporary value. However, 7452 * because specifying an arbitrary temporary state may not be implementable 7453 * on all native windowing systems, correct behavior for this method can be 7454 * guaranteed only for lightweight <code>Component</code>s. 7455 * This method is not intended 7456 * for general use, but exists instead as a hook for lightweight component 7457 * libraries, such as Swing. 7458 * 7459 * <p>Note: Not all focus transfers result from invoking this method. As 7460 * such, a component may receive focus without this or any of the other 7461 * {@code requestFocus} methods of {@code Component} being invoked. 7462 * 7463 * @param temporary true if the focus change is temporary, 7464 * such as when the window loses the focus; for 7465 * more information on temporary focus changes see the 7466 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7467 * @return <code>false</code> if the focus change request is guaranteed to 7468 * fail; <code>true</code> if it is likely to succeed 7469 * @see java.awt.event.FocusEvent 7470 * @see #addFocusListener 7471 * @see #isFocusable 7472 * @see #isDisplayable 7473 * @see KeyboardFocusManager#clearGlobalFocusOwner 7474 * @since 1.4 7475 */ 7476 protected boolean requestFocus(boolean temporary) { 7477 return requestFocusHelper(temporary, true); 7478 } 7479 7480 boolean requestFocus(boolean temporary, CausedFocusEvent.Cause cause) { 7481 return requestFocusHelper(temporary, true, cause); 7482 } 7483 /** 7484 * Requests that this Component get the input focus, if this 7485 * Component's top-level ancestor is already the focused 7486 * Window. This component must be displayable, focusable, visible 7487 * and all of its ancestors (with the exception of the top-level 7488 * Window) must be visible for the request to be granted. Every 7489 * effort will be made to honor the request; however, in some 7490 * cases it may be impossible to do so. Developers must never 7491 * assume that this Component is the focus owner until this 7492 * Component receives a FOCUS_GAINED event. 7493 * <p> 7494 * This method returns a boolean value. If <code>false</code> is returned, 7495 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7496 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7497 * extraordinary event, such as disposal of the Component's peer, occurs 7498 * before the request can be granted by the native windowing system. Again, 7499 * while a return value of <code>true</code> indicates that the request is 7500 * likely to succeed, developers must never assume that this Component is 7501 * the focus owner until this Component receives a FOCUS_GAINED event. 7502 * <p> 7503 * This method cannot be used to set the focus owner to no Component at 7504 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner()</code> 7505 * instead. 7506 * <p> 7507 * The focus behavior of this method can be implemented uniformly across 7508 * platforms, and thus developers are strongly encouraged to use this 7509 * method over <code>requestFocus</code> when possible. Code which relies 7510 * on <code>requestFocus</code> may exhibit different focus behavior on 7511 * different platforms. 7512 * 7513 * <p>Note: Not all focus transfers result from invoking this method. As 7514 * such, a component may receive focus without this or any of the other 7515 * {@code requestFocus} methods of {@code Component} being invoked. 7516 * 7517 * @return <code>false</code> if the focus change request is guaranteed to 7518 * fail; <code>true</code> if it is likely to succeed 7519 * @see #requestFocus 7520 * @see java.awt.event.FocusEvent 7521 * @see #addFocusListener 7522 * @see #isFocusable 7523 * @see #isDisplayable 7524 * @see KeyboardFocusManager#clearGlobalFocusOwner 7525 * @since 1.4 7526 */ 7527 public boolean requestFocusInWindow() { 7528 return requestFocusHelper(false, false); 7529 } 7530 7531 boolean requestFocusInWindow(CausedFocusEvent.Cause cause) { 7532 return requestFocusHelper(false, false, cause); 7533 } 7534 7535 /** 7536 * Requests that this <code>Component</code> get the input focus, 7537 * if this <code>Component</code>'s top-level ancestor is already 7538 * the focused <code>Window</code>. This component must be 7539 * displayable, focusable, visible and all of its ancestors (with 7540 * the exception of the top-level Window) must be visible for the 7541 * request to be granted. Every effort will be made to honor the 7542 * request; however, in some cases it may be impossible to do 7543 * so. Developers must never assume that this component is the 7544 * focus owner until this component receives a FOCUS_GAINED event. 7545 * <p> 7546 * This method returns a boolean value. If <code>false</code> is returned, 7547 * the request is <b>guaranteed to fail</b>. If <code>true</code> is 7548 * returned, the request will succeed <b>unless</b> it is vetoed, or an 7549 * extraordinary event, such as disposal of the component's peer, occurs 7550 * before the request can be granted by the native windowing system. Again, 7551 * while a return value of <code>true</code> indicates that the request is 7552 * likely to succeed, developers must never assume that this component is 7553 * the focus owner until this component receives a FOCUS_GAINED event. 7554 * <p> 7555 * This method cannot be used to set the focus owner to no component at 7556 * all. Use <code>KeyboardFocusManager.clearGlobalFocusOwner</code> 7557 * instead. 7558 * <p> 7559 * The focus behavior of this method can be implemented uniformly across 7560 * platforms, and thus developers are strongly encouraged to use this 7561 * method over <code>requestFocus</code> when possible. Code which relies 7562 * on <code>requestFocus</code> may exhibit different focus behavior on 7563 * different platforms. 7564 * <p> 7565 * Every effort will be made to ensure that <code>FocusEvent</code>s 7566 * generated as a 7567 * result of this request will have the specified temporary value. However, 7568 * because specifying an arbitrary temporary state may not be implementable 7569 * on all native windowing systems, correct behavior for this method can be 7570 * guaranteed only for lightweight components. This method is not intended 7571 * for general use, but exists instead as a hook for lightweight component 7572 * libraries, such as Swing. 7573 * 7574 * <p>Note: Not all focus transfers result from invoking this method. As 7575 * such, a component may receive focus without this or any of the other 7576 * {@code requestFocus} methods of {@code Component} being invoked. 7577 * 7578 * @param temporary true if the focus change is temporary, 7579 * such as when the window loses the focus; for 7580 * more information on temporary focus changes see the 7581 *<a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a> 7582 * @return <code>false</code> if the focus change request is guaranteed to 7583 * fail; <code>true</code> if it is likely to succeed 7584 * @see #requestFocus 7585 * @see java.awt.event.FocusEvent 7586 * @see #addFocusListener 7587 * @see #isFocusable 7588 * @see #isDisplayable 7589 * @see KeyboardFocusManager#clearGlobalFocusOwner 7590 * @since 1.4 7591 */ 7592 protected boolean requestFocusInWindow(boolean temporary) { 7593 return requestFocusHelper(temporary, false); 7594 } 7595 7596 boolean requestFocusInWindow(boolean temporary, CausedFocusEvent.Cause cause) { 7597 return requestFocusHelper(temporary, false, cause); 7598 } 7599 7600 final boolean requestFocusHelper(boolean temporary, 7601 boolean focusedWindowChangeAllowed) { 7602 return requestFocusHelper(temporary, focusedWindowChangeAllowed, CausedFocusEvent.Cause.UNKNOWN); 7603 } 7604 7605 final boolean requestFocusHelper(boolean temporary, 7606 boolean focusedWindowChangeAllowed, 7607 CausedFocusEvent.Cause cause) 7608 { 7609 if (!isRequestFocusAccepted(temporary, focusedWindowChangeAllowed, cause)) { 7610 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7611 focusLog.finest("requestFocus is not accepted"); 7612 } 7613 return false; 7614 } 7615 7616 // Update most-recent map 7617 KeyboardFocusManager.setMostRecentFocusOwner(this); 7618 7619 Component window = this; 7620 while ( (window != null) && !(window instanceof Window)) { 7621 if (!window.isVisible()) { 7622 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7623 focusLog.finest("component is recurively invisible"); 7624 } 7625 return false; 7626 } 7627 window = window.parent; 7628 } 7629 7630 ComponentPeer peer = this.peer; 7631 Component heavyweight = (peer instanceof LightweightPeer) 7632 ? getNativeContainer() : this; 7633 if (heavyweight == null || !heavyweight.isVisible()) { 7634 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7635 focusLog.finest("Component is not a part of visible hierarchy"); 7636 } 7637 return false; 7638 } 7639 peer = heavyweight.peer; 7640 if (peer == null) { 7641 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7642 focusLog.finest("Peer is null"); 7643 } 7644 return false; 7645 } 7646 7647 // Focus this Component 7648 long time = EventQueue.getMostRecentEventTime(); 7649 boolean success = peer.requestFocus 7650 (this, temporary, focusedWindowChangeAllowed, time, cause); 7651 if (!success) { 7652 KeyboardFocusManager.getCurrentKeyboardFocusManager 7653 (appContext).dequeueKeyEvents(time, this); 7654 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7655 focusLog.finest("Peer request failed"); 7656 } 7657 } else { 7658 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7659 focusLog.finest("Pass for " + this); 7660 } 7661 } 7662 return success; 7663 } 7664 7665 private boolean isRequestFocusAccepted(boolean temporary, 7666 boolean focusedWindowChangeAllowed, 7667 CausedFocusEvent.Cause cause) 7668 { 7669 if (!isFocusable() || !isVisible()) { 7670 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7671 focusLog.finest("Not focusable or not visible"); 7672 } 7673 return false; 7674 } 7675 7676 ComponentPeer peer = this.peer; 7677 if (peer == null) { 7678 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7679 focusLog.finest("peer is null"); 7680 } 7681 return false; 7682 } 7683 7684 Window window = getContainingWindow(); 7685 if (window == null || !window.isFocusableWindow()) { 7686 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7687 focusLog.finest("Component doesn't have toplevel"); 7688 } 7689 return false; 7690 } 7691 7692 // We have passed all regular checks for focus request, 7693 // now let's call RequestFocusController and see what it says. 7694 Component focusOwner = KeyboardFocusManager.getMostRecentFocusOwner(window); 7695 if (focusOwner == null) { 7696 // sometimes most recent focus owner may be null, but focus owner is not 7697 // e.g. we reset most recent focus owner if user removes focus owner 7698 focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); 7699 if (focusOwner != null && focusOwner.getContainingWindow() != window) { 7700 focusOwner = null; 7701 } 7702 } 7703 7704 if (focusOwner == this || focusOwner == null) { 7705 // Controller is supposed to verify focus transfers and for this it 7706 // should know both from and to components. And it shouldn't verify 7707 // transfers from when these components are equal. 7708 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7709 focusLog.finest("focus owner is null or this"); 7710 } 7711 return true; 7712 } 7713 7714 if (CausedFocusEvent.Cause.ACTIVATION == cause) { 7715 // we shouldn't call RequestFocusController in case we are 7716 // in activation. We do request focus on component which 7717 // has got temporary focus lost and then on component which is 7718 // most recent focus owner. But most recent focus owner can be 7719 // changed by requestFocsuXXX() call only, so this transfer has 7720 // been already approved. 7721 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7722 focusLog.finest("cause is activation"); 7723 } 7724 return true; 7725 } 7726 7727 boolean ret = Component.requestFocusController.acceptRequestFocus(focusOwner, 7728 this, 7729 temporary, 7730 focusedWindowChangeAllowed, 7731 cause); 7732 if (focusLog.isLoggable(PlatformLogger.FINEST)) { 7733 focusLog.finest("RequestFocusController returns {0}", ret); 7734 } 7735 7736 return ret; 7737 } 7738 7739 private static RequestFocusController requestFocusController = new DummyRequestFocusController(); 7740 7741 // Swing access this method through reflection to implement InputVerifier's functionality. 7742 // Perhaps, we should make this method public (later ;) 7743 private static class DummyRequestFocusController implements RequestFocusController { 7744 public boolean acceptRequestFocus(Component from, Component to, 7745 boolean temporary, boolean focusedWindowChangeAllowed, 7746 CausedFocusEvent.Cause cause) 7747 { 7748 return true; 7749 } 7750 }; 7751 7752 synchronized static void setRequestFocusController(RequestFocusController requestController) 7753 { 7754 if (requestController == null) { 7755 requestFocusController = new DummyRequestFocusController(); 7756 } else { 7757 requestFocusController = requestController; 7758 } 7759 } 7760 7761 /** 7762 * Returns the Container which is the focus cycle root of this Component's 7763 * focus traversal cycle. Each focus traversal cycle has only a single 7764 * focus cycle root and each Component which is not a Container belongs to 7765 * only a single focus traversal cycle. Containers which are focus cycle 7766 * roots belong to two cycles: one rooted at the Container itself, and one 7767 * rooted at the Container's nearest focus-cycle-root ancestor. For such 7768 * Containers, this method will return the Container's nearest focus-cycle- 7769 * root ancestor. 7770 * 7771 * @return this Component's nearest focus-cycle-root ancestor 7772 * @see Container#isFocusCycleRoot() 7773 * @since 1.4 7774 */ 7775 public Container getFocusCycleRootAncestor() { 7776 Container rootAncestor = this.parent; 7777 while (rootAncestor != null && !rootAncestor.isFocusCycleRoot()) { 7778 rootAncestor = rootAncestor.parent; 7779 } 7780 return rootAncestor; 7781 } 7782 7783 /** 7784 * Returns whether the specified Container is the focus cycle root of this 7785 * Component's focus traversal cycle. Each focus traversal cycle has only 7786 * a single focus cycle root and each Component which is not a Container 7787 * belongs to only a single focus traversal cycle. 7788 * 7789 * @param container the Container to be tested 7790 * @return <code>true</code> if the specified Container is a focus-cycle- 7791 * root of this Component; <code>false</code> otherwise 7792 * @see Container#isFocusCycleRoot() 7793 * @since 1.4 7794 */ 7795 public boolean isFocusCycleRoot(Container container) { 7796 Container rootAncestor = getFocusCycleRootAncestor(); 7797 return (rootAncestor == container); 7798 } 7799 7800 Container getTraversalRoot() { 7801 return getFocusCycleRootAncestor(); 7802 } 7803 7804 /** 7805 * Transfers the focus to the next component, as though this Component were 7806 * the focus owner. 7807 * @see #requestFocus() 7808 * @since JDK1.1 7809 */ 7810 public void transferFocus() { 7811 nextFocus(); 7812 } 7813 7814 /** 7815 * @deprecated As of JDK version 1.1, 7816 * replaced by transferFocus(). 7817 */ 7818 @Deprecated 7819 public void nextFocus() { 7820 transferFocus(false); 7821 } 7822 7823 boolean transferFocus(boolean clearOnFailure) { 7824 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7825 focusLog.finer("clearOnFailure = " + clearOnFailure); 7826 } 7827 Component toFocus = getNextFocusCandidate(); 7828 boolean res = false; 7829 if (toFocus != null && !toFocus.isFocusOwner() && toFocus != this) { 7830 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_FORWARD); 7831 } 7832 if (clearOnFailure && !res) { 7833 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7834 focusLog.finer("clear global focus owner"); 7835 } 7836 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv(); 7837 } 7838 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7839 focusLog.finer("returning result: " + res); 7840 } 7841 return res; 7842 } 7843 7844 final Component getNextFocusCandidate() { 7845 Container rootAncestor = getTraversalRoot(); 7846 Component comp = this; 7847 while (rootAncestor != null && 7848 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 7849 { 7850 comp = rootAncestor; 7851 rootAncestor = comp.getFocusCycleRootAncestor(); 7852 } 7853 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7854 focusLog.finer("comp = " + comp + ", root = " + rootAncestor); 7855 } 7856 Component candidate = null; 7857 if (rootAncestor != null) { 7858 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 7859 Component toFocus = policy.getComponentAfter(rootAncestor, comp); 7860 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7861 focusLog.finer("component after is " + toFocus); 7862 } 7863 if (toFocus == null) { 7864 toFocus = policy.getDefaultComponent(rootAncestor); 7865 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7866 focusLog.finer("default component is " + toFocus); 7867 } 7868 } 7869 if (toFocus == null) { 7870 Applet applet = EmbeddedFrame.getAppletIfAncestorOf(this); 7871 if (applet != null) { 7872 toFocus = applet; 7873 } 7874 } 7875 candidate = toFocus; 7876 } 7877 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7878 focusLog.finer("Focus transfer candidate: " + candidate); 7879 } 7880 return candidate; 7881 } 7882 7883 /** 7884 * Transfers the focus to the previous component, as though this Component 7885 * were the focus owner. 7886 * @see #requestFocus() 7887 * @since 1.4 7888 */ 7889 public void transferFocusBackward() { 7890 transferFocusBackward(false); 7891 } 7892 7893 boolean transferFocusBackward(boolean clearOnFailure) { 7894 Container rootAncestor = getTraversalRoot(); 7895 Component comp = this; 7896 while (rootAncestor != null && 7897 !(rootAncestor.isShowing() && rootAncestor.canBeFocusOwner())) 7898 { 7899 comp = rootAncestor; 7900 rootAncestor = comp.getFocusCycleRootAncestor(); 7901 } 7902 boolean res = false; 7903 if (rootAncestor != null) { 7904 FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); 7905 Component toFocus = policy.getComponentBefore(rootAncestor, comp); 7906 if (toFocus == null) { 7907 toFocus = policy.getDefaultComponent(rootAncestor); 7908 } 7909 if (toFocus != null) { 7910 res = toFocus.requestFocusInWindow(CausedFocusEvent.Cause.TRAVERSAL_BACKWARD); 7911 } 7912 } 7913 if (clearOnFailure && !res) { 7914 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7915 focusLog.finer("clear global focus owner"); 7916 } 7917 KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwnerPriv(); 7918 } 7919 if (focusLog.isLoggable(PlatformLogger.FINER)) { 7920 focusLog.finer("returning result: " + res); 7921 } 7922 return res; 7923 } 7924 7925 /** 7926 * Transfers the focus up one focus traversal cycle. Typically, the focus 7927 * owner is set to this Component's focus cycle root, and the current focus 7928 * cycle root is set to the new focus owner's focus cycle root. If, 7929 * however, this Component's focus cycle root is a Window, then the focus 7930 * owner is set to the focus cycle root's default Component to focus, and 7931 * the current focus cycle root is unchanged. 7932 * 7933 * @see #requestFocus() 7934 * @see Container#isFocusCycleRoot() 7935 * @see Container#setFocusCycleRoot(boolean) 7936 * @since 1.4 7937 */ 7938 public void transferFocusUpCycle() { 7939 Container rootAncestor; 7940 for (rootAncestor = getFocusCycleRootAncestor(); 7941 rootAncestor != null && !(rootAncestor.isShowing() && 7942 rootAncestor.isFocusable() && 7943 rootAncestor.isEnabled()); 7944 rootAncestor = rootAncestor.getFocusCycleRootAncestor()) { 7945 } 7946 7947 if (rootAncestor != null) { 7948 Container rootAncestorRootAncestor = 7949 rootAncestor.getFocusCycleRootAncestor(); 7950 Container fcr = (rootAncestorRootAncestor != null) ? 7951 rootAncestorRootAncestor : rootAncestor; 7952 7953 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7954 setGlobalCurrentFocusCycleRootPriv(fcr); 7955 rootAncestor.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); 7956 } else { 7957 Window window = getContainingWindow(); 7958 7959 if (window != null) { 7960 Component toFocus = window.getFocusTraversalPolicy(). 7961 getDefaultComponent(window); 7962 if (toFocus != null) { 7963 KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7964 setGlobalCurrentFocusCycleRootPriv(window); 7965 toFocus.requestFocus(CausedFocusEvent.Cause.TRAVERSAL_UP); 7966 } 7967 } 7968 } 7969 } 7970 7971 /** 7972 * Returns <code>true</code> if this <code>Component</code> is the 7973 * focus owner. This method is obsolete, and has been replaced by 7974 * <code>isFocusOwner()</code>. 7975 * 7976 * @return <code>true</code> if this <code>Component</code> is the 7977 * focus owner; <code>false</code> otherwise 7978 * @since 1.2 7979 */ 7980 public boolean hasFocus() { 7981 return (KeyboardFocusManager.getCurrentKeyboardFocusManager(). 7982 getFocusOwner() == this); 7983 } 7984 7985 /** 7986 * Returns <code>true</code> if this <code>Component</code> is the 7987 * focus owner. 7988 * 7989 * @return <code>true</code> if this <code>Component</code> is the 7990 * focus owner; <code>false</code> otherwise 7991 * @since 1.4 7992 */ 7993 public boolean isFocusOwner() { 7994 return hasFocus(); 7995 } 7996 7997 /* 7998 * Used to disallow auto-focus-transfer on disposal of the focus owner 7999 * in the process of disposing its parent container. 8000 */ 8001 private boolean autoFocusTransferOnDisposal = true; 8002 8003 void setAutoFocusTransferOnDisposal(boolean value) { 8004 autoFocusTransferOnDisposal = value; 8005 } 8006 8007 boolean isAutoFocusTransferOnDisposal() { 8008 return autoFocusTransferOnDisposal; 8009 } 8010 8011 /** 8012 * Adds the specified popup menu to the component. 8013 * @param popup the popup menu to be added to the component. 8014 * @see #remove(MenuComponent) 8015 * @exception NullPointerException if {@code popup} is {@code null} 8016 * @since JDK1.1 8017 */ 8018 public void add(PopupMenu popup) { 8019 synchronized (getTreeLock()) { 8020 if (popup.parent != null) { 8021 popup.parent.remove(popup); 8022 } 8023 if (popups == null) { 8024 popups = new Vector<PopupMenu>(); 8025 } 8026 popups.addElement(popup); 8027 popup.parent = this; 8028 8029 if (peer != null) { 8030 if (popup.peer == null) { 8031 popup.addNotify(); 8032 } 8033 } 8034 } 8035 } 8036 8037 /** 8038 * Removes the specified popup menu from the component. 8039 * @param popup the popup menu to be removed 8040 * @see #add(PopupMenu) 8041 * @since JDK1.1 8042 */ 8043 @SuppressWarnings("unchecked") 8044 public void remove(MenuComponent popup) { 8045 synchronized (getTreeLock()) { 8046 if (popups == null) { 8047 return; 8048 } 8049 int index = popups.indexOf(popup); 8050 if (index >= 0) { 8051 PopupMenu pmenu = (PopupMenu)popup; 8052 if (pmenu.peer != null) { 8053 pmenu.removeNotify(); 8054 } 8055 pmenu.parent = null; 8056 popups.removeElementAt(index); 8057 if (popups.size() == 0) { 8058 popups = null; 8059 } 8060 } 8061 } 8062 } 8063 8064 /** 8065 * Returns a string representing the state of this component. This 8066 * method is intended to be used only for debugging purposes, and the 8067 * content and format of the returned string may vary between 8068 * implementations. The returned string may be empty but may not be 8069 * <code>null</code>. 8070 * 8071 * @return a string representation of this component's state 8072 * @since JDK1.0 8073 */ 8074 protected String paramString() { 8075 String thisName = getName(); 8076 String str = (thisName != null? thisName : "") + "," + x + "," + y + "," + width + "x" + height; 8077 if (!isValid()) { 8078 str += ",invalid"; 8079 } 8080 if (!visible) { 8081 str += ",hidden"; 8082 } 8083 if (!enabled) { 8084 str += ",disabled"; 8085 } 8086 return str; 8087 } 8088 8089 /** 8090 * Returns a string representation of this component and its values. 8091 * @return a string representation of this component 8092 * @since JDK1.0 8093 */ 8094 public String toString() { 8095 return getClass().getName() + "[" + paramString() + "]"; 8096 } 8097 8098 /** 8099 * Prints a listing of this component to the standard system output 8100 * stream <code>System.out</code>. 8101 * @see java.lang.System#out 8102 * @since JDK1.0 8103 */ 8104 public void list() { 8105 list(System.out, 0); 8106 } 8107 8108 /** 8109 * Prints a listing of this component to the specified output 8110 * stream. 8111 * @param out a print stream 8112 * @throws NullPointerException if {@code out} is {@code null} 8113 * @since JDK1.0 8114 */ 8115 public void list(PrintStream out) { 8116 list(out, 0); 8117 } 8118 8119 /** 8120 * Prints out a list, starting at the specified indentation, to the 8121 * specified print stream. 8122 * @param out a print stream 8123 * @param indent number of spaces to indent 8124 * @see java.io.PrintStream#println(java.lang.Object) 8125 * @throws NullPointerException if {@code out} is {@code null} 8126 * @since JDK1.0 8127 */ 8128 public void list(PrintStream out, int indent) { 8129 for (int i = 0 ; i < indent ; i++) { 8130 out.print(" "); 8131 } 8132 out.println(this); 8133 } 8134 8135 /** 8136 * Prints a listing to the specified print writer. 8137 * @param out the print writer to print to 8138 * @throws NullPointerException if {@code out} is {@code null} 8139 * @since JDK1.1 8140 */ 8141 public void list(PrintWriter out) { 8142 list(out, 0); 8143 } 8144 8145 /** 8146 * Prints out a list, starting at the specified indentation, to 8147 * the specified print writer. 8148 * @param out the print writer to print to 8149 * @param indent the number of spaces to indent 8150 * @throws NullPointerException if {@code out} is {@code null} 8151 * @see java.io.PrintStream#println(java.lang.Object) 8152 * @since JDK1.1 8153 */ 8154 public void list(PrintWriter out, int indent) { 8155 for (int i = 0 ; i < indent ; i++) { 8156 out.print(" "); 8157 } 8158 out.println(this); 8159 } 8160 8161 /* 8162 * Fetches the native container somewhere higher up in the component 8163 * tree that contains this component. 8164 */ 8165 Container getNativeContainer() { 8166 Container p = parent; 8167 while (p != null && p.peer instanceof LightweightPeer) { 8168 p = p.getParent_NoClientCode(); 8169 } 8170 return p; 8171 } 8172 8173 /** 8174 * Adds a PropertyChangeListener to the listener list. The listener is 8175 * registered for all bound properties of this class, including the 8176 * following: 8177 * <ul> 8178 * <li>this Component's font ("font")</li> 8179 * <li>this Component's background color ("background")</li> 8180 * <li>this Component's foreground color ("foreground")</li> 8181 * <li>this Component's focusability ("focusable")</li> 8182 * <li>this Component's focus traversal keys enabled state 8183 * ("focusTraversalKeysEnabled")</li> 8184 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 8185 * ("forwardFocusTraversalKeys")</li> 8186 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 8187 * ("backwardFocusTraversalKeys")</li> 8188 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 8189 * ("upCycleFocusTraversalKeys")</li> 8190 * <li>this Component's preferred size ("preferredSize")</li> 8191 * <li>this Component's minimum size ("minimumSize")</li> 8192 * <li>this Component's maximum size ("maximumSize")</li> 8193 * <li>this Component's name ("name")</li> 8194 * </ul> 8195 * Note that if this <code>Component</code> is inheriting a bound property, then no 8196 * event will be fired in response to a change in the inherited property. 8197 * <p> 8198 * If <code>listener</code> is <code>null</code>, 8199 * no exception is thrown and no action is performed. 8200 * 8201 * @param listener the property change listener to be added 8202 * 8203 * @see #removePropertyChangeListener 8204 * @see #getPropertyChangeListeners 8205 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8206 */ 8207 public void addPropertyChangeListener( 8208 PropertyChangeListener listener) { 8209 synchronized (getObjectLock()) { 8210 if (listener == null) { 8211 return; 8212 } 8213 if (changeSupport == null) { 8214 changeSupport = new PropertyChangeSupport(this); 8215 } 8216 changeSupport.addPropertyChangeListener(listener); 8217 } 8218 } 8219 8220 /** 8221 * Removes a PropertyChangeListener from the listener list. This method 8222 * should be used to remove PropertyChangeListeners that were registered 8223 * for all bound properties of this class. 8224 * <p> 8225 * If listener is null, no exception is thrown and no action is performed. 8226 * 8227 * @param listener the PropertyChangeListener to be removed 8228 * 8229 * @see #addPropertyChangeListener 8230 * @see #getPropertyChangeListeners 8231 * @see #removePropertyChangeListener(java.lang.String,java.beans.PropertyChangeListener) 8232 */ 8233 public void removePropertyChangeListener( 8234 PropertyChangeListener listener) { 8235 synchronized (getObjectLock()) { 8236 if (listener == null || changeSupport == null) { 8237 return; 8238 } 8239 changeSupport.removePropertyChangeListener(listener); 8240 } 8241 } 8242 8243 /** 8244 * Returns an array of all the property change listeners 8245 * registered on this component. 8246 * 8247 * @return all of this component's <code>PropertyChangeListener</code>s 8248 * or an empty array if no property change 8249 * listeners are currently registered 8250 * 8251 * @see #addPropertyChangeListener 8252 * @see #removePropertyChangeListener 8253 * @see #getPropertyChangeListeners(java.lang.String) 8254 * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners 8255 * @since 1.4 8256 */ 8257 public PropertyChangeListener[] getPropertyChangeListeners() { 8258 synchronized (getObjectLock()) { 8259 if (changeSupport == null) { 8260 return new PropertyChangeListener[0]; 8261 } 8262 return changeSupport.getPropertyChangeListeners(); 8263 } 8264 } 8265 8266 /** 8267 * Adds a PropertyChangeListener to the listener list for a specific 8268 * property. The specified property may be user-defined, or one of the 8269 * following: 8270 * <ul> 8271 * <li>this Component's font ("font")</li> 8272 * <li>this Component's background color ("background")</li> 8273 * <li>this Component's foreground color ("foreground")</li> 8274 * <li>this Component's focusability ("focusable")</li> 8275 * <li>this Component's focus traversal keys enabled state 8276 * ("focusTraversalKeysEnabled")</li> 8277 * <li>this Component's Set of FORWARD_TRAVERSAL_KEYS 8278 * ("forwardFocusTraversalKeys")</li> 8279 * <li>this Component's Set of BACKWARD_TRAVERSAL_KEYS 8280 * ("backwardFocusTraversalKeys")</li> 8281 * <li>this Component's Set of UP_CYCLE_TRAVERSAL_KEYS 8282 * ("upCycleFocusTraversalKeys")</li> 8283 * </ul> 8284 * Note that if this <code>Component</code> is inheriting a bound property, then no 8285 * event will be fired in response to a change in the inherited property. 8286 * <p> 8287 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, 8288 * no exception is thrown and no action is taken. 8289 * 8290 * @param propertyName one of the property names listed above 8291 * @param listener the property change listener to be added 8292 * 8293 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8294 * @see #getPropertyChangeListeners(java.lang.String) 8295 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8296 */ 8297 public void addPropertyChangeListener( 8298 String propertyName, 8299 PropertyChangeListener listener) { 8300 synchronized (getObjectLock()) { 8301 if (listener == null) { 8302 return; 8303 } 8304 if (changeSupport == null) { 8305 changeSupport = new PropertyChangeSupport(this); 8306 } 8307 changeSupport.addPropertyChangeListener(propertyName, listener); 8308 } 8309 } 8310 8311 /** 8312 * Removes a <code>PropertyChangeListener</code> from the listener 8313 * list for a specific property. This method should be used to remove 8314 * <code>PropertyChangeListener</code>s 8315 * that were registered for a specific bound property. 8316 * <p> 8317 * If <code>propertyName</code> or <code>listener</code> is <code>null</code>, 8318 * no exception is thrown and no action is taken. 8319 * 8320 * @param propertyName a valid property name 8321 * @param listener the PropertyChangeListener to be removed 8322 * 8323 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8324 * @see #getPropertyChangeListeners(java.lang.String) 8325 * @see #removePropertyChangeListener(java.beans.PropertyChangeListener) 8326 */ 8327 public void removePropertyChangeListener( 8328 String propertyName, 8329 PropertyChangeListener listener) { 8330 synchronized (getObjectLock()) { 8331 if (listener == null || changeSupport == null) { 8332 return; 8333 } 8334 changeSupport.removePropertyChangeListener(propertyName, listener); 8335 } 8336 } 8337 8338 /** 8339 * Returns an array of all the listeners which have been associated 8340 * with the named property. 8341 * 8342 * @return all of the <code>PropertyChangeListener</code>s associated with 8343 * the named property; if no such listeners have been added or 8344 * if <code>propertyName</code> is <code>null</code>, an empty 8345 * array is returned 8346 * 8347 * @see #addPropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8348 * @see #removePropertyChangeListener(java.lang.String, java.beans.PropertyChangeListener) 8349 * @see #getPropertyChangeListeners 8350 * @since 1.4 8351 */ 8352 public PropertyChangeListener[] getPropertyChangeListeners( 8353 String propertyName) { 8354 synchronized (getObjectLock()) { 8355 if (changeSupport == null) { 8356 return new PropertyChangeListener[0]; 8357 } 8358 return changeSupport.getPropertyChangeListeners(propertyName); 8359 } 8360 } 8361 8362 /** 8363 * Support for reporting bound property changes for Object properties. 8364 * This method can be called when a bound property has changed and it will 8365 * send the appropriate PropertyChangeEvent to any registered 8366 * PropertyChangeListeners. 8367 * 8368 * @param propertyName the property whose value has changed 8369 * @param oldValue the property's previous value 8370 * @param newValue the property's new value 8371 */ 8372 protected void firePropertyChange(String propertyName, 8373 Object oldValue, Object newValue) { 8374 PropertyChangeSupport changeSupport; 8375 synchronized (getObjectLock()) { 8376 changeSupport = this.changeSupport; 8377 } 8378 if (changeSupport == null || 8379 (oldValue != null && newValue != null && oldValue.equals(newValue))) { 8380 return; 8381 } 8382 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8383 } 8384 8385 /** 8386 * Support for reporting bound property changes for boolean properties. 8387 * This method can be called when a bound property has changed and it will 8388 * send the appropriate PropertyChangeEvent to any registered 8389 * PropertyChangeListeners. 8390 * 8391 * @param propertyName the property whose value has changed 8392 * @param oldValue the property's previous value 8393 * @param newValue the property's new value 8394 * @since 1.4 8395 */ 8396 protected void firePropertyChange(String propertyName, 8397 boolean oldValue, boolean newValue) { 8398 PropertyChangeSupport changeSupport = this.changeSupport; 8399 if (changeSupport == null || oldValue == newValue) { 8400 return; 8401 } 8402 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8403 } 8404 8405 /** 8406 * Support for reporting bound property changes for integer properties. 8407 * This method can be called when a bound property has changed and it will 8408 * send the appropriate PropertyChangeEvent to any registered 8409 * PropertyChangeListeners. 8410 * 8411 * @param propertyName the property whose value has changed 8412 * @param oldValue the property's previous value 8413 * @param newValue the property's new value 8414 * @since 1.4 8415 */ 8416 protected void firePropertyChange(String propertyName, 8417 int oldValue, int newValue) { 8418 PropertyChangeSupport changeSupport = this.changeSupport; 8419 if (changeSupport == null || oldValue == newValue) { 8420 return; 8421 } 8422 changeSupport.firePropertyChange(propertyName, oldValue, newValue); 8423 } 8424 8425 /** 8426 * Reports a bound property change. 8427 * 8428 * @param propertyName the programmatic name of the property 8429 * that was changed 8430 * @param oldValue the old value of the property (as a byte) 8431 * @param newValue the new value of the property (as a byte) 8432 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8433 * java.lang.Object) 8434 * @since 1.5 8435 */ 8436 public void firePropertyChange(String propertyName, byte oldValue, byte newValue) { 8437 if (changeSupport == null || oldValue == newValue) { 8438 return; 8439 } 8440 firePropertyChange(propertyName, Byte.valueOf(oldValue), Byte.valueOf(newValue)); 8441 } 8442 8443 /** 8444 * Reports a bound property change. 8445 * 8446 * @param propertyName the programmatic name of the property 8447 * that was changed 8448 * @param oldValue the old value of the property (as a char) 8449 * @param newValue the new value of the property (as a char) 8450 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8451 * java.lang.Object) 8452 * @since 1.5 8453 */ 8454 public void firePropertyChange(String propertyName, char oldValue, char newValue) { 8455 if (changeSupport == null || oldValue == newValue) { 8456 return; 8457 } 8458 firePropertyChange(propertyName, new Character(oldValue), new Character(newValue)); 8459 } 8460 8461 /** 8462 * Reports a bound property change. 8463 * 8464 * @param propertyName the programmatic name of the property 8465 * that was changed 8466 * @param oldValue the old value of the property (as a short) 8467 * @param newValue the old value of the property (as a short) 8468 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8469 * java.lang.Object) 8470 * @since 1.5 8471 */ 8472 public void firePropertyChange(String propertyName, short oldValue, short newValue) { 8473 if (changeSupport == null || oldValue == newValue) { 8474 return; 8475 } 8476 firePropertyChange(propertyName, Short.valueOf(oldValue), Short.valueOf(newValue)); 8477 } 8478 8479 8480 /** 8481 * Reports a bound property change. 8482 * 8483 * @param propertyName the programmatic name of the property 8484 * that was changed 8485 * @param oldValue the old value of the property (as a long) 8486 * @param newValue the new value of the property (as a long) 8487 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8488 * java.lang.Object) 8489 * @since 1.5 8490 */ 8491 public void firePropertyChange(String propertyName, long oldValue, long newValue) { 8492 if (changeSupport == null || oldValue == newValue) { 8493 return; 8494 } 8495 firePropertyChange(propertyName, Long.valueOf(oldValue), Long.valueOf(newValue)); 8496 } 8497 8498 /** 8499 * Reports a bound property change. 8500 * 8501 * @param propertyName the programmatic name of the property 8502 * that was changed 8503 * @param oldValue the old value of the property (as a float) 8504 * @param newValue the new value of the property (as a float) 8505 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8506 * java.lang.Object) 8507 * @since 1.5 8508 */ 8509 public void firePropertyChange(String propertyName, float oldValue, float newValue) { 8510 if (changeSupport == null || oldValue == newValue) { 8511 return; 8512 } 8513 firePropertyChange(propertyName, Float.valueOf(oldValue), Float.valueOf(newValue)); 8514 } 8515 8516 /** 8517 * Reports a bound property change. 8518 * 8519 * @param propertyName the programmatic name of the property 8520 * that was changed 8521 * @param oldValue the old value of the property (as a double) 8522 * @param newValue the new value of the property (as a double) 8523 * @see #firePropertyChange(java.lang.String, java.lang.Object, 8524 * java.lang.Object) 8525 * @since 1.5 8526 */ 8527 public void firePropertyChange(String propertyName, double oldValue, double newValue) { 8528 if (changeSupport == null || oldValue == newValue) { 8529 return; 8530 } 8531 firePropertyChange(propertyName, Double.valueOf(oldValue), Double.valueOf(newValue)); 8532 } 8533 8534 8535 // Serialization support. 8536 8537 /** 8538 * Component Serialized Data Version. 8539 * 8540 * @serial 8541 */ 8542 private int componentSerializedDataVersion = 4; 8543 8544 /** 8545 * This hack is for Swing serialization. It will invoke 8546 * the Swing package private method <code>compWriteObjectNotify</code>. 8547 */ 8548 private void doSwingSerialization() { 8549 Package swingPackage = Package.getPackage("javax.swing"); 8550 // For Swing serialization to correctly work Swing needs to 8551 // be notified before Component does it's serialization. This 8552 // hack accomodates this. 8553 // 8554 // Swing classes MUST be loaded by the bootstrap class loader, 8555 // otherwise we don't consider them. 8556 for (Class<?> klass = Component.this.getClass(); klass != null; 8557 klass = klass.getSuperclass()) { 8558 if (klass.getPackage() == swingPackage && 8559 klass.getClassLoader() == null) { 8560 final Class<?> swingClass = klass; 8561 // Find the first override of the compWriteObjectNotify method 8562 Method[] methods = AccessController.doPrivileged( 8563 new PrivilegedAction<Method[]>() { 8564 public Method[] run() { 8565 return swingClass.getDeclaredMethods(); 8566 } 8567 }); 8568 for (int counter = methods.length - 1; counter >= 0; 8569 counter--) { 8570 final Method method = methods[counter]; 8571 if (method.getName().equals("compWriteObjectNotify")){ 8572 // We found it, use doPrivileged to make it accessible 8573 // to use. 8574 AccessController.doPrivileged(new PrivilegedAction<Void>() { 8575 public Void run() { 8576 method.setAccessible(true); 8577 return null; 8578 } 8579 }); 8580 // Invoke the method 8581 try { 8582 method.invoke(this, (Object[]) null); 8583 } catch (IllegalAccessException iae) { 8584 } catch (InvocationTargetException ite) { 8585 } 8586 // We're done, bail. 8587 return; 8588 } 8589 } 8590 } 8591 } 8592 } 8593 8594 /** 8595 * Writes default serializable fields to stream. Writes 8596 * a variety of serializable listeners as optional data. 8597 * The non-serializable listeners are detected and 8598 * no attempt is made to serialize them. 8599 * 8600 * @param s the <code>ObjectOutputStream</code> to write 8601 * @serialData <code>null</code> terminated sequence of 8602 * 0 or more pairs; the pair consists of a <code>String</code> 8603 * and an <code>Object</code>; the <code>String</code> indicates 8604 * the type of object and is one of the following (as of 1.4): 8605 * <code>componentListenerK</code> indicating an 8606 * <code>ComponentListener</code> object; 8607 * <code>focusListenerK</code> indicating an 8608 * <code>FocusListener</code> object; 8609 * <code>keyListenerK</code> indicating an 8610 * <code>KeyListener</code> object; 8611 * <code>mouseListenerK</code> indicating an 8612 * <code>MouseListener</code> object; 8613 * <code>mouseMotionListenerK</code> indicating an 8614 * <code>MouseMotionListener</code> object; 8615 * <code>inputMethodListenerK</code> indicating an 8616 * <code>InputMethodListener</code> object; 8617 * <code>hierarchyListenerK</code> indicating an 8618 * <code>HierarchyListener</code> object; 8619 * <code>hierarchyBoundsListenerK</code> indicating an 8620 * <code>HierarchyBoundsListener</code> object; 8621 * <code>mouseWheelListenerK</code> indicating an 8622 * <code>MouseWheelListener</code> object 8623 * @serialData an optional <code>ComponentOrientation</code> 8624 * (after <code>inputMethodListener</code>, as of 1.2) 8625 * 8626 * @see AWTEventMulticaster#save(java.io.ObjectOutputStream, java.lang.String, java.util.EventListener) 8627 * @see #componentListenerK 8628 * @see #focusListenerK 8629 * @see #keyListenerK 8630 * @see #mouseListenerK 8631 * @see #mouseMotionListenerK 8632 * @see #inputMethodListenerK 8633 * @see #hierarchyListenerK 8634 * @see #hierarchyBoundsListenerK 8635 * @see #mouseWheelListenerK 8636 * @see #readObject(ObjectInputStream) 8637 */ 8638 private void writeObject(ObjectOutputStream s) 8639 throws IOException 8640 { 8641 doSwingSerialization(); 8642 8643 s.defaultWriteObject(); 8644 8645 AWTEventMulticaster.save(s, componentListenerK, componentListener); 8646 AWTEventMulticaster.save(s, focusListenerK, focusListener); 8647 AWTEventMulticaster.save(s, keyListenerK, keyListener); 8648 AWTEventMulticaster.save(s, mouseListenerK, mouseListener); 8649 AWTEventMulticaster.save(s, mouseMotionListenerK, mouseMotionListener); 8650 AWTEventMulticaster.save(s, inputMethodListenerK, inputMethodListener); 8651 8652 s.writeObject(null); 8653 s.writeObject(componentOrientation); 8654 8655 AWTEventMulticaster.save(s, hierarchyListenerK, hierarchyListener); 8656 AWTEventMulticaster.save(s, hierarchyBoundsListenerK, 8657 hierarchyBoundsListener); 8658 s.writeObject(null); 8659 8660 AWTEventMulticaster.save(s, mouseWheelListenerK, mouseWheelListener); 8661 s.writeObject(null); 8662 8663 } 8664 8665 /** 8666 * Reads the <code>ObjectInputStream</code> and if it isn't 8667 * <code>null</code> adds a listener to receive a variety 8668 * of events fired by the component. 8669 * Unrecognized keys or values will be ignored. 8670 * 8671 * @param s the <code>ObjectInputStream</code> to read 8672 * @see #writeObject(ObjectOutputStream) 8673 */ 8674 private void readObject(ObjectInputStream s) 8675 throws ClassNotFoundException, IOException 8676 { 8677 objectLock = new Object(); 8678 8679 acc = AccessController.getContext(); 8680 8681 s.defaultReadObject(); 8682 8683 appContext = AppContext.getAppContext(); 8684 coalescingEnabled = checkCoalescing(); 8685 if (componentSerializedDataVersion < 4) { 8686 // These fields are non-transient and rely on default 8687 // serialization. However, the default values are insufficient, 8688 // so we need to set them explicitly for object data streams prior 8689 // to 1.4. 8690 focusable = true; 8691 isFocusTraversableOverridden = FOCUS_TRAVERSABLE_UNKNOWN; 8692 initializeFocusTraversalKeys(); 8693 focusTraversalKeysEnabled = true; 8694 } 8695 8696 Object keyOrNull; 8697 while(null != (keyOrNull = s.readObject())) { 8698 String key = ((String)keyOrNull).intern(); 8699 8700 if (componentListenerK == key) 8701 addComponentListener((ComponentListener)(s.readObject())); 8702 8703 else if (focusListenerK == key) 8704 addFocusListener((FocusListener)(s.readObject())); 8705 8706 else if (keyListenerK == key) 8707 addKeyListener((KeyListener)(s.readObject())); 8708 8709 else if (mouseListenerK == key) 8710 addMouseListener((MouseListener)(s.readObject())); 8711 8712 else if (mouseMotionListenerK == key) 8713 addMouseMotionListener((MouseMotionListener)(s.readObject())); 8714 8715 else if (inputMethodListenerK == key) 8716 addInputMethodListener((InputMethodListener)(s.readObject())); 8717 8718 else // skip value for unrecognized key 8719 s.readObject(); 8720 8721 } 8722 8723 // Read the component's orientation if it's present 8724 Object orient = null; 8725 8726 try { 8727 orient = s.readObject(); 8728 } catch (java.io.OptionalDataException e) { 8729 // JDK 1.1 instances will not have this optional data. 8730 // e.eof will be true to indicate that there is no more 8731 // data available for this object. 8732 // If e.eof is not true, throw the exception as it 8733 // might have been caused by reasons unrelated to 8734 // componentOrientation. 8735 8736 if (!e.eof) { 8737 throw (e); 8738 } 8739 } 8740 8741 if (orient != null) { 8742 componentOrientation = (ComponentOrientation)orient; 8743 } else { 8744 componentOrientation = ComponentOrientation.UNKNOWN; 8745 } 8746 8747 try { 8748 while(null != (keyOrNull = s.readObject())) { 8749 String key = ((String)keyOrNull).intern(); 8750 8751 if (hierarchyListenerK == key) { 8752 addHierarchyListener((HierarchyListener)(s.readObject())); 8753 } 8754 else if (hierarchyBoundsListenerK == key) { 8755 addHierarchyBoundsListener((HierarchyBoundsListener) 8756 (s.readObject())); 8757 } 8758 else { 8759 // skip value for unrecognized key 8760 s.readObject(); 8761 } 8762 } 8763 } catch (java.io.OptionalDataException e) { 8764 // JDK 1.1/1.2 instances will not have this optional data. 8765 // e.eof will be true to indicate that there is no more 8766 // data available for this object. 8767 // If e.eof is not true, throw the exception as it 8768 // might have been caused by reasons unrelated to 8769 // hierarchy and hierarchyBounds listeners. 8770 8771 if (!e.eof) { 8772 throw (e); 8773 } 8774 } 8775 8776 try { 8777 while (null != (keyOrNull = s.readObject())) { 8778 String key = ((String)keyOrNull).intern(); 8779 8780 if (mouseWheelListenerK == key) { 8781 addMouseWheelListener((MouseWheelListener)(s.readObject())); 8782 } 8783 else { 8784 // skip value for unrecognized key 8785 s.readObject(); 8786 } 8787 } 8788 } catch (java.io.OptionalDataException e) { 8789 // pre-1.3 instances will not have this optional data. 8790 // e.eof will be true to indicate that there is no more 8791 // data available for this object. 8792 // If e.eof is not true, throw the exception as it 8793 // might have been caused by reasons unrelated to 8794 // mouse wheel listeners 8795 8796 if (!e.eof) { 8797 throw (e); 8798 } 8799 } 8800 8801 if (popups != null) { 8802 int npopups = popups.size(); 8803 for (int i = 0 ; i < npopups ; i++) { 8804 PopupMenu popup = popups.elementAt(i); 8805 popup.parent = this; 8806 } 8807 } 8808 } 8809 8810 /** 8811 * Sets the language-sensitive orientation that is to be used to order 8812 * the elements or text within this component. Language-sensitive 8813 * <code>LayoutManager</code> and <code>Component</code> 8814 * subclasses will use this property to 8815 * determine how to lay out and draw components. 8816 * <p> 8817 * At construction time, a component's orientation is set to 8818 * <code>ComponentOrientation.UNKNOWN</code>, 8819 * indicating that it has not been specified 8820 * explicitly. The UNKNOWN orientation behaves the same as 8821 * <code>ComponentOrientation.LEFT_TO_RIGHT</code>. 8822 * <p> 8823 * To set the orientation of a single component, use this method. 8824 * To set the orientation of an entire component 8825 * hierarchy, use 8826 * {@link #applyComponentOrientation applyComponentOrientation}. 8827 * <p> 8828 * This method changes layout-related information, and therefore, 8829 * invalidates the component hierarchy. 8830 * 8831 * 8832 * @see ComponentOrientation 8833 * @see #invalidate 8834 * 8835 * @author Laura Werner, IBM 8836 * @beaninfo 8837 * bound: true 8838 */ 8839 public void setComponentOrientation(ComponentOrientation o) { 8840 ComponentOrientation oldValue = componentOrientation; 8841 componentOrientation = o; 8842 8843 // This is a bound property, so report the change to 8844 // any registered listeners. (Cheap if there are none.) 8845 firePropertyChange("componentOrientation", oldValue, o); 8846 8847 // This could change the preferred size of the Component. 8848 invalidateIfValid(); 8849 } 8850 8851 /** 8852 * Retrieves the language-sensitive orientation that is to be used to order 8853 * the elements or text within this component. <code>LayoutManager</code> 8854 * and <code>Component</code> 8855 * subclasses that wish to respect orientation should call this method to 8856 * get the component's orientation before performing layout or drawing. 8857 * 8858 * @see ComponentOrientation 8859 * 8860 * @author Laura Werner, IBM 8861 */ 8862 public ComponentOrientation getComponentOrientation() { 8863 return componentOrientation; 8864 } 8865 8866 /** 8867 * Sets the <code>ComponentOrientation</code> property of this component 8868 * and all components contained within it. 8869 * <p> 8870 * This method changes layout-related information, and therefore, 8871 * invalidates the component hierarchy. 8872 * 8873 * 8874 * @param orientation the new component orientation of this component and 8875 * the components contained within it. 8876 * @exception NullPointerException if <code>orientation</code> is null. 8877 * @see #setComponentOrientation 8878 * @see #getComponentOrientation 8879 * @see #invalidate 8880 * @since 1.4 8881 */ 8882 public void applyComponentOrientation(ComponentOrientation orientation) { 8883 if (orientation == null) { 8884 throw new NullPointerException(); 8885 } 8886 setComponentOrientation(orientation); 8887 } 8888 8889 final boolean canBeFocusOwner() { 8890 // It is enabled, visible, focusable. 8891 if (isEnabled() && isDisplayable() && isVisible() && isFocusable()) { 8892 return true; 8893 } 8894 return false; 8895 } 8896 8897 /** 8898 * Checks that this component meets the prerequesites to be focus owner: 8899 * - it is enabled, visible, focusable 8900 * - it's parents are all enabled and showing 8901 * - top-level window is focusable 8902 * - if focus cycle root has DefaultFocusTraversalPolicy then it also checks that this policy accepts 8903 * this component as focus owner 8904 * @since 1.5 8905 */ 8906 final boolean canBeFocusOwnerRecursively() { 8907 // - it is enabled, visible, focusable 8908 if (!canBeFocusOwner()) { 8909 return false; 8910 } 8911 8912 // - it's parents are all enabled and showing 8913 synchronized(getTreeLock()) { 8914 if (parent != null) { 8915 return parent.canContainFocusOwner(this); 8916 } 8917 } 8918 return true; 8919 } 8920 8921 /** 8922 * Fix the location of the HW component in a LW container hierarchy. 8923 */ 8924 final void relocateComponent() { 8925 synchronized (getTreeLock()) { 8926 if (peer == null) { 8927 return; 8928 } 8929 int nativeX = x; 8930 int nativeY = y; 8931 for (Component cont = getContainer(); 8932 cont != null && cont.isLightweight(); 8933 cont = cont.getContainer()) 8934 { 8935 nativeX += cont.x; 8936 nativeY += cont.y; 8937 } 8938 peer.setBounds(nativeX, nativeY, width, height, 8939 ComponentPeer.SET_LOCATION); 8940 } 8941 } 8942 8943 /** 8944 * Returns the <code>Window</code> ancestor of the component. 8945 * @return Window ancestor of the component or component by itself if it is Window; 8946 * null, if component is not a part of window hierarchy 8947 */ 8948 Window getContainingWindow() { 8949 return SunToolkit.getContainingWindow(this); 8950 } 8951 8952 /** 8953 * Initialize JNI field and method IDs 8954 */ 8955 private static native void initIDs(); 8956 8957 /* 8958 * --- Accessibility Support --- 8959 * 8960 * Component will contain all of the methods in interface Accessible, 8961 * though it won't actually implement the interface - that will be up 8962 * to the individual objects which extend Component. 8963 */ 8964 8965 AccessibleContext accessibleContext = null; 8966 8967 /** 8968 * Gets the <code>AccessibleContext</code> associated 8969 * with this <code>Component</code>. 8970 * The method implemented by this base 8971 * class returns null. Classes that extend <code>Component</code> 8972 * should implement this method to return the 8973 * <code>AccessibleContext</code> associated with the subclass. 8974 * 8975 * 8976 * @return the <code>AccessibleContext</code> of this 8977 * <code>Component</code> 8978 * @since 1.3 8979 */ 8980 public AccessibleContext getAccessibleContext() { 8981 return accessibleContext; 8982 } 8983 8984 /** 8985 * Inner class of Component used to provide default support for 8986 * accessibility. This class is not meant to be used directly by 8987 * application developers, but is instead meant only to be 8988 * subclassed by component developers. 8989 * <p> 8990 * The class used to obtain the accessible role for this object. 8991 * @since 1.3 8992 */ 8993 protected abstract class AccessibleAWTComponent extends AccessibleContext 8994 implements Serializable, AccessibleComponent { 8995 8996 private static final long serialVersionUID = 642321655757800191L; 8997 8998 /** 8999 * Though the class is abstract, this should be called by 9000 * all sub-classes. 9001 */ 9002 protected AccessibleAWTComponent() { 9003 } 9004 9005 protected ComponentListener accessibleAWTComponentHandler = null; 9006 protected FocusListener accessibleAWTFocusHandler = null; 9007 9008 /** 9009 * Fire PropertyChange listener, if one is registered, 9010 * when shown/hidden.. 9011 * @since 1.3 9012 */ 9013 protected class AccessibleAWTComponentHandler implements ComponentListener { 9014 public void componentHidden(ComponentEvent e) { 9015 if (accessibleContext != null) { 9016 accessibleContext.firePropertyChange( 9017 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9018 AccessibleState.VISIBLE, null); 9019 } 9020 } 9021 9022 public void componentShown(ComponentEvent e) { 9023 if (accessibleContext != null) { 9024 accessibleContext.firePropertyChange( 9025 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9026 null, AccessibleState.VISIBLE); 9027 } 9028 } 9029 9030 public void componentMoved(ComponentEvent e) { 9031 } 9032 9033 public void componentResized(ComponentEvent e) { 9034 } 9035 } // inner class AccessibleAWTComponentHandler 9036 9037 9038 /** 9039 * Fire PropertyChange listener, if one is registered, 9040 * when focus events happen 9041 * @since 1.3 9042 */ 9043 protected class AccessibleAWTFocusHandler implements FocusListener { 9044 public void focusGained(FocusEvent event) { 9045 if (accessibleContext != null) { 9046 accessibleContext.firePropertyChange( 9047 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9048 null, AccessibleState.FOCUSED); 9049 } 9050 } 9051 public void focusLost(FocusEvent event) { 9052 if (accessibleContext != null) { 9053 accessibleContext.firePropertyChange( 9054 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9055 AccessibleState.FOCUSED, null); 9056 } 9057 } 9058 } // inner class AccessibleAWTFocusHandler 9059 9060 9061 /** 9062 * Adds a <code>PropertyChangeListener</code> to the listener list. 9063 * 9064 * @param listener the property change listener to be added 9065 */ 9066 public void addPropertyChangeListener(PropertyChangeListener listener) { 9067 if (accessibleAWTComponentHandler == null) { 9068 accessibleAWTComponentHandler = new AccessibleAWTComponentHandler(); 9069 Component.this.addComponentListener(accessibleAWTComponentHandler); 9070 } 9071 if (accessibleAWTFocusHandler == null) { 9072 accessibleAWTFocusHandler = new AccessibleAWTFocusHandler(); 9073 Component.this.addFocusListener(accessibleAWTFocusHandler); 9074 } 9075 super.addPropertyChangeListener(listener); 9076 } 9077 9078 /** 9079 * Remove a PropertyChangeListener from the listener list. 9080 * This removes a PropertyChangeListener that was registered 9081 * for all properties. 9082 * 9083 * @param listener The PropertyChangeListener to be removed 9084 */ 9085 public void removePropertyChangeListener(PropertyChangeListener listener) { 9086 if (accessibleAWTComponentHandler != null) { 9087 Component.this.removeComponentListener(accessibleAWTComponentHandler); 9088 accessibleAWTComponentHandler = null; 9089 } 9090 if (accessibleAWTFocusHandler != null) { 9091 Component.this.removeFocusListener(accessibleAWTFocusHandler); 9092 accessibleAWTFocusHandler = null; 9093 } 9094 super.removePropertyChangeListener(listener); 9095 } 9096 9097 // AccessibleContext methods 9098 // 9099 /** 9100 * Gets the accessible name of this object. This should almost never 9101 * return <code>java.awt.Component.getName()</code>, 9102 * as that generally isn't a localized name, 9103 * and doesn't have meaning for the user. If the 9104 * object is fundamentally a text object (e.g. a menu item), the 9105 * accessible name should be the text of the object (e.g. "save"). 9106 * If the object has a tooltip, the tooltip text may also be an 9107 * appropriate String to return. 9108 * 9109 * @return the localized name of the object -- can be 9110 * <code>null</code> if this 9111 * object does not have a name 9112 * @see javax.accessibility.AccessibleContext#setAccessibleName 9113 */ 9114 public String getAccessibleName() { 9115 return accessibleName; 9116 } 9117 9118 /** 9119 * Gets the accessible description of this object. This should be 9120 * a concise, localized description of what this object is - what 9121 * is its meaning to the user. If the object has a tooltip, the 9122 * tooltip text may be an appropriate string to return, assuming 9123 * it contains a concise description of the object (instead of just 9124 * the name of the object - e.g. a "Save" icon on a toolbar that 9125 * had "save" as the tooltip text shouldn't return the tooltip 9126 * text as the description, but something like "Saves the current 9127 * text document" instead). 9128 * 9129 * @return the localized description of the object -- can be 9130 * <code>null</code> if this object does not have a description 9131 * @see javax.accessibility.AccessibleContext#setAccessibleDescription 9132 */ 9133 public String getAccessibleDescription() { 9134 return accessibleDescription; 9135 } 9136 9137 /** 9138 * Gets the role of this object. 9139 * 9140 * @return an instance of <code>AccessibleRole</code> 9141 * describing the role of the object 9142 * @see javax.accessibility.AccessibleRole 9143 */ 9144 public AccessibleRole getAccessibleRole() { 9145 return AccessibleRole.AWT_COMPONENT; 9146 } 9147 9148 /** 9149 * Gets the state of this object. 9150 * 9151 * @return an instance of <code>AccessibleStateSet</code> 9152 * containing the current state set of the object 9153 * @see javax.accessibility.AccessibleState 9154 */ 9155 public AccessibleStateSet getAccessibleStateSet() { 9156 return Component.this.getAccessibleStateSet(); 9157 } 9158 9159 /** 9160 * Gets the <code>Accessible</code> parent of this object. 9161 * If the parent of this object implements <code>Accessible</code>, 9162 * this method should simply return <code>getParent</code>. 9163 * 9164 * @return the <code>Accessible</code> parent of this 9165 * object -- can be <code>null</code> if this 9166 * object does not have an <code>Accessible</code> parent 9167 */ 9168 public Accessible getAccessibleParent() { 9169 if (accessibleParent != null) { 9170 return accessibleParent; 9171 } else { 9172 Container parent = getParent(); 9173 if (parent instanceof Accessible) { 9174 return (Accessible) parent; 9175 } 9176 } 9177 return null; 9178 } 9179 9180 /** 9181 * Gets the index of this object in its accessible parent. 9182 * 9183 * @return the index of this object in its parent; or -1 if this 9184 * object does not have an accessible parent 9185 * @see #getAccessibleParent 9186 */ 9187 public int getAccessibleIndexInParent() { 9188 return Component.this.getAccessibleIndexInParent(); 9189 } 9190 9191 /** 9192 * Returns the number of accessible children in the object. If all 9193 * of the children of this object implement <code>Accessible</code>, 9194 * then this method should return the number of children of this object. 9195 * 9196 * @return the number of accessible children in the object 9197 */ 9198 public int getAccessibleChildrenCount() { 9199 return 0; // Components don't have children 9200 } 9201 9202 /** 9203 * Returns the nth <code>Accessible</code> child of the object. 9204 * 9205 * @param i zero-based index of child 9206 * @return the nth <code>Accessible</code> child of the object 9207 */ 9208 public Accessible getAccessibleChild(int i) { 9209 return null; // Components don't have children 9210 } 9211 9212 /** 9213 * Returns the locale of this object. 9214 * 9215 * @return the locale of this object 9216 */ 9217 public Locale getLocale() { 9218 return Component.this.getLocale(); 9219 } 9220 9221 /** 9222 * Gets the <code>AccessibleComponent</code> associated 9223 * with this object if one exists. 9224 * Otherwise return <code>null</code>. 9225 * 9226 * @return the component 9227 */ 9228 public AccessibleComponent getAccessibleComponent() { 9229 return this; 9230 } 9231 9232 9233 // AccessibleComponent methods 9234 // 9235 /** 9236 * Gets the background color of this object. 9237 * 9238 * @return the background color, if supported, of the object; 9239 * otherwise, <code>null</code> 9240 */ 9241 public Color getBackground() { 9242 return Component.this.getBackground(); 9243 } 9244 9245 /** 9246 * Sets the background color of this object. 9247 * (For transparency, see <code>isOpaque</code>.) 9248 * 9249 * @param c the new <code>Color</code> for the background 9250 * @see Component#isOpaque 9251 */ 9252 public void setBackground(Color c) { 9253 Component.this.setBackground(c); 9254 } 9255 9256 /** 9257 * Gets the foreground color of this object. 9258 * 9259 * @return the foreground color, if supported, of the object; 9260 * otherwise, <code>null</code> 9261 */ 9262 public Color getForeground() { 9263 return Component.this.getForeground(); 9264 } 9265 9266 /** 9267 * Sets the foreground color of this object. 9268 * 9269 * @param c the new <code>Color</code> for the foreground 9270 */ 9271 public void setForeground(Color c) { 9272 Component.this.setForeground(c); 9273 } 9274 9275 /** 9276 * Gets the <code>Cursor</code> of this object. 9277 * 9278 * @return the <code>Cursor</code>, if supported, 9279 * of the object; otherwise, <code>null</code> 9280 */ 9281 public Cursor getCursor() { 9282 return Component.this.getCursor(); 9283 } 9284 9285 /** 9286 * Sets the <code>Cursor</code> of this object. 9287 * <p> 9288 * The method may have no visual effect if the Java platform 9289 * implementation and/or the native system do not support 9290 * changing the mouse cursor shape. 9291 * @param cursor the new <code>Cursor</code> for the object 9292 */ 9293 public void setCursor(Cursor cursor) { 9294 Component.this.setCursor(cursor); 9295 } 9296 9297 /** 9298 * Gets the <code>Font</code> of this object. 9299 * 9300 * @return the <code>Font</code>, if supported, 9301 * for the object; otherwise, <code>null</code> 9302 */ 9303 public Font getFont() { 9304 return Component.this.getFont(); 9305 } 9306 9307 /** 9308 * Sets the <code>Font</code> of this object. 9309 * 9310 * @param f the new <code>Font</code> for the object 9311 */ 9312 public void setFont(Font f) { 9313 Component.this.setFont(f); 9314 } 9315 9316 /** 9317 * Gets the <code>FontMetrics</code> of this object. 9318 * 9319 * @param f the <code>Font</code> 9320 * @return the <code>FontMetrics</code>, if supported, 9321 * the object; otherwise, <code>null</code> 9322 * @see #getFont 9323 */ 9324 public FontMetrics getFontMetrics(Font f) { 9325 if (f == null) { 9326 return null; 9327 } else { 9328 return Component.this.getFontMetrics(f); 9329 } 9330 } 9331 9332 /** 9333 * Determines if the object is enabled. 9334 * 9335 * @return true if object is enabled; otherwise, false 9336 */ 9337 public boolean isEnabled() { 9338 return Component.this.isEnabled(); 9339 } 9340 9341 /** 9342 * Sets the enabled state of the object. 9343 * 9344 * @param b if true, enables this object; otherwise, disables it 9345 */ 9346 public void setEnabled(boolean b) { 9347 boolean old = Component.this.isEnabled(); 9348 Component.this.setEnabled(b); 9349 if (b != old) { 9350 if (accessibleContext != null) { 9351 if (b) { 9352 accessibleContext.firePropertyChange( 9353 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9354 null, AccessibleState.ENABLED); 9355 } else { 9356 accessibleContext.firePropertyChange( 9357 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9358 AccessibleState.ENABLED, null); 9359 } 9360 } 9361 } 9362 } 9363 9364 /** 9365 * Determines if the object is visible. Note: this means that the 9366 * object intends to be visible; however, it may not in fact be 9367 * showing on the screen because one of the objects that this object 9368 * is contained by is not visible. To determine if an object is 9369 * showing on the screen, use <code>isShowing</code>. 9370 * 9371 * @return true if object is visible; otherwise, false 9372 */ 9373 public boolean isVisible() { 9374 return Component.this.isVisible(); 9375 } 9376 9377 /** 9378 * Sets the visible state of the object. 9379 * 9380 * @param b if true, shows this object; otherwise, hides it 9381 */ 9382 public void setVisible(boolean b) { 9383 boolean old = Component.this.isVisible(); 9384 Component.this.setVisible(b); 9385 if (b != old) { 9386 if (accessibleContext != null) { 9387 if (b) { 9388 accessibleContext.firePropertyChange( 9389 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9390 null, AccessibleState.VISIBLE); 9391 } else { 9392 accessibleContext.firePropertyChange( 9393 AccessibleContext.ACCESSIBLE_STATE_PROPERTY, 9394 AccessibleState.VISIBLE, null); 9395 } 9396 } 9397 } 9398 } 9399 9400 /** 9401 * Determines if the object is showing. This is determined by checking 9402 * the visibility of the object and ancestors of the object. Note: 9403 * this will return true even if the object is obscured by another 9404 * (for example, it happens to be underneath a menu that was pulled 9405 * down). 9406 * 9407 * @return true if object is showing; otherwise, false 9408 */ 9409 public boolean isShowing() { 9410 return Component.this.isShowing(); 9411 } 9412 9413 /** 9414 * Checks whether the specified point is within this object's bounds, 9415 * where the point's x and y coordinates are defined to be relative to 9416 * the coordinate system of the object. 9417 * 9418 * @param p the <code>Point</code> relative to the 9419 * coordinate system of the object 9420 * @return true if object contains <code>Point</code>; otherwise false 9421 */ 9422 public boolean contains(Point p) { 9423 return Component.this.contains(p); 9424 } 9425 9426 /** 9427 * Returns the location of the object on the screen. 9428 * 9429 * @return location of object on screen -- can be 9430 * <code>null</code> if this object is not on the screen 9431 */ 9432 public Point getLocationOnScreen() { 9433 synchronized (Component.this.getTreeLock()) { 9434 if (Component.this.isShowing()) { 9435 return Component.this.getLocationOnScreen(); 9436 } else { 9437 return null; 9438 } 9439 } 9440 } 9441 9442 /** 9443 * Gets the location of the object relative to the parent in the form 9444 * of a point specifying the object's top-left corner in the screen's 9445 * coordinate space. 9446 * 9447 * @return an instance of Point representing the top-left corner of 9448 * the object's bounds in the coordinate space of the screen; 9449 * <code>null</code> if this object or its parent are not on the screen 9450 */ 9451 public Point getLocation() { 9452 return Component.this.getLocation(); 9453 } 9454 9455 /** 9456 * Sets the location of the object relative to the parent. 9457 * @param p the coordinates of the object 9458 */ 9459 public void setLocation(Point p) { 9460 Component.this.setLocation(p); 9461 } 9462 9463 /** 9464 * Gets the bounds of this object in the form of a Rectangle object. 9465 * The bounds specify this object's width, height, and location 9466 * relative to its parent. 9467 * 9468 * @return a rectangle indicating this component's bounds; 9469 * <code>null</code> if this object is not on the screen 9470 */ 9471 public Rectangle getBounds() { 9472 return Component.this.getBounds(); 9473 } 9474 9475 /** 9476 * Sets the bounds of this object in the form of a 9477 * <code>Rectangle</code> object. 9478 * The bounds specify this object's width, height, and location 9479 * relative to its parent. 9480 * 9481 * @param r a rectangle indicating this component's bounds 9482 */ 9483 public void setBounds(Rectangle r) { 9484 Component.this.setBounds(r); 9485 } 9486 9487 /** 9488 * Returns the size of this object in the form of a 9489 * <code>Dimension</code> object. The height field of the 9490 * <code>Dimension</code> object contains this objects's 9491 * height, and the width field of the <code>Dimension</code> 9492 * object contains this object's width. 9493 * 9494 * @return a <code>Dimension</code> object that indicates 9495 * the size of this component; <code>null</code> if 9496 * this object is not on the screen 9497 */ 9498 public Dimension getSize() { 9499 return Component.this.getSize(); 9500 } 9501 9502 /** 9503 * Resizes this object so that it has width and height. 9504 * 9505 * @param d - the dimension specifying the new size of the object 9506 */ 9507 public void setSize(Dimension d) { 9508 Component.this.setSize(d); 9509 } 9510 9511 /** 9512 * Returns the <code>Accessible</code> child, 9513 * if one exists, contained at the local 9514 * coordinate <code>Point</code>. Otherwise returns 9515 * <code>null</code>. 9516 * 9517 * @param p the point defining the top-left corner of 9518 * the <code>Accessible</code>, given in the 9519 * coordinate space of the object's parent 9520 * @return the <code>Accessible</code>, if it exists, 9521 * at the specified location; else <code>null</code> 9522 */ 9523 public Accessible getAccessibleAt(Point p) { 9524 return null; // Components don't have children 9525 } 9526 9527 /** 9528 * Returns whether this object can accept focus or not. 9529 * 9530 * @return true if object can accept focus; otherwise false 9531 */ 9532 public boolean isFocusTraversable() { 9533 return Component.this.isFocusTraversable(); 9534 } 9535 9536 /** 9537 * Requests focus for this object. 9538 */ 9539 public void requestFocus() { 9540 Component.this.requestFocus(); 9541 } 9542 9543 /** 9544 * Adds the specified focus listener to receive focus events from this 9545 * component. 9546 * 9547 * @param l the focus listener 9548 */ 9549 public void addFocusListener(FocusListener l) { 9550 Component.this.addFocusListener(l); 9551 } 9552 9553 /** 9554 * Removes the specified focus listener so it no longer receives focus 9555 * events from this component. 9556 * 9557 * @param l the focus listener 9558 */ 9559 public void removeFocusListener(FocusListener l) { 9560 Component.this.removeFocusListener(l); 9561 } 9562 9563 } // inner class AccessibleAWTComponent 9564 9565 9566 /** 9567 * Gets the index of this object in its accessible parent. 9568 * If this object does not have an accessible parent, returns 9569 * -1. 9570 * 9571 * @return the index of this object in its accessible parent 9572 */ 9573 int getAccessibleIndexInParent() { 9574 synchronized (getTreeLock()) { 9575 int index = -1; 9576 Container parent = this.getParent(); 9577 if (parent != null && parent instanceof Accessible) { 9578 Component ca[] = parent.getComponents(); 9579 for (int i = 0; i < ca.length; i++) { 9580 if (ca[i] instanceof Accessible) { 9581 index++; 9582 } 9583 if (this.equals(ca[i])) { 9584 return index; 9585 } 9586 } 9587 } 9588 return -1; 9589 } 9590 } 9591 9592 /** 9593 * Gets the current state set of this object. 9594 * 9595 * @return an instance of <code>AccessibleStateSet</code> 9596 * containing the current state set of the object 9597 * @see AccessibleState 9598 */ 9599 AccessibleStateSet getAccessibleStateSet() { 9600 synchronized (getTreeLock()) { 9601 AccessibleStateSet states = new AccessibleStateSet(); 9602 if (this.isEnabled()) { 9603 states.add(AccessibleState.ENABLED); 9604 } 9605 if (this.isFocusTraversable()) { 9606 states.add(AccessibleState.FOCUSABLE); 9607 } 9608 if (this.isVisible()) { 9609 states.add(AccessibleState.VISIBLE); 9610 } 9611 if (this.isShowing()) { 9612 states.add(AccessibleState.SHOWING); 9613 } 9614 if (this.isFocusOwner()) { 9615 states.add(AccessibleState.FOCUSED); 9616 } 9617 if (this instanceof Accessible) { 9618 AccessibleContext ac = ((Accessible) this).getAccessibleContext(); 9619 if (ac != null) { 9620 Accessible ap = ac.getAccessibleParent(); 9621 if (ap != null) { 9622 AccessibleContext pac = ap.getAccessibleContext(); 9623 if (pac != null) { 9624 AccessibleSelection as = pac.getAccessibleSelection(); 9625 if (as != null) { 9626 states.add(AccessibleState.SELECTABLE); 9627 int i = ac.getAccessibleIndexInParent(); 9628 if (i >= 0) { 9629 if (as.isAccessibleChildSelected(i)) { 9630 states.add(AccessibleState.SELECTED); 9631 } 9632 } 9633 } 9634 } 9635 } 9636 } 9637 } 9638 if (Component.isInstanceOf(this, "javax.swing.JComponent")) { 9639 if (((javax.swing.JComponent) this).isOpaque()) { 9640 states.add(AccessibleState.OPAQUE); 9641 } 9642 } 9643 return states; 9644 } 9645 } 9646 9647 /** 9648 * Checks that the given object is instance of the given class. 9649 * @param obj Object to be checked 9650 * @param className The name of the class. Must be fully-qualified class name. 9651 * @return true, if this object is instanceof given class, 9652 * false, otherwise, or if obj or className is null 9653 */ 9654 static boolean isInstanceOf(Object obj, String className) { 9655 if (obj == null) return false; 9656 if (className == null) return false; 9657 9658 Class<?> cls = obj.getClass(); 9659 while (cls != null) { 9660 if (cls.getName().equals(className)) { 9661 return true; 9662 } 9663 cls = cls.getSuperclass(); 9664 } 9665 return false; 9666 } 9667 9668 9669 // ************************** MIXING CODE ******************************* 9670 9671 /** 9672 * Check whether we can trust the current bounds of the component. 9673 * The return value of false indicates that the container of the 9674 * component is invalid, and therefore needs to be layed out, which would 9675 * probably mean changing the bounds of its children. 9676 * Null-layout of the container or absence of the container mean 9677 * the bounds of the component are final and can be trusted. 9678 */ 9679 final boolean areBoundsValid() { 9680 Container cont = getContainer(); 9681 return cont == null || cont.isValid() || cont.getLayout() == null; 9682 } 9683 9684 /** 9685 * Applies the shape to the component 9686 * @param shape Shape to be applied to the component 9687 */ 9688 void applyCompoundShape(Region shape) { 9689 checkTreeLock(); 9690 9691 if (!areBoundsValid()) { 9692 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9693 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 9694 } 9695 return; 9696 } 9697 9698 if (!isLightweight()) { 9699 ComponentPeer peer = getPeer(); 9700 if (peer != null) { 9701 // The Region class has some optimizations. That's why 9702 // we should manually check whether it's empty and 9703 // substitute the object ourselves. Otherwise we end up 9704 // with some incorrect Region object with loX being 9705 // greater than the hiX for instance. 9706 if (shape.isEmpty()) { 9707 shape = Region.EMPTY_REGION; 9708 } 9709 9710 9711 // Note: the shape is not really copied/cloned. We create 9712 // the Region object ourselves, so there's no any possibility 9713 // to modify the object outside of the mixing code. 9714 // Nullifying compoundShape means that the component has normal shape 9715 // (or has no shape at all). 9716 if (shape.equals(getNormalShape())) { 9717 if (this.compoundShape == null) { 9718 return; 9719 } 9720 this.compoundShape = null; 9721 peer.applyShape(null); 9722 } else { 9723 if (shape.equals(getAppliedShape())) { 9724 return; 9725 } 9726 this.compoundShape = shape; 9727 Point compAbsolute = getLocationOnWindow(); 9728 if (mixingLog.isLoggable(PlatformLogger.FINER)) { 9729 mixingLog.fine("this = " + this + 9730 "; compAbsolute=" + compAbsolute + "; shape=" + shape); 9731 } 9732 peer.applyShape(shape.getTranslatedRegion(-compAbsolute.x, -compAbsolute.y)); 9733 } 9734 } 9735 } 9736 } 9737 9738 /** 9739 * Returns the shape previously set with applyCompoundShape(). 9740 * If the component is LW or no shape was applied yet, 9741 * the method returns the normal shape. 9742 */ 9743 private Region getAppliedShape() { 9744 checkTreeLock(); 9745 //XXX: if we allow LW components to have a shape, this must be changed 9746 return (this.compoundShape == null || isLightweight()) ? getNormalShape() : this.compoundShape; 9747 } 9748 9749 Point getLocationOnWindow() { 9750 checkTreeLock(); 9751 Point curLocation = getLocation(); 9752 9753 for (Container parent = getContainer(); 9754 parent != null && !(parent instanceof Window); 9755 parent = parent.getContainer()) 9756 { 9757 curLocation.x += parent.getX(); 9758 curLocation.y += parent.getY(); 9759 } 9760 9761 return curLocation; 9762 } 9763 9764 /** 9765 * Returns the full shape of the component located in window coordinates 9766 */ 9767 final Region getNormalShape() { 9768 checkTreeLock(); 9769 //XXX: we may take into account a user-specified shape for this component 9770 Point compAbsolute = getLocationOnWindow(); 9771 return 9772 Region.getInstanceXYWH( 9773 compAbsolute.x, 9774 compAbsolute.y, 9775 getWidth(), 9776 getHeight() 9777 ); 9778 } 9779 9780 /** 9781 * Returns the "opaque shape" of the component. 9782 * 9783 * The opaque shape of a lightweight components is the actual shape that 9784 * needs to be cut off of the heavyweight components in order to mix this 9785 * lightweight component correctly with them. 9786 * 9787 * The method is overriden in the java.awt.Container to handle non-opaque 9788 * containers containing opaque children. 9789 * 9790 * See 6637655 for details. 9791 */ 9792 Region getOpaqueShape() { 9793 checkTreeLock(); 9794 if (mixingCutoutRegion != null) { 9795 return mixingCutoutRegion; 9796 } else { 9797 return getNormalShape(); 9798 } 9799 } 9800 9801 final int getSiblingIndexAbove() { 9802 checkTreeLock(); 9803 Container parent = getContainer(); 9804 if (parent == null) { 9805 return -1; 9806 } 9807 9808 int nextAbove = parent.getComponentZOrder(this) - 1; 9809 9810 return nextAbove < 0 ? -1 : nextAbove; 9811 } 9812 9813 final ComponentPeer getHWPeerAboveMe() { 9814 checkTreeLock(); 9815 9816 Container cont = getContainer(); 9817 int indexAbove = getSiblingIndexAbove(); 9818 9819 while (cont != null) { 9820 for (int i = indexAbove; i > -1; i--) { 9821 Component comp = cont.getComponent(i); 9822 if (comp != null && comp.isDisplayable() && !comp.isLightweight()) { 9823 return comp.getPeer(); 9824 } 9825 } 9826 // traversing the hierarchy up to the closest HW container; 9827 // further traversing may return a component that is not actually 9828 // a native sibling of this component and this kind of z-order 9829 // request may not be allowed by the underlying system (6852051). 9830 if (!cont.isLightweight()) { 9831 break; 9832 } 9833 9834 indexAbove = cont.getSiblingIndexAbove(); 9835 cont = cont.getContainer(); 9836 } 9837 9838 return null; 9839 } 9840 9841 final int getSiblingIndexBelow() { 9842 checkTreeLock(); 9843 Container parent = getContainer(); 9844 if (parent == null) { 9845 return -1; 9846 } 9847 9848 int nextBelow = parent.getComponentZOrder(this) + 1; 9849 9850 return nextBelow >= parent.getComponentCount() ? -1 : nextBelow; 9851 } 9852 9853 final boolean isNonOpaqueForMixing() { 9854 return mixingCutoutRegion != null && 9855 mixingCutoutRegion.isEmpty(); 9856 } 9857 9858 private Region calculateCurrentShape() { 9859 checkTreeLock(); 9860 Region s = getNormalShape(); 9861 9862 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9863 mixingLog.fine("this = " + this + "; normalShape=" + s); 9864 } 9865 9866 if (getContainer() != null) { 9867 Component comp = this; 9868 Container cont = comp.getContainer(); 9869 9870 while (cont != null) { 9871 for (int index = comp.getSiblingIndexAbove(); index != -1; --index) { 9872 /* It is assumed that: 9873 * 9874 * getComponent(getContainer().getComponentZOrder(comp)) == comp 9875 * 9876 * The assumption has been made according to the current 9877 * implementation of the Container class. 9878 */ 9879 Component c = cont.getComponent(index); 9880 if (c.isLightweight() && c.isShowing()) { 9881 s = s.getDifference(c.getOpaqueShape()); 9882 } 9883 } 9884 9885 if (cont.isLightweight()) { 9886 s = s.getIntersection(cont.getNormalShape()); 9887 } else { 9888 break; 9889 } 9890 9891 comp = cont; 9892 cont = cont.getContainer(); 9893 } 9894 } 9895 9896 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9897 mixingLog.fine("currentShape=" + s); 9898 } 9899 9900 return s; 9901 } 9902 9903 void applyCurrentShape() { 9904 checkTreeLock(); 9905 if (!areBoundsValid()) { 9906 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9907 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 9908 } 9909 return; // Because applyCompoundShape() ignores such components anyway 9910 } 9911 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9912 mixingLog.fine("this = " + this); 9913 } 9914 applyCompoundShape(calculateCurrentShape()); 9915 } 9916 9917 final void subtractAndApplyShape(Region s) { 9918 checkTreeLock(); 9919 9920 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9921 mixingLog.fine("this = " + this + "; s=" + s); 9922 } 9923 9924 applyCompoundShape(getAppliedShape().getDifference(s)); 9925 } 9926 9927 private final void applyCurrentShapeBelowMe() { 9928 checkTreeLock(); 9929 Container parent = getContainer(); 9930 if (parent != null && parent.isShowing()) { 9931 // First, reapply shapes of my siblings 9932 parent.recursiveApplyCurrentShape(getSiblingIndexBelow()); 9933 9934 // Second, if my container is non-opaque, reapply shapes of siblings of my container 9935 Container parent2 = parent.getContainer(); 9936 while (!parent.isOpaque() && parent2 != null) { 9937 parent2.recursiveApplyCurrentShape(parent.getSiblingIndexBelow()); 9938 9939 parent = parent2; 9940 parent2 = parent.getContainer(); 9941 } 9942 } 9943 } 9944 9945 final void subtractAndApplyShapeBelowMe() { 9946 checkTreeLock(); 9947 Container parent = getContainer(); 9948 if (parent != null && isShowing()) { 9949 Region opaqueShape = getOpaqueShape(); 9950 9951 // First, cut my siblings 9952 parent.recursiveSubtractAndApplyShape(opaqueShape, getSiblingIndexBelow()); 9953 9954 // Second, if my container is non-opaque, cut siblings of my container 9955 Container parent2 = parent.getContainer(); 9956 while (!parent.isOpaque() && parent2 != null) { 9957 parent2.recursiveSubtractAndApplyShape(opaqueShape, parent.getSiblingIndexBelow()); 9958 9959 parent = parent2; 9960 parent2 = parent.getContainer(); 9961 } 9962 } 9963 } 9964 9965 void mixOnShowing() { 9966 synchronized (getTreeLock()) { 9967 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9968 mixingLog.fine("this = " + this); 9969 } 9970 if (!isMixingNeeded()) { 9971 return; 9972 } 9973 if (isLightweight()) { 9974 subtractAndApplyShapeBelowMe(); 9975 } else { 9976 applyCurrentShape(); 9977 } 9978 } 9979 } 9980 9981 void mixOnHiding(boolean isLightweight) { 9982 // We cannot be sure that the peer exists at this point, so we need the argument 9983 // to find out whether the hiding component is (well, actually was) a LW or a HW. 9984 synchronized (getTreeLock()) { 9985 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 9986 mixingLog.fine("this = " + this + "; isLightweight = " + isLightweight); 9987 } 9988 if (!isMixingNeeded()) { 9989 return; 9990 } 9991 if (isLightweight) { 9992 applyCurrentShapeBelowMe(); 9993 } 9994 } 9995 } 9996 9997 void mixOnReshaping() { 9998 synchronized (getTreeLock()) { 9999 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 10000 mixingLog.fine("this = " + this); 10001 } 10002 if (!isMixingNeeded()) { 10003 return; 10004 } 10005 if (isLightweight()) { 10006 applyCurrentShapeBelowMe(); 10007 } else { 10008 applyCurrentShape(); 10009 } 10010 } 10011 } 10012 10013 void mixOnZOrderChanging(int oldZorder, int newZorder) { 10014 synchronized (getTreeLock()) { 10015 boolean becameHigher = newZorder < oldZorder; 10016 Container parent = getContainer(); 10017 10018 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 10019 mixingLog.fine("this = " + this + 10020 "; oldZorder=" + oldZorder + "; newZorder=" + newZorder + "; parent=" + parent); 10021 } 10022 if (!isMixingNeeded()) { 10023 return; 10024 } 10025 if (isLightweight()) { 10026 if (becameHigher) { 10027 if (parent != null && isShowing()) { 10028 parent.recursiveSubtractAndApplyShape(getOpaqueShape(), getSiblingIndexBelow(), oldZorder); 10029 } 10030 } else { 10031 if (parent != null) { 10032 parent.recursiveApplyCurrentShape(oldZorder, newZorder); 10033 } 10034 } 10035 } else { 10036 if (becameHigher) { 10037 applyCurrentShape(); 10038 } else { 10039 if (parent != null) { 10040 Region shape = getAppliedShape(); 10041 10042 for (int index = oldZorder; index < newZorder; index++) { 10043 Component c = parent.getComponent(index); 10044 if (c.isLightweight() && c.isShowing()) { 10045 shape = shape.getDifference(c.getOpaqueShape()); 10046 } 10047 } 10048 applyCompoundShape(shape); 10049 } 10050 } 10051 } 10052 } 10053 } 10054 10055 void mixOnValidating() { 10056 // This method gets overriden in the Container. Obviously, a plain 10057 // non-container components don't need to handle validation. 10058 } 10059 10060 final boolean isMixingNeeded() { 10061 if (SunToolkit.getSunAwtDisableMixing()) { 10062 if (mixingLog.isLoggable(PlatformLogger.FINEST)) { 10063 mixingLog.finest("this = " + this + "; Mixing disabled via sun.awt.disableMixing"); 10064 } 10065 return false; 10066 } 10067 if (!areBoundsValid()) { 10068 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 10069 mixingLog.fine("this = " + this + "; areBoundsValid = " + areBoundsValid()); 10070 } 10071 return false; 10072 } 10073 Window window = getContainingWindow(); 10074 if (window != null) { 10075 if (!window.hasHeavyweightDescendants() || !window.hasLightweightDescendants() || window.isDisposing()) { 10076 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 10077 mixingLog.fine("containing window = " + window + 10078 "; has h/w descendants = " + window.hasHeavyweightDescendants() + 10079 "; has l/w descendants = " + window.hasLightweightDescendants() + 10080 "; disposing = " + window.isDisposing()); 10081 } 10082 return false; 10083 } 10084 } else { 10085 if (mixingLog.isLoggable(PlatformLogger.FINE)) { 10086 mixingLog.fine("this = " + this + "; containing window is null"); 10087 } 10088 return false; 10089 } 10090 return true; 10091 } 10092 10093 // ****************** END OF MIXING CODE ******************************** 10094 10095 // Note that the method is overriden in the Window class, 10096 // a window doesn't need to be updated in the Z-order. 10097 void updateZOrder() { 10098 peer.setZOrder(getHWPeerAboveMe()); 10099 } 10100 10101 }