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