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