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