1. /*
  2. * @(#)JComponent.java 2.211 03/08/26
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package javax.swing;
  8. import java.util.Hashtable;
  9. import java.util.Dictionary;
  10. import java.util.Enumeration;
  11. import java.util.Locale;
  12. import java.util.Vector;
  13. import java.util.EventListener;
  14. import java.util.Set;
  15. import java.util.TreeSet;
  16. import java.awt.*;
  17. import java.awt.event.*;
  18. import java.awt.image.VolatileImage;
  19. import java.awt.Graphics2D;
  20. import java.awt.peer.LightweightPeer;
  21. import java.awt.dnd.DropTarget;
  22. import java.beans.*;
  23. import java.applet.Applet;
  24. import java.io.Serializable;
  25. import java.io.ObjectOutputStream;
  26. import java.io.ObjectInputStream;
  27. import java.io.IOException;
  28. import java.io.ObjectInputValidation;
  29. import java.io.InvalidObjectException;
  30. import javax.swing.border.*;
  31. import javax.swing.event.*;
  32. import javax.swing.plaf.*;
  33. import javax.accessibility.*;
  34. /**
  35. * The base class for all Swing components except top-level containers.
  36. * To use a component that inherits from <code>JComponent</code>,
  37. * you must place the component in a containment hierarchy
  38. * whose root is a top-level Swing container.
  39. * Top-level Swing containers --
  40. * such as <code>JFrame</code>, <code>JDialog</code>,
  41. * and <code>JApplet</code> --
  42. * are specialized components
  43. * that provide a place for other Swing components to paint themselves.
  44. * For an explanation of containment hierarchies, see
  45. * <a
  46. href="http://java.sun.com/docs/books/tutorial/uiswing/overview/hierarchy.html">Swing Components and the Containment Hierarchy</a>,
  47. * a section in <em>The Java Tutorial</em>.
  48. *
  49. * <p>
  50. * The <code>JComponent</code> class provides:
  51. * <ul>
  52. * <li>The base class for both standard and custom components
  53. * that use the Swing architecture.
  54. * <li>A "pluggable look and feel" (L&F) that can be specified by the
  55. * programmer or (optionally) selected by the user at runtime.
  56. * The look and feel for each component is provided by a
  57. * <em>UI delegate</em> -- an object that descends from
  58. * {@link javax.swing.plaf.ComponentUI}.
  59. * See <a
  60. * href="http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html">How
  61. * to Set the Look and Feel</a>
  62. * in <em>The Java Tutorial</em>
  63. * for more information.
  64. * <li>Comprehensive keystroke handling.
  65. * See the document <a
  66. * href="http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html">Keyboard
  67. * Bindings in Swing</a>,
  68. * an article in <em>The Swing Connection</em>,
  69. * for more information.
  70. * <li>Support for tool tips --
  71. * short descriptions that pop up when the cursor lingers
  72. * over a component.
  73. * See <a
  74. * href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How
  75. * to Use Tool Tips</a>
  76. * in <em>The Java Tutorial</em>
  77. * for more information.
  78. * <li>Support for accessibility.
  79. * <code>JComponent</code> contains all of the methods in the
  80. * <code>Accessible</code> interface,
  81. * but it doesn't actually implement the interface. That is the
  82. * responsibility of the individual classes
  83. * that extend <code>JComponent</code>.
  84. * <li>Support for component-specific properties.
  85. * With the {@link #putClientProperty}
  86. * and {@link #getClientProperty} methods,
  87. * you can associate name-object pairs
  88. * with any object that descends from <code>JComponent</code>.
  89. * <li>An infrastructure for painting
  90. * that includes double buffering and support for borders.
  91. * For more information see <a
  92. * href="http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html">Painting</a> and
  93. * <a href="http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html">How
  94. * to Use Borders</a>,
  95. * both of which are sections in <em>The Java Tutorial</em>.
  96. * </ul>
  97. * For more information on these subjects, see the
  98. * <a href="package-summary.html#package_description">Swing package description</a>
  99. * and <em>The Java Tutorial</em> section
  100. * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/jcomponent.html">The JComponent Class</a>.
  101. * <p>
  102. * <strong>Warning:</strong>
  103. * Serialized objects of this class will not be compatible with
  104. * future Swing releases. The current serialization support is
  105. * appropriate for short term storage or RMI between applications running
  106. * the same version of Swing. As of 1.4, support for long term storage
  107. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  108. * has been added to the <code>java.beans</code> package.
  109. * Please see {@link java.beans.XMLEncoder}.
  110. *
  111. * @see KeyStroke
  112. * @see Action
  113. * @see #setBorder
  114. * @see #registerKeyboardAction
  115. * @see JOptionPane
  116. * @see #setDebugGraphicsOptions
  117. * @see #setToolTipText
  118. * @see #setAutoscrolls
  119. *
  120. * @version 2.130 07/09/99
  121. * @author Hans Muller
  122. * @author Arnaud Weber
  123. */
  124. public abstract class JComponent extends Container implements Serializable
  125. {
  126. /**
  127. * @see #getUIClassID
  128. * @see #writeObject
  129. */
  130. private static final String uiClassID = "ComponentUI";
  131. /**
  132. * @see ReadObjectCallback
  133. * @see #readObject
  134. */
  135. private static final Hashtable readObjectCallbacks = new Hashtable(1);
  136. /**
  137. * Keys to use for forward focus traversal when the JComponent is
  138. * managing focus.
  139. */
  140. private static Set managingFocusForwardTraversalKeys;
  141. /**
  142. * Keys to use for backward focus traversal when the JComponent is
  143. * managing focus.
  144. */
  145. private static Set managingFocusBackwardTraversalKeys;
  146. /**
  147. * Indicates if we should register a <code>DropTarget</code> for a
  148. * non-null <code>TransferHandler</code>. Use
  149. * <code>getSuppressDropTarget</code> to check.
  150. */
  151. private static boolean suppressDropSupport;
  152. /**
  153. * Indiciates if we've checked the system property for suppressing
  154. * drop support.
  155. */
  156. private static boolean checkedSuppressDropSupport;
  157. // Following are the possible return values from getObscuredState.
  158. private static final int NOT_OBSCURED = 0;
  159. private static final int PARTIALLY_OBSCURED = 1;
  160. private static final int COMPLETELY_OBSCURED = 2;
  161. /* The following fields support set methods for the corresponding
  162. * java.awt.Component properties.
  163. */
  164. private Dimension preferredSize;
  165. private Dimension minimumSize;
  166. private Dimension maximumSize;
  167. private Float alignmentX;
  168. private Float alignmentY;
  169. private AncestorNotifier ancestorNotifier;
  170. Rectangle _bounds = new Rectangle();
  171. /**
  172. * Backing store for JComponent properties and listeners
  173. */
  174. /** The look and feel delegate for this component. */
  175. protected transient ComponentUI ui;
  176. /** A list of event listeners for this component. */
  177. protected EventListenerList listenerList = new EventListenerList();
  178. private Hashtable clientProperties;
  179. private VetoableChangeSupport vetoableChangeSupport;
  180. private Autoscroller autoscroller;
  181. private Border border;
  182. private int flags;
  183. private TransferHandler transfer;
  184. /* Input verifier for this component */
  185. private InputVerifier inputVerifier = null;
  186. private boolean verifyInputWhenFocusTarget = true;
  187. /* A "scratch pad" rectangle used by the painting code.
  188. */
  189. private transient Rectangle tmpRect;
  190. /**
  191. * Set in <code>_paintImmediately</code>.
  192. * Will indicate the child that initiated the painting operation.
  193. * If <code>paintingChild</code> is opaque, no need to paint
  194. * any child components after <code>paintingChild</code>.
  195. * Test used in <code>paintChildren</code>.
  196. */
  197. transient Component paintingChild;
  198. /**
  199. * Constant used for <code>registerKeyboardAction</code> that
  200. * means that the command should be invoked when
  201. * the component has the focus.
  202. */
  203. public static final int WHEN_FOCUSED = 0;
  204. /**
  205. * Constant used for <code>registerKeyboardAction</code> that
  206. * means that the command should be invoked when the receiving
  207. * component is an ancestor of the focused component or is
  208. * itself the focused component.
  209. */
  210. public static final int WHEN_ANCESTOR_OF_FOCUSED_COMPONENT = 1;
  211. /**
  212. * Constant used for <code>registerKeyboardAction</code> that
  213. * means that the command should be invoked when
  214. * the receiving component is in the window that has the focus
  215. * or is itself the focused component.
  216. */
  217. public static final int WHEN_IN_FOCUSED_WINDOW = 2;
  218. /**
  219. * Constant used by some of the APIs to mean that no condition is defined.
  220. */
  221. public static final int UNDEFINED_CONDITION = -1;
  222. /**
  223. * The key used by <code>JComponent</code> to access keyboard bindings.
  224. */
  225. private static final String KEYBOARD_BINDINGS_KEY = "_KeyboardBindings";
  226. /**
  227. * An array of <code>KeyStroke</code>s used for
  228. * <code>WHEN_IN_FOCUSED_WINDOW</code> are stashed
  229. * in the client properties under this string.
  230. */
  231. private static final String WHEN_IN_FOCUSED_WINDOW_BINDINGS = "_WhenInFocusedWindow";
  232. /**
  233. * The comment to display when the cursor is over the component,
  234. * also known as a "value tip", "flyover help", or "flyover label".
  235. */
  236. public static final String TOOL_TIP_TEXT_KEY = "ToolTipText";
  237. private static final String NEXT_FOCUS = "nextFocus";
  238. /** Private flags **/
  239. private static final int IS_DOUBLE_BUFFERED = 0;
  240. private static final int ANCESTOR_USING_BUFFER = 1;
  241. private static final int IS_PAINTING_TILE = 2;
  242. private static final int IS_OPAQUE = 3;
  243. private static final int KEY_EVENTS_ENABLED = 4;
  244. private static final int FOCUS_INPUTMAP_CREATED = 5;
  245. private static final int ANCESTOR_INPUTMAP_CREATED = 6;
  246. private static final int WIF_INPUTMAP_CREATED = 7;
  247. private static final int ACTIONMAP_CREATED = 8;
  248. private static final int CREATED_DOUBLE_BUFFER = 9;
  249. // Bit 10 is free
  250. private static final int IS_PRINTING = 11;
  251. private static final int IS_PRINTING_ALL = 12;
  252. private static final int IS_REPAINTING = 13;
  253. /** Bits 14-21 are used to handle nested writeObject calls. **/
  254. private static final int WRITE_OBJ_COUNTER_FIRST = 14;
  255. private static final int RESERVED_1 = 15;
  256. private static final int RESERVED_2 = 16;
  257. private static final int RESERVED_3 = 17;
  258. private static final int RESERVED_4 = 18;
  259. private static final int RESERVED_5 = 19;
  260. private static final int RESERVED_6 = 20;
  261. private static final int WRITE_OBJ_COUNTER_LAST = 21;
  262. private static final int REQUEST_FOCUS_DISABLED = 22;
  263. /** Used for <code>WHEN_FOCUSED</code> bindings. */
  264. private InputMap focusInputMap;
  265. /** Used for <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings. */
  266. private InputMap ancestorInputMap;
  267. /** Used for <code>WHEN_IN_FOCUSED_KEY</code> bindings. */
  268. private ComponentInputMap windowInputMap;
  269. /** ActionMap. */
  270. private ActionMap actionMap;
  271. /** Key used to store the default locale in an AppContext **/
  272. private static final String defaultLocale = "JComponent.defaultLocale";
  273. /**
  274. * Returns the Set of <code>KeyStroke</code>s to use if the component
  275. * is managing focus for forward focus traversal.
  276. */
  277. static Set getManagingFocusForwardTraversalKeys() {
  278. if (managingFocusForwardTraversalKeys == null) {
  279. managingFocusForwardTraversalKeys = new TreeSet();
  280. managingFocusForwardTraversalKeys.add(
  281. KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.CTRL_MASK));
  282. }
  283. return managingFocusForwardTraversalKeys;
  284. }
  285. /**
  286. * Returns the Set of <code>KeyStroke</code>s to use if the component
  287. * is managing focus for backward focus traversal.
  288. */
  289. static Set getManagingFocusBackwardTraversalKeys() {
  290. if (managingFocusBackwardTraversalKeys == null) {
  291. managingFocusBackwardTraversalKeys = new TreeSet();
  292. managingFocusBackwardTraversalKeys.add(
  293. KeyStroke.getKeyStroke(KeyEvent.VK_TAB,
  294. InputEvent.SHIFT_MASK |
  295. InputEvent.CTRL_MASK));
  296. }
  297. return managingFocusBackwardTraversalKeys;
  298. }
  299. /**
  300. * Returns true if <code>setTransferHandler</code> should install
  301. * a <code>DropTarget</code>.
  302. */
  303. private static boolean getSuppressDropTarget() {
  304. if (!checkedSuppressDropSupport) {
  305. Boolean b = (Boolean)java.security.AccessController.doPrivileged(
  306. new java.security.PrivilegedAction() {
  307. public Object run() {
  308. String value = System.getProperty(
  309. "suppressSwingDropSupport");
  310. if (value != null) {
  311. return Boolean.valueOf(value);
  312. }
  313. return Boolean.FALSE;
  314. }
  315. }
  316. );
  317. suppressDropSupport = b.booleanValue();
  318. checkedSuppressDropSupport = true;
  319. }
  320. return suppressDropSupport;
  321. }
  322. /**
  323. * Default <code>JComponent</code> constructor. This constructor does
  324. * very little initialization beyond calling the <code>Container</code>
  325. * constructor. For example, the initial layout manager is
  326. * <code>null</code>. It does, however, set the component's locale
  327. * property to the value returned by
  328. * <code>JComponent.getDefaultLocale</code>.
  329. *
  330. * @see #getDefaultLocale
  331. */
  332. public JComponent() {
  333. super();
  334. // We enable key events on all JComponents so that accessibility
  335. // bindings will work everywhere. This is a partial fix to BugID
  336. // 4282211.
  337. enableEvents(AWTEvent.KEY_EVENT_MASK);
  338. enableSerialization();
  339. if (isManagingFocus()) {
  340. setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
  341. getManagingFocusForwardTraversalKeys());
  342. setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
  343. getManagingFocusBackwardTraversalKeys());
  344. }
  345. super.setLocale( JComponent.getDefaultLocale() );
  346. }
  347. /**
  348. * Resets the UI property to a value from the current look and feel.
  349. * <code>JComponent</code> subclasses must override this method
  350. * like this:
  351. * <pre>
  352. * public void updateUI() {
  353. * setUI((SliderUI)UIManager.getUI(this);
  354. * }
  355. * </pre>
  356. *
  357. * @see #setUI
  358. * @see UIManager#getLookAndFeel
  359. * @see UIManager#getUI
  360. */
  361. public void updateUI() {}
  362. /**
  363. * Sets the look and feel delegate for this component.
  364. * <code>JComponent</code> subclasses generally override this method
  365. * to narrow the argument type. For example, in <code>JSlider</code>:
  366. * <pre>
  367. * public void setUI(SliderUI newUI) {
  368. * super.setUI(newUI);
  369. * }
  370. * </pre>
  371. * <p>
  372. * Additionally <code>JComponent</code> subclasses must provide a
  373. * <code>getUI</code> method that returns the correct type. For example:
  374. * <pre>
  375. * public SliderUI getUI() {
  376. * return (SliderUI)ui;
  377. * }
  378. * </pre>
  379. *
  380. * @param newUI the new UI delegate
  381. * @see #updateUI
  382. * @see UIManager#getLookAndFeel
  383. * @see UIManager#getUI
  384. * @beaninfo
  385. * bound: true
  386. * hidden: true
  387. * attribute: visualUpdate true
  388. * description: The component's look and feel delegate.
  389. */
  390. protected void setUI(ComponentUI newUI) {
  391. /* We do not check that the UI instance is different
  392. * before allowing the switch in order to enable the
  393. * same UI instance *with different default settings*
  394. * to be installed.
  395. */
  396. if (ui != null) {
  397. ui.uninstallUI(this);
  398. }
  399. ComponentUI oldUI = ui;
  400. ui = newUI;
  401. if (ui != null) {
  402. ui.installUI(this);
  403. }
  404. firePropertyChange("UI", oldUI, newUI);
  405. revalidate();
  406. repaint();
  407. }
  408. /**
  409. * Returns the <code>UIDefaults</code> key used to
  410. * look up the name of the <code>swing.plaf.ComponentUI</code>
  411. * class that defines the look and feel
  412. * for this component. Most applications will never need to
  413. * call this method. Subclasses of <code>JComponent</code> that support
  414. * pluggable look and feel should override this method to
  415. * return a <code>UIDefaults</code> key that maps to the
  416. * <code>ComponentUI</code> subclass that defines their look and feel.
  417. *
  418. * @return the <code>UIDefaults</code> key for a
  419. * <code>ComponentUI</code> subclass
  420. * @see UIDefaults#getUI
  421. * @beaninfo
  422. * expert: true
  423. * description: UIClassID
  424. */
  425. public String getUIClassID() {
  426. return uiClassID;
  427. }
  428. /**
  429. * Returns the graphics object used to paint this component.
  430. * If <code>DebugGraphics</code> is turned on we create a new
  431. * <code>DebugGraphics</code> object if necessary.
  432. * Otherwise we just configure the
  433. * specified graphics object's foreground and font.
  434. *
  435. * @param g the original <code>Graphics</code> object
  436. * @return a <code>Graphics</code> object configured for this component
  437. */
  438. protected Graphics getComponentGraphics(Graphics g) {
  439. Graphics componentGraphics = g;
  440. if (ui != null) {
  441. if ((DebugGraphics.debugComponentCount() != 0) &&
  442. (shouldDebugGraphics() != 0) &&
  443. !(g instanceof DebugGraphics)) {
  444. if(g instanceof SwingGraphics) {
  445. if(!(((SwingGraphics)g).subGraphics() instanceof DebugGraphics)) {
  446. Graphics dbgGraphics = new DebugGraphics(((SwingGraphics)g).subGraphics(),this);
  447. componentGraphics = SwingGraphics.createSwingGraphics(dbgGraphics);
  448. dbgGraphics.dispose();
  449. }
  450. } else {
  451. componentGraphics = new DebugGraphics(g,this);
  452. }
  453. }
  454. }
  455. componentGraphics.setColor(getForeground());
  456. componentGraphics.setFont(getFont());
  457. return componentGraphics;
  458. }
  459. /**
  460. * Calls the UI delegate's paint method, if the UI delegate
  461. * is non-<code>null</code>. We pass the delegate a copy of the
  462. * <code>Graphics</code> object to protect the rest of the
  463. * paint code from irrevocable changes
  464. * (for example, <code>Graphics.translate</code>).
  465. * <p>
  466. * If you override this in a subclass you should not make permanent
  467. * changes to the passed in <code>Graphics</code>. For example, you
  468. * should not alter the clip <code>Rectangle</code> or modify the
  469. * transform. If you need to do these operations you may find it
  470. * easier to create a new <code>Graphics</code> from the passed in
  471. * <code>Graphics</code> and manipulate it. Further, if you do not
  472. * invoker super's implementation you must honor the opaque property,
  473. * that is
  474. * if this component is opaque, you must completely fill in the background
  475. * in a non-opaque color. If you do not honor the opaque property you
  476. * will likely see visual artifacts.
  477. *
  478. * @param g the <code>Graphics</code> object to protect
  479. * @see #paint
  480. * @see ComponentUI
  481. */
  482. protected void paintComponent(Graphics g) {
  483. if (ui != null) {
  484. Graphics scratchGraphics = SwingGraphics.createSwingGraphics(g);
  485. try {
  486. ui.update(scratchGraphics, this);
  487. }
  488. finally {
  489. scratchGraphics.dispose();
  490. }
  491. }
  492. }
  493. /**
  494. * Paints this component's children.
  495. * If <code>shouldUseBuffer</code> is true,
  496. * no component ancestor has a buffer and
  497. * the component children can use a buffer if they have one.
  498. * Otherwise, one ancestor has a buffer currently in use and children
  499. * should not use a buffer to paint.
  500. * @param g the <code>Graphics</code> context in which to paint
  501. * @see #paint
  502. * @see java.awt.Container#paint
  503. */
  504. protected void paintChildren(Graphics g) {
  505. boolean isJComponent;
  506. Graphics sg = null;
  507. try {
  508. synchronized(getTreeLock()) {
  509. int i = getComponentCount() - 1;
  510. if (i < 0) {
  511. return;
  512. }
  513. sg = SwingGraphics.createSwingGraphics(g);
  514. // If we are only to paint to a specific child, determine
  515. // its index.
  516. if (paintingChild != null &&
  517. (paintingChild instanceof JComponent) &&
  518. ((JComponent)paintingChild).isOpaque()) {
  519. for (; i >= 0; i--) {
  520. if (getComponent(i) == paintingChild){
  521. break;
  522. }
  523. }
  524. }
  525. if(tmpRect == null) {
  526. tmpRect = new Rectangle();
  527. }
  528. boolean checkSiblings = (!isOptimizedDrawingEnabled() &&
  529. checkIfChildObscuredBySibling());
  530. Rectangle clipBounds = null;
  531. if (checkSiblings) {
  532. clipBounds = sg.getClipBounds();
  533. if (clipBounds == null) {
  534. clipBounds = new Rectangle(0, 0, _bounds.width,
  535. _bounds.height);
  536. }
  537. }
  538. boolean printing = getFlag(IS_PRINTING);
  539. for (; i >= 0 ; i--) {
  540. Component comp = getComponent(i);
  541. if (comp != null && isLightweightComponent(comp) &&
  542. (comp.isVisible() == true)) {
  543. Rectangle cr;
  544. isJComponent = (comp instanceof JComponent);
  545. if(isJComponent) {
  546. cr = tmpRect;
  547. ((JComponent)comp).getBounds(cr);
  548. } else {
  549. cr = comp.getBounds();
  550. }
  551. boolean hitClip = g.hitClip(cr.x, cr.y, cr.width, cr.height);
  552. if (hitClip) {
  553. if (checkSiblings && i > 0) {
  554. int x = cr.x;
  555. int y = cr.y;
  556. int width = cr.width;
  557. int height = cr.height;
  558. SwingUtilities.computeIntersection
  559. (clipBounds.x, clipBounds.y,
  560. clipBounds.width, clipBounds.height, cr);
  561. if(getObscuredState(i, cr.x, cr.y, cr.width,
  562. cr.height) == COMPLETELY_OBSCURED) {
  563. continue;
  564. }
  565. cr.x = x;
  566. cr.y = y;
  567. cr.width = width;
  568. cr.height = height;
  569. }
  570. Graphics cg = SwingGraphics.createSwingGraphics(
  571. sg, cr.x, cr.y, cr.width, cr.height);
  572. cg.setColor(comp.getForeground());
  573. cg.setFont(comp.getFont());
  574. boolean shouldSetFlagBack = false;
  575. try {
  576. if(isJComponent) {
  577. if(getFlag(ANCESTOR_USING_BUFFER)) {
  578. ((JComponent)comp).setFlag(ANCESTOR_USING_BUFFER,true);
  579. shouldSetFlagBack = true;
  580. }
  581. if(getFlag(IS_PAINTING_TILE)) {
  582. ((JComponent)comp).setFlag(IS_PAINTING_TILE,true);
  583. shouldSetFlagBack = true;
  584. }
  585. if(!printing) {
  586. ((JComponent)comp).paint(cg);
  587. }
  588. else {
  589. if (!getFlag(IS_PRINTING_ALL)) {
  590. comp.print(cg);
  591. }
  592. else {
  593. comp.printAll(cg);
  594. }
  595. }
  596. } else {
  597. if (!printing) {
  598. comp.paint(cg);
  599. }
  600. else {
  601. if (!getFlag(IS_PRINTING_ALL)) {
  602. comp.print(cg);
  603. }
  604. else {
  605. comp.printAll(cg);
  606. }
  607. }
  608. }
  609. } finally {
  610. cg.dispose();
  611. if(shouldSetFlagBack) {
  612. ((JComponent)comp).setFlag(ANCESTOR_USING_BUFFER,false);
  613. ((JComponent)comp).setFlag(IS_PAINTING_TILE,false);
  614. }
  615. }
  616. }
  617. }
  618. }
  619. }
  620. } finally {
  621. if (sg != null) {
  622. sg.dispose();
  623. }
  624. }
  625. }
  626. /**
  627. * Paints the component's border.
  628. * <p>
  629. * If you override this in a subclass you should not make permanent
  630. * changes to the passed in <code>Graphics</code>. For example, you
  631. * should not alter the clip <code>Rectangle</code> or modify the
  632. * transform. If you need to do these operations you may find it
  633. * easier to create a new <code>Graphics</code> from the passed in
  634. * <code>Graphics</code> and manipulate it.
  635. *
  636. * @param g the <code>Graphics</code> context in which to paint
  637. *
  638. * @see #paint
  639. * @see #setBorder
  640. */
  641. protected void paintBorder(Graphics g) {
  642. Border border = getBorder();
  643. if (border != null) {
  644. border.paintBorder(this, g, 0, 0, getWidth(), getHeight());
  645. }
  646. }
  647. /**
  648. * Calls <code>paint</code>. Doesn't clear the background but see
  649. * <code>ComponentUI.update</code>, which is called by
  650. * <code>paintComponent</code>.
  651. *
  652. * @param g the <code>Graphics</code> context in which to paint
  653. * @see #paint
  654. * @see #paintComponent
  655. * @see javax.swing.plaf.ComponentUI
  656. */
  657. public void update(Graphics g) {
  658. paint(g);
  659. }
  660. /**
  661. * Invoked by Swing to draw components.
  662. * Applications should not invoke <code>paint</code> directly,
  663. * but should instead use the <code>repaint</code> method to
  664. * schedule the component for redrawing.
  665. * <p>
  666. * This method actually delegates the work of painting to three
  667. * protected methods: <code>paintComponent</code>,
  668. * <code>paintBorder</code>,
  669. * and <code>paintChildren</code>. They're called in the order
  670. * listed to ensure that children appear on top of component itself.
  671. * Generally speaking, the component and its children should not
  672. * paint in the insets area allocated to the border. Subclasses can
  673. * just override this method, as always. A subclass that just
  674. * wants to specialize the UI (look and feel) delegate's
  675. * <code>paint</code> method should just override
  676. * <code>paintComponent</code>.
  677. *
  678. * @param g the <code>Graphics</code> context in which to paint
  679. * @see #paintComponent
  680. * @see #paintBorder
  681. * @see #paintChildren
  682. * @see #getComponentGraphics
  683. * @see #repaint
  684. */
  685. public void paint(Graphics g) {
  686. boolean shouldClearPaintFlags = false;
  687. boolean paintCompleted = false;
  688. if ((getWidth() <= 0) || (getHeight() <= 0)) {
  689. return;
  690. }
  691. Graphics componentGraphics = getComponentGraphics(g);
  692. Graphics co = SwingGraphics.createSwingGraphics(componentGraphics);
  693. try {
  694. RepaintManager repaintManager = RepaintManager.currentManager(this);
  695. Rectangle clipRect = co.getClipBounds();
  696. int clipX;
  697. int clipY;
  698. int clipW;
  699. int clipH;
  700. if (clipRect == null) {
  701. clipX = clipY = 0;
  702. clipW = _bounds.width;
  703. clipH = _bounds.height;
  704. }
  705. else {
  706. clipX = clipRect.x;
  707. clipY = clipRect.y;
  708. clipW = clipRect.width;
  709. clipH = clipRect.height;
  710. }
  711. if(clipW > getWidth()) {
  712. clipW = getWidth();
  713. }
  714. if(clipH > getHeight()) {
  715. clipH = getHeight();
  716. }
  717. if(getParent() != null && !(getParent() instanceof JComponent)) {
  718. adjustPaintFlags();
  719. shouldClearPaintFlags = true;
  720. }
  721. int bw,bh;
  722. boolean printing = getFlag(IS_PRINTING);
  723. if(!printing && repaintManager.isDoubleBufferingEnabled() &&
  724. !getFlag(ANCESTOR_USING_BUFFER) && isDoubleBuffered()) {
  725. paintCompleted = paintDoubleBuffered(this, this, co, clipX, clipY, clipW, clipH);
  726. }
  727. if (!paintCompleted) {
  728. // Will ocassionaly happen in 1.2, especially when printing.
  729. if (clipRect == null) {
  730. co.setClip(clipX, clipY, clipW, clipH);
  731. }
  732. if (!rectangleIsObscured(clipX,clipY,clipW,clipH)) {
  733. if (!printing) {
  734. paintComponent(co);
  735. paintBorder(co);
  736. }
  737. else {
  738. printComponent(co);
  739. printBorder(co);
  740. }
  741. }
  742. if (!printing) {
  743. paintChildren(co);
  744. }
  745. else {
  746. printChildren(co);
  747. }
  748. }
  749. } finally {
  750. co.dispose();
  751. if(shouldClearPaintFlags) {
  752. setFlag(ANCESTOR_USING_BUFFER,false);
  753. setFlag(IS_PAINTING_TILE,false);
  754. setFlag(IS_PRINTING,false);
  755. setFlag(IS_PRINTING_ALL,false);
  756. }
  757. }
  758. }
  759. private void adjustPaintFlags() {
  760. JComponent jparent = null;
  761. Container parent;
  762. for(parent = getParent() ; parent != null ; parent =
  763. parent.getParent()) {
  764. if(parent instanceof JComponent) {
  765. jparent = (JComponent) parent;
  766. if(jparent.getFlag(ANCESTOR_USING_BUFFER))
  767. setFlag(ANCESTOR_USING_BUFFER, true);
  768. if(jparent.getFlag(IS_PAINTING_TILE))
  769. setFlag(IS_PAINTING_TILE, true);
  770. if(jparent.getFlag(IS_PRINTING))
  771. setFlag(IS_PRINTING, true);
  772. if(jparent.getFlag(IS_PRINTING_ALL))
  773. setFlag(IS_PRINTING_ALL, true);
  774. break;
  775. }
  776. }
  777. }
  778. /**
  779. * Invoke this method to print the component. This method invokes
  780. * <code>print</code> on the component.
  781. *
  782. * @param g the <code>Graphics</code> context in which to paint
  783. * @see #print
  784. * @see #printComponent
  785. * @see #printBorder
  786. * @see #printChildren
  787. */
  788. public void printAll(Graphics g) {
  789. setFlag(IS_PRINTING_ALL, true);
  790. try {
  791. print(g);
  792. }
  793. finally {
  794. setFlag(IS_PRINTING_ALL, false);
  795. }
  796. }
  797. /**
  798. * Invoke this method to print the component. This method will
  799. * result in invocations to <code>printComponent</code>,
  800. * <code>printBorder</code> and <code>printChildren</code>. It is
  801. * not recommended that you override this method, instead override
  802. * one of the previously mentioned methods. This method sets the
  803. * component's state such that the double buffer will not be used, eg
  804. * painting will be done directly on the passed in <code>Graphics</code>.
  805. *
  806. * @param g the <code>Graphics</code> context in which to paint
  807. * @see #printComponent
  808. * @see #printBorder
  809. * @see #printChildren
  810. */
  811. public void print(Graphics g) {
  812. setFlag(IS_PRINTING, true);
  813. try {
  814. paint(g);
  815. }
  816. finally {
  817. setFlag(IS_PRINTING, false);
  818. }
  819. }
  820. /**
  821. * This is invoked during a printing operation. This is implemented to
  822. * invoke <code>paintComponent</code> on the component. Override this
  823. * if you wish to add special painting behavior when printing.
  824. *
  825. * @param g the <code>Graphics</code> context in which to paint
  826. * @see #print
  827. * @since 1.3
  828. */
  829. protected void printComponent(Graphics g) {
  830. paintComponent(g);
  831. }
  832. /**
  833. * Prints this component's children. This is implemented to invoke
  834. * <code>paintChildren</code> on the component. Override this if you
  835. * wish to print the children differently than painting.
  836. *
  837. * @param g the <code>Graphics</code> context in which to paint
  838. * @see #print
  839. * @since 1.3
  840. */
  841. protected void printChildren(Graphics g) {
  842. paintChildren(g);
  843. }
  844. /**
  845. * Prints the component's border. This is implemented to invoke
  846. * <code>paintBorder</code> on the component. Override this if you
  847. * wish to print the border differently that it is painted.
  848. *
  849. * @param g the <code>Graphics</code> context in which to paint
  850. * @see #print
  851. * @since 1.3
  852. */
  853. protected void printBorder(Graphics g) {
  854. paintBorder(g);
  855. }
  856. /**
  857. * Returns true if the component is currently painting a tile.
  858. * If this method returns true, paint will be called again for another
  859. * tile. This method returns false if you are not painting a tile or
  860. * if the last tile is painted.
  861. * Use this method to keep some state you might need between tiles.
  862. *
  863. * @return true if the component is currently painting a tile,
  864. * false otherwise
  865. */
  866. public boolean isPaintingTile() {
  867. return getFlag(IS_PAINTING_TILE);
  868. }
  869. /**
  870. * Changes this <code>JComponent</code>'s focus traversal keys to
  871. * CTRL+TAB and CTRL+SHIFT+TAB. Also prevents
  872. * <code>SortingFocusTraversalPolicy</code> from considering descendants
  873. * of this JComponent when computing a focus traversal cycle.
  874. *
  875. * @see java.awt.Component#setFocusTraversalKeys
  876. * @see SortingFocusTraversalPolicy
  877. * @deprecated As of 1.4, replaced by
  878. * <code>Component.setFocusTraversalKeys(int, Set)</code> and
  879. * <code>Container.setFocusCycleRoot(boolean)</code>.
  880. */
  881. public boolean isManagingFocus() {
  882. return false;
  883. }
  884. private void registerNextFocusableComponent() {
  885. registerNextFocusableComponent(getNextFocusableComponent());
  886. }
  887. private void registerNextFocusableComponent(Component
  888. nextFocusableComponent) {
  889. if (nextFocusableComponent == null) {
  890. return;
  891. }
  892. Container nearestRoot =
  893. (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
  894. FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
  895. if (!(policy instanceof LegacyGlueFocusTraversalPolicy)) {
  896. policy = new LegacyGlueFocusTraversalPolicy(policy);
  897. nearestRoot.setFocusTraversalPolicy(policy);
  898. }
  899. ((LegacyGlueFocusTraversalPolicy)policy).
  900. setNextFocusableComponent(this, nextFocusableComponent);
  901. }
  902. private void deregisterNextFocusableComponent() {
  903. Component nextFocusableComponent = getNextFocusableComponent();
  904. if (nextFocusableComponent == null) {
  905. return;
  906. }
  907. Container nearestRoot =
  908. (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
  909. if (nearestRoot == null) {
  910. return;
  911. }
  912. FocusTraversalPolicy policy = nearestRoot.getFocusTraversalPolicy();
  913. if (policy instanceof LegacyGlueFocusTraversalPolicy) {
  914. ((LegacyGlueFocusTraversalPolicy)policy).
  915. unsetNextFocusableComponent(this, nextFocusableComponent);
  916. }
  917. }
  918. /**
  919. * Overrides the default <code>FocusTraversalPolicy</code> for this
  920. * <code>JComponent</code>'s focus traversal cycle by unconditionally
  921. * setting the specified <code>Component</code> as the next
  922. * <code>Component</code> in the cycle, and this <code>JComponent</code>
  923. * as the specified <code>Component</code>'s previous
  924. * <code>Component</code> in the cycle.
  925. *
  926. * @param aComponent the <code>Component</code> that should follow this
  927. * <code>JComponent</code> in the focus traversal cycle
  928. *
  929. * @see #getNextFocusableComponent
  930. * @see java.awt.FocusTraversalPolicy
  931. * @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>
  932. */
  933. public void setNextFocusableComponent(Component aComponent) {
  934. boolean displayable = isDisplayable();
  935. if (displayable) {
  936. deregisterNextFocusableComponent();
  937. }
  938. putClientProperty(NEXT_FOCUS, aComponent);
  939. if (displayable) {
  940. registerNextFocusableComponent(aComponent);
  941. }
  942. }
  943. /**
  944. * Returns the <code>Component</code> set by a prior call to
  945. * <code>setNextFocusableComponent(Component)</code> on this
  946. * <code>JComponent</code>.
  947. *
  948. * @return the <code>Component</code> that will follow this
  949. * <code>JComponent</code> in the focus traversal cycle, or
  950. * <code>null</code> if none has been explicitly specified
  951. *
  952. * @see #setNextFocusableComponent
  953. * @deprecated As of 1.4, replaced by <code>FocusTraversalPolicy</code>.
  954. */
  955. public Component getNextFocusableComponent() {
  956. return (Component)getClientProperty(NEXT_FOCUS);
  957. }
  958. /**
  959. * Provides a hint as to whether or not this <code>JComponent</code>
  960. * should get focus. This is only a hint, and it is up to consumers that
  961. * are requesting focus to honor this property. This is typically honored
  962. * for mouse operations, but not keyboard operations. For example, look
  963. * and feels could verify this property is true before requesting focus
  964. * during a mouse operation. This would often times be used if you did
  965. * not want a mouse press on a <code>JComponent</code> to steal focus,
  966. * but did want the <code>JComponent</code> to be traversable via the
  967. * keyboard. If you do not want this <code>JComponent</code> focusable at
  968. * all, use the <code>setFocusable</code> method instead.
  969. *
  970. * @param requestFocusEnabled Indicates if you want this JComponent to
  971. * be focusable or not
  972. * @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus Specification</a>
  973. * @see java.awt.Component#setFocusable
  974. */
  975. public void setRequestFocusEnabled(boolean requestFocusEnabled) {
  976. setFlag(REQUEST_FOCUS_DISABLED, !requestFocusEnabled);
  977. }
  978. /**
  979. * Returns <code>true</code> if this <code>JComponent</code> should
  980. * get focus; otherwise returns <code>false</code>.
  981. *
  982. * @return <code>true</code> if this component should get focus,
  983. * otherwise returns <code>false</code>
  984. * @see #setRequestFocusEnabled
  985. * @see <a href="../../java/awt/doc-files/FocusSpec.html">Focus
  986. * Specification</a>
  987. * @see java.awt.Component#isFocusable
  988. */
  989. public boolean isRequestFocusEnabled() {
  990. return !getFlag(REQUEST_FOCUS_DISABLED);
  991. }
  992. private boolean runInputVerifier() {
  993. Component focusOwner =
  994. KeyboardFocusManager.getCurrentKeyboardFocusManager().
  995. getFocusOwner();
  996. if (focusOwner == this) {
  997. return true;
  998. }
  999. if (!getVerifyInputWhenFocusTarget()) {
  1000. return true;
  1001. }
  1002. if (focusOwner == null || !(focusOwner instanceof JComponent)) {
  1003. return true;
  1004. }
  1005. JComponent jFocusOwner = (JComponent)focusOwner;
  1006. InputVerifier iv = jFocusOwner.getInputVerifier();
  1007. if (iv == null) {
  1008. return true;
  1009. } else {
  1010. return iv.shouldYieldFocus(jFocusOwner);
  1011. }
  1012. }
  1013. public void requestFocus() {
  1014. if (runInputVerifier()) {
  1015. super.requestFocus();
  1016. }
  1017. }
  1018. /**
  1019. * <code>JComponent</code> overrides <code>requestFocus</code> solely
  1020. * to make the method public so that UI implementations can cause
  1021. * temporary focus changes. This method is not meant for general use,
  1022. * instead developers are urged to call the noarg <code>requestFocus</code>
  1023. * or <code>requestFocusInWindow</code> methods. If the
  1024. * <code>JComponent</code> has an <code>InputVerifier</code>associated
  1025. * with it, the <code>InputVerifier</code> will be messaged.
  1026. * <p>
  1027. * Refer to {@link java.awt.Component#requestFocus(boolean)
  1028. * Component.requestFocus(boolean)} for a complete description
  1029. * of this method.
  1030. *
  1031. * @param temporary boolean indicating if the focus change is temporary
  1032. * @return <code>false</code> if the focus change request is guaranteed to
  1033. * fail; <code>true</code> if it is likely to succeed
  1034. * @see java.awt.Component#requestFocus()
  1035. * @see java.awt.Component#requestFocusInWindow()
  1036. * @see java.awt.Component#requestFocus(boolean)
  1037. * @see java.awt.Component#requestFocusInWindow(boolean)
  1038. * @since 1.4
  1039. */
  1040. public boolean requestFocus(boolean temporary) {
  1041. return (runInputVerifier())
  1042. ? super.requestFocus(temporary)
  1043. : false;
  1044. }
  1045. public boolean requestFocusInWindow() {
  1046. return (runInputVerifier())
  1047. ? super.requestFocusInWindow()
  1048. : false;
  1049. }
  1050. /**
  1051. * <code>JComponent</code> overrides <code>requestFocusInWindow</code>
  1052. * solely to make the method public so that UI implementations can cause
  1053. * temporary focus changes. This method is not meant for general use,
  1054. * instead developers are urged to call the noarg <code>requestFocus</code>
  1055. * or <code>requestFocusInWindow</code> methods. If the
  1056. * <code>JComponent</code> has an <code>InputVerifier</code>associated
  1057. * with it, the <code>InputVerifier</code> will be messaged.
  1058. * <p>
  1059. * Refer to {@link java.awt.Component#requestFocusInWindow(boolean)
  1060. * Component.requestFocusInWindow(boolean)} for a complete description of
  1061. * this method.
  1062. *
  1063. * @param temporary boolean indicating if the focus change is temporary
  1064. * @return <code>false</code> if the focus change request is guaranteed to
  1065. * fail; <code>true</code> if it is likely to succeed
  1066. * @see java.awt.Component#requestFocus()
  1067. * @see java.awt.Component#requestFocusInWindow()
  1068. * @see java.awt.Component#requestFocus(boolean)
  1069. * @see java.awt.Component#requestFocusInWindow(boolean)
  1070. * @since 1.4
  1071. */
  1072. protected boolean requestFocusInWindow(boolean temporary) {
  1073. return (runInputVerifier())
  1074. ? super.requestFocusInWindow(temporary)
  1075. : false;
  1076. }
  1077. /**
  1078. * Requests that this Component get the input focus, and that this
  1079. * Component's top-level ancestor become the focused Window. This component
  1080. * must be displayable, visible, and focusable for the request to be
  1081. * granted.
  1082. * <p>
  1083. * This method is intended for use by focus implementations. Client code
  1084. * should not use this method; instead, it should use
  1085. * <code>requestFocus()</code>.
  1086. *
  1087. * @see #requestFocus()
  1088. */
  1089. public void grabFocus() {
  1090. requestFocus();
  1091. }
  1092. /**
  1093. * Sets the value to indicate whether input verifier for the
  1094. * current focus owner will be called before this component requests
  1095. * focus. The default is true. Set to false on components such as a
  1096. * Cancel button or a scrollbar, which should activate even if the
  1097. * input in the current focus owner is not "passed" by the input
  1098. * verifier for that component.
  1099. *
  1100. * @param verifyInputWhenFocusTarget value for the
  1101. * <code>verifyInputWhenFocusTarget</code> property
  1102. * @see InputVerifier
  1103. * @see #setInputVerifier
  1104. * @see #getInputVerifier
  1105. * @see #getVerifyInputWhenFocusTarget
  1106. *
  1107. * @since 1.3
  1108. * @beaninfo
  1109. * bound: true
  1110. * description: Whether the Component verifies input before accepting
  1111. * focus.
  1112. */
  1113. public void setVerifyInputWhenFocusTarget(boolean
  1114. verifyInputWhenFocusTarget) {
  1115. boolean oldVerifyInputWhenFocusTarget =
  1116. this.verifyInputWhenFocusTarget;
  1117. this.verifyInputWhenFocusTarget = verifyInputWhenFocusTarget;
  1118. firePropertyChange("verifyInputWhenFocusTarget",
  1119. oldVerifyInputWhenFocusTarget,
  1120. verifyInputWhenFocusTarget);
  1121. }
  1122. /**
  1123. * Returns the value that indicates whether the input verifier for the
  1124. * current focus owner will be called before this component requests
  1125. * focus.
  1126. *
  1127. * @return value of the <code>verifyInputWhenFocusTarget</code> property
  1128. *
  1129. * @see InputVerifier
  1130. * @see #setInputVerifier
  1131. * @see #getInputVerifier
  1132. * @see #setVerifyInputWhenFocusTarget
  1133. *
  1134. * @since 1.3
  1135. */
  1136. public boolean getVerifyInputWhenFocusTarget() {
  1137. return verifyInputWhenFocusTarget;
  1138. }
  1139. /**
  1140. * Sets the preferred size of this component.
  1141. * If <code>preferredSize</code> is <code>null</code>, the UI will
  1142. * be asked for the preferred size.
  1143. * @beaninfo
  1144. * preferred: true
  1145. * bound: true
  1146. * description: The preferred size of the component.
  1147. */
  1148. public void setPreferredSize(Dimension preferredSize) {
  1149. Dimension old = this.preferredSize;
  1150. this.preferredSize = preferredSize;
  1151. firePropertyChange("preferredSize", old, preferredSize);
  1152. }
  1153. /**
  1154. * If the <code>preferredSize</code> has been set to a
  1155. * non-<code>null</code> value just returns it.
  1156. * If the UI delegate's <code>getPreferredSize</code>
  1157. * method returns a non <code>null</code> value then return that;
  1158. * otherwise defer to the component's layout manager.
  1159. *
  1160. * @return the value of the <code>preferredSize</code> property
  1161. * @see #setPreferredSize
  1162. * @see ComponentUI
  1163. */
  1164. public Dimension getPreferredSize() {
  1165. if (preferredSize != null) {
  1166. return preferredSize;
  1167. }
  1168. Dimension size = null;
  1169. if (ui != null) {
  1170. size = ui.getPreferredSize(this);
  1171. }
  1172. return (size != null) ? size : super.getPreferredSize();
  1173. }
  1174. /**
  1175. * Sets the maximum size of this component to a constant
  1176. * value. Subsequent calls to <code>getMaximumSize</code> will always
  1177. * return this value; the component's UI will not be asked
  1178. * to compute it. Setting the maximum size to <code>null</code>
  1179. * restores the default behavior.
  1180. *
  1181. * @param maximumSize a <code>Dimension</code> containing the
  1182. * desired maximum allowable size
  1183. * @see #getMaximumSize
  1184. * @beaninfo
  1185. * bound: true
  1186. * description: The maximum size of the component.
  1187. */
  1188. public void setMaximumSize(Dimension maximumSize) {
  1189. Dimension old = this.maximumSize;
  1190. this.maximumSize = maximumSize;
  1191. firePropertyChange("maximumSize", old, maximumSize);
  1192. }
  1193. /**
  1194. * If the maximum size has been set to a non-<code>null</code> value
  1195. * just returns it. If the UI delegate's <code>getMaximumSize</code>
  1196. * method returns a non-<code>null</code> value then return that;
  1197. * otherwise defer to the component's layout manager.
  1198. *
  1199. * @return the value of the <code>maximumSize</code> property
  1200. * @see #setMaximumSize
  1201. * @see ComponentUI
  1202. */
  1203. public Dimension getMaximumSize() {
  1204. if (maximumSize != null) {
  1205. return maximumSize;
  1206. }
  1207. Dimension size = null;
  1208. if (ui != null) {
  1209. size = ui.getMaximumSize(this);
  1210. }
  1211. return (size != null) ? size : super.getMaximumSize();
  1212. }
  1213. /**
  1214. * Sets the minimum size of this component to a constant
  1215. * value. Subsequent calls to <code>getMinimumSize</code> will always
  1216. * return this value; the component's UI will not be asked
  1217. * to compute it. Setting the minimum size to <code>null</code>
  1218. * restores the default behavior.
  1219. *
  1220. * @param minimumSize the new minimum size of this component
  1221. * @see #getMinimumSize
  1222. * @beaninfo
  1223. * bound: true
  1224. * description: The minimum size of the component.
  1225. */
  1226. public void setMinimumSize(Dimension minimumSize) {
  1227. Dimension old = this.minimumSize;
  1228. this.minimumSize = minimumSize;
  1229. firePropertyChange("minimumSize", old, minimumSize);
  1230. }
  1231. /**
  1232. * If the minimum size has been set to a non-<code>null</code> value
  1233. * just returns it. If the UI delegate's <code>getMinimumSize</code>
  1234. * method returns a non-<code>null</code> value then return that; otherwise
  1235. * defer to the component's layout manager.
  1236. *
  1237. * @return the value of the <code>minimumSize</code> property
  1238. * @see #setMinimumSize
  1239. * @see ComponentUI
  1240. */
  1241. public Dimension getMinimumSize() {
  1242. if (minimumSize != null) {
  1243. return minimumSize;
  1244. }
  1245. Dimension size = null;
  1246. if (ui != null) {
  1247. size = ui.getMinimumSize(this);
  1248. }
  1249. return (size != null) ? size : super.getMinimumSize();
  1250. }
  1251. /**
  1252. * Returns true if the minimum size has been set to a non-<code>null</code>
  1253. * value otherwise returns false.
  1254. *
  1255. * @return true if <code>minimumSize</code> is non-<code>null</code>,
  1256. * false otherwise
  1257. * @since 1.3
  1258. */
  1259. public boolean isMinimumSizeSet() {
  1260. return minimumSize != null;
  1261. }
  1262. /**
  1263. * Returns true if the preferred size has been set to a
  1264. * non-<code>null</code> value otherwise returns false.
  1265. *
  1266. * @return true if <code>preferredSize</code> is non-<code>null</code>,
  1267. * false otherwise
  1268. * @since 1.3
  1269. */
  1270. public boolean isPreferredSizeSet() {
  1271. return preferredSize != null;
  1272. }
  1273. /**
  1274. * Returns true if the maximum size has been set to a non-<code>null</code>
  1275. * value otherwise returns false.
  1276. *
  1277. * @return true if <code>maximumSize</code> is non-<code>null</code>,
  1278. * false otherwise
  1279. * @since 1.3
  1280. */
  1281. public boolean isMaximumSizeSet() {
  1282. return maximumSize != null;
  1283. }
  1284. /**
  1285. * Gives the UI delegate an opportunity to define the precise
  1286. * shape of this component for the sake of mouse processing.
  1287. *
  1288. * @return true if this component logically contains x,y
  1289. * @see java.awt.Component#contains(int, int)
  1290. * @see ComponentUI
  1291. */
  1292. public boolean contains(int x, int y) {
  1293. return (ui != null) ? ui.contains(this, x, y) : super.contains(x, y);
  1294. }
  1295. /**
  1296. * Sets the border of this component. The <code>Border</code> object is
  1297. * responsible for defining the insets for the component
  1298. * (overriding any insets set directly on the component) and
  1299. * for optionally rendering any border decorations within the
  1300. * bounds of those insets. Borders should be used (rather
  1301. * than insets) for creating both decorative and non-decorative
  1302. * (such as margins and padding) regions for a swing component.
  1303. * Compound borders can be used to nest multiple borders within a
  1304. * single component.
  1305. * <p>
  1306. * This is a bound property.
  1307. *
  1308. * @param border the border to be rendered for this component
  1309. * @see Border
  1310. * @see CompoundBorder
  1311. * @beaninfo
  1312. * bound: true
  1313. * preferred: true
  1314. * attribute: visualUpdate true
  1315. * description: The component's border.
  1316. */
  1317. public void setBorder(Border border) {
  1318. Border oldBorder = this.border;
  1319. this.border = border;
  1320. firePropertyChange("border", oldBorder, border);
  1321. if (border != oldBorder) {
  1322. if (border == null || oldBorder == null ||
  1323. !(border.getBorderInsets(this).equals(oldBorder.getBorderInsets(this)))) {
  1324. revalidate();
  1325. }
  1326. repaint();
  1327. }
  1328. }
  1329. /**
  1330. * Returns the border of this component or <code>null</code> if no
  1331. * border is currently set.
  1332. *
  1333. * @return the border object for this component
  1334. * @see #setBorder
  1335. */
  1336. public Border getBorder() {
  1337. return border;
  1338. }
  1339. /**
  1340. * If a border has been set on this component, returns the
  1341. * border's insets; otherwise calls <code>super.getInsets</code>.
  1342. *
  1343. * @return the value of the insets property
  1344. * @see #setBorder
  1345. */
  1346. public Insets getInsets() {
  1347. if (border != null) {
  1348. return border.getBorderInsets(this);
  1349. }
  1350. return super.getInsets();
  1351. }
  1352. /**
  1353. * Returns an <code>Insets</code> object containing this component's inset
  1354. * values. The passed-in <code>Insets</code> object will be reused
  1355. * if possible.
  1356. * Calling methods cannot assume that the same object will be returned,
  1357. * however. All existing values within this object are overwritten.
  1358. * If <code>insets</code> is null, this will allocate a new one.
  1359. *
  1360. * @param insets the <code>Insets</code> object, which can be reused
  1361. * @return the <code>Insets</code> object
  1362. * @see #getInsets
  1363. * @beaninfo
  1364. * expert: true
  1365. */
  1366. public Insets getInsets(Insets insets) {
  1367. if (insets == null) {
  1368. insets = new Insets(0, 0, 0, 0);
  1369. }
  1370. if (border != null) {
  1371. if (border instanceof AbstractBorder) {
  1372. return ((AbstractBorder)border).getBorderInsets(this, insets);
  1373. } else {
  1374. // Can't reuse border insets because the Border interface
  1375. // can't be enhanced.
  1376. return border.getBorderInsets(this);
  1377. }
  1378. } else {
  1379. // super.getInsets() always returns an Insets object with
  1380. // all of its value zeroed. No need for a new object here.
  1381. insets.left = insets.top = insets.right = insets.bottom = 0;
  1382. return insets;
  1383. }
  1384. }
  1385. /**
  1386. * Overrides <code>Container.getAlignmentY</code> to return
  1387. * the horizontal alignment.
  1388. *
  1389. * @return the value of the <code>alignmentY</code> property
  1390. * @see #setAlignmentY
  1391. * @see java.awt.Component#getAlignmentY
  1392. */
  1393. public float getAlignmentY() {
  1394. return (alignmentY != null) ? alignmentY.floatValue() : super.getAlignmentY();
  1395. }
  1396. /**
  1397. * Sets the the horizontal alignment.
  1398. *
  1399. * @param alignmentY the new horizontal alignment
  1400. * @see #getAlignmentY
  1401. * @beaninfo
  1402. * description: The preferred vertical alignment of the component.
  1403. */
  1404. public void setAlignmentY(float alignmentY) {
  1405. this.alignmentY = new Float(alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY);
  1406. }
  1407. /**
  1408. * Overrides <code>Container.getAlignmentX</code> to return
  1409. * the vertical alignment.
  1410. *
  1411. * @return the value of the <code>alignmentX</code> property
  1412. * @see #setAlignmentX
  1413. * @see java.awt.Component#getAlignmentX
  1414. */
  1415. public float getAlignmentX() {
  1416. return (alignmentX != null) ? alignmentX.floatValue() : super.getAlignmentX();
  1417. }
  1418. /**
  1419. * Sets the the vertical alignment.
  1420. *
  1421. * @param alignmentX the new vertical alignment
  1422. * @see #getAlignmentX
  1423. * @beaninfo
  1424. * description: The preferred horizontal alignment of the component.
  1425. */
  1426. public void setAlignmentX(float alignmentX) {
  1427. this.alignmentX = new Float(alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX);
  1428. }
  1429. /**
  1430. * Sets the input verifier for this component.
  1431. *
  1432. * @param inputVerifier the new input verifier
  1433. * @since 1.3
  1434. * @see InputVerifier
  1435. * @beaninfo
  1436. * bound: true
  1437. * description: The component's input verifier.
  1438. */
  1439. public void setInputVerifier(InputVerifier inputVerifier) {
  1440. InputVerifier oldInputVerifier = this.inputVerifier;
  1441. this.inputVerifier = inputVerifier;
  1442. firePropertyChange("inputVerifier", oldInputVerifier, inputVerifier);
  1443. }
  1444. /**
  1445. * Returns the input verifier for this component.
  1446. *
  1447. * @return the <code>inputVerifier</code> property
  1448. * @since 1.3
  1449. * @see InputVerifier
  1450. */
  1451. public InputVerifier getInputVerifier() {
  1452. return inputVerifier;
  1453. }
  1454. /**
  1455. * Returns this component's graphics context, which lets you draw
  1456. * on a component. Use this method get a <code>Graphics</code> object and
  1457. * then invoke operations on that object to draw on the component.
  1458. * @return this components graphics context
  1459. */
  1460. public Graphics getGraphics() {
  1461. if (shouldDebugGraphics() != 0) {
  1462. DebugGraphics graphics = new DebugGraphics(super.getGraphics(),
  1463. this);
  1464. return graphics;
  1465. }
  1466. return super.getGraphics();
  1467. }
  1468. /** Enables or disables diagnostic information about every graphics
  1469. * operation performed within the component or one of its children.
  1470. *
  1471. * @param debugOptions determines how the component should display
  1472. * the information; one of the following options:
  1473. * <ul>
  1474. * <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
  1475. * <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
  1476. * times.
  1477. * <li>DebugGraphics.BUFFERED_OPTION - creates an
  1478. * <code>ExternalWindow</code> that displays the operations
  1479. * performed on the View's offscreen buffer.
  1480. * <li>DebugGraphics.NONE_OPTION disables debugging.
  1481. * <li>A value of 0 causes no changes to the debugging options.
  1482. * </ul>
  1483. * <code>debugOptions</code> is bitwise OR'd into the current value
  1484. *
  1485. * @beaninfo
  1486. * preferred: true
  1487. * enum: NONE_OPTION DebugGraphics.NONE_OPTION
  1488. * LOG_OPTION DebugGraphics.LOG_OPTION
  1489. * FLASH_OPTION DebugGraphics.FLASH_OPTION
  1490. * BUFFERED_OPTION DebugGraphics.BUFFERED_OPTION
  1491. * description: Diagnostic options for graphics operations.
  1492. */
  1493. public void setDebugGraphicsOptions(int debugOptions) {
  1494. DebugGraphics.setDebugOptions(this, debugOptions);
  1495. }
  1496. /** Returns the state of graphics debugging.
  1497. *
  1498. * @return a bitwise OR'd flag of zero or more of the following options:
  1499. * <ul>
  1500. * <li>DebugGraphics.LOG_OPTION - causes a text message to be printed.
  1501. * <li>DebugGraphics.FLASH_OPTION - causes the drawing to flash several
  1502. * times.
  1503. * <li>DebugGraphics.BUFFERED_OPTION - creates an
  1504. * <code>ExternalWindow</code> that displays the operations
  1505. * performed on the View's offscreen buffer.
  1506. * <li>DebugGraphics.NONE_OPTION disables debugging.
  1507. * <li>A value of 0 causes no changes to the debugging options.
  1508. * </ul>
  1509. * @see #setDebugGraphicsOptions
  1510. */
  1511. public int getDebugGraphicsOptions() {
  1512. return DebugGraphics.getDebugOptions(this);
  1513. }
  1514. /**
  1515. * Returns true if debug information is enabled for this
  1516. * <code>JComponent</code> or one of its parents.
  1517. */
  1518. int shouldDebugGraphics() {
  1519. return DebugGraphics.shouldComponentDebug(this);
  1520. }
  1521. /**
  1522. * This method is now obsolete, please use a combination of
  1523. * <code>getActionMap()</code> and <code>getInputMap()</code> for
  1524. * similiar behavior. For example, to bind the <code>KeyStroke</code>
  1525. * <code>aKeyStroke</code> to the <code>Action</code> <code>anAction</code>
  1526. * now use:
  1527. * <pre>
  1528. * component.getInputMap().put(aKeyStroke, aCommand);
  1529. * component.getActionMap().put(aCommmand, anAction);
  1530. * </pre>
  1531. * The above assumes you want the binding to be applicable for
  1532. * <code>WHEN_FOCUSED</code>. To register bindings for other focus
  1533. * states use the <code>getInputMap</code> method that takes an integer.
  1534. * <p>
  1535. * Register a new keyboard action.
  1536. * <code>anAction</code> will be invoked if a key event matching
  1537. * <code>aKeyStroke</code> occurs and <code>aCondition</code> is verified.
  1538. * The <code>KeyStroke</code> object defines a
  1539. * particular combination of a keyboard key and one or more modifiers
  1540. * (alt, shift, ctrl, meta).
  1541. * <p>
  1542. * The <code>aCommand</code> will be set in the delivered event if
  1543. * specified.
  1544. * <p>
  1545. * The <code>aCondition</code> can be one of:
  1546. * <blockquote>
  1547. * <DL>
  1548. * <DT>WHEN_FOCUSED
  1549. * <DD>The action will be invoked only when the keystroke occurs
  1550. * while the component has the focus.
  1551. * <DT>WHEN_IN_FOCUSED_WINDOW
  1552. * <DD>The action will be invoked when the keystroke occurs while
  1553. * the component has the focus or if the component is in the
  1554. * window that has the focus. Note that the component need not
  1555. * be an immediate descendent of the window -- it can be
  1556. * anywhere in the window's containment hierarchy. In other
  1557. * words, whenever <em>any</em> component in the window has the focus,
  1558. * the action registered with this component is invoked.
  1559. * <DT>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  1560. * <DD>The action will be invoked when the keystroke occurs while the
  1561. * component has the focus or if the component is an ancestor of
  1562. * the component that has the focus.
  1563. * </DL>
  1564. * </blockquote>
  1565. * <p>
  1566. * The combination of keystrokes and conditions lets you define high
  1567. * level (semantic) action events for a specified keystroke+modifier
  1568. * combination (using the KeyStroke class) and direct to a parent or
  1569. * child of a component that has the focus, or to the component itself.
  1570. * In other words, in any hierarchical structure of components, an
  1571. * arbitrary key-combination can be immediately directed to the
  1572. * appropriate component in the hierarchy, and cause a specific method
  1573. * to be invoked (usually by way of adapter objects).
  1574. * <p>
  1575. * If an action has already been registered for the receiving
  1576. * container, with the same charCode and the same modifiers,
  1577. * <code>anAction</code> will replace the action.
  1578. *
  1579. * @param anAction the <code>Action</code> to be registered
  1580. * @param aCommand the command to be set in the delivered event
  1581. * @param aKeyStroke the <code>KeyStroke</code> to bind to the action
  1582. * @param aCondition the condition that needs to be met, see above
  1583. * @see KeyStroke
  1584. */
  1585. public void registerKeyboardAction(ActionListener anAction,String aCommand,KeyStroke aKeyStroke,int aCondition) {
  1586. InputMap inputMap = getInputMap(aCondition, true);
  1587. if (inputMap != null) {
  1588. ActionMap actionMap = getActionMap(true);
  1589. ActionStandin action = new ActionStandin(anAction, aCommand);
  1590. inputMap.put(aKeyStroke, action);
  1591. if (actionMap != null) {
  1592. actionMap.put(action, action);
  1593. }
  1594. }
  1595. }
  1596. /**
  1597. * Registers any bound <code>WHEN_IN_FOCUSED_WINDOW</code> actions with
  1598. * the <code>KeyboardManager</code>. If <code>onlyIfNew</code>
  1599. * is true only actions that haven't been registered are pushed
  1600. * to the <code>KeyboardManager</code>
  1601. * otherwise all actions are pushed to the <code>KeyboardManager</code>.
  1602. *
  1603. * @param onlyIfNew if true, only actions that haven't been registered
  1604. * are pushed to the <code>KeyboardManager</code>
  1605. */
  1606. private void registerWithKeyboardManager(boolean onlyIfNew) {
  1607. InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
  1608. KeyStroke[] strokes;
  1609. Hashtable registered = (Hashtable)getClientProperty
  1610. (WHEN_IN_FOCUSED_WINDOW_BINDINGS);
  1611. if (inputMap != null) {
  1612. // Push any new KeyStrokes to the KeyboardManager.
  1613. strokes = inputMap.allKeys();
  1614. if (strokes != null) {
  1615. for (int counter = strokes.length - 1; counter >= 0;
  1616. counter--) {
  1617. if (!onlyIfNew || registered == null ||
  1618. registered.get(strokes[counter]) == null) {
  1619. registerWithKeyboardManager(strokes[counter]);
  1620. }
  1621. if (registered != null) {
  1622. registered.remove(strokes[counter]);
  1623. }
  1624. }
  1625. }
  1626. }
  1627. else {
  1628. strokes = null;
  1629. }
  1630. // Remove any old ones.
  1631. if (registered != null && registered.size() > 0) {
  1632. Enumeration keys = registered.keys();
  1633. while (keys.hasMoreElements()) {
  1634. KeyStroke ks = (KeyStroke)keys.nextElement();
  1635. unregisterWithKeyboardManager(ks);
  1636. }
  1637. registered.clear();
  1638. }
  1639. // Updated the registered Hashtable.
  1640. if (strokes != null && strokes.length > 0) {
  1641. if (registered == null) {
  1642. registered = new Hashtable(strokes.length);
  1643. putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, registered);
  1644. }
  1645. for (int counter = strokes.length - 1; counter >= 0; counter--) {
  1646. registered.put(strokes[counter], strokes[counter]);
  1647. }
  1648. }
  1649. else {
  1650. putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
  1651. }
  1652. }
  1653. /**
  1654. * Unregisters all the previously registered
  1655. * <code>WHEN_IN_FOCUSED_WINDOW</code> <code>KeyStroke</code> bindings.
  1656. */
  1657. private void unregisterWithKeyboardManager() {
  1658. Hashtable registered = (Hashtable)getClientProperty
  1659. (WHEN_IN_FOCUSED_WINDOW_BINDINGS);
  1660. if (registered != null && registered.size() > 0) {
  1661. Enumeration keys = registered.keys();
  1662. while (keys.hasMoreElements()) {
  1663. KeyStroke ks = (KeyStroke)keys.nextElement();
  1664. unregisterWithKeyboardManager(ks);
  1665. }
  1666. }
  1667. putClientProperty(WHEN_IN_FOCUSED_WINDOW_BINDINGS, null);
  1668. }
  1669. /**
  1670. * Invoked from <code>ComponentInputMap</code> when its bindings change.
  1671. * If <code>inputMap</code> is the current <code>windowInputMap</code>
  1672. * (or a parent of the window <code>InputMap</code>)
  1673. * the <code>KeyboardManager</code> is notified of the new bindings.
  1674. *
  1675. * @param inputMap the map containing the new bindings
  1676. */
  1677. void componentInputMapChanged(ComponentInputMap inputMap) {
  1678. InputMap km = getInputMap(WHEN_IN_FOCUSED_WINDOW, false);
  1679. while (km != inputMap && km != null) {
  1680. km = (ComponentInputMap)km.getParent();
  1681. }
  1682. if (km != null) {
  1683. registerWithKeyboardManager(false);
  1684. }
  1685. }
  1686. private void registerWithKeyboardManager(KeyStroke aKeyStroke) {
  1687. KeyboardManager.getCurrentManager().registerKeyStroke(aKeyStroke,this);
  1688. }
  1689. private void unregisterWithKeyboardManager(KeyStroke aKeyStroke) {
  1690. KeyboardManager.getCurrentManager().unregisterKeyStroke(aKeyStroke,
  1691. this);
  1692. }
  1693. /**
  1694. * This method is now obsolete, please use a combination of
  1695. * <code>getActionMap()</code> and <code>getInputMap()</code> for
  1696. * similiar behavior.
  1697. */
  1698. public void registerKeyboardAction(ActionListener anAction,KeyStroke aKeyStroke,int aCondition) {
  1699. registerKeyboardAction(anAction,null,aKeyStroke,aCondition);
  1700. }
  1701. /**
  1702. * This method is now obsolete. To unregister an existing binding
  1703. * you can either remove the binding from the
  1704. * <code>ActionMap/InputMap</code>, or place a dummy binding the
  1705. * <code>InputMap</code>. Removing the binding from the
  1706. * <code>InputMap</code> allows bindings in parent <code>InputMap</code>s
  1707. * to be active, whereas putting a dummy binding in the
  1708. * <code>InputMap</code> effectively disables
  1709. * the binding from ever happening.
  1710. * <p>
  1711. * Unregisters a keyboard action.
  1712. * This will remove the binding from the <code>ActionMap</code>
  1713. * (if it exists) as well as the <code>InputMap</code>s.
  1714. */
  1715. public void unregisterKeyboardAction(KeyStroke aKeyStroke) {
  1716. ActionMap am = getActionMap(false);
  1717. for (int counter = 0; counter < 3; counter++) {
  1718. InputMap km = getInputMap(counter, false);
  1719. if (km != null) {
  1720. Object actionID = km.get(aKeyStroke);
  1721. if (am != null && actionID != null) {
  1722. am.remove(actionID);
  1723. }
  1724. km.remove(aKeyStroke);
  1725. }
  1726. }
  1727. }
  1728. /**
  1729. * Returns the <code>KeyStrokes</code> that will initiate
  1730. * registered actions.
  1731. *
  1732. * @return an array of <code>KeyStroke</code> objects
  1733. * @see #registerKeyboardAction
  1734. */
  1735. public KeyStroke[] getRegisteredKeyStrokes() {
  1736. int[] counts = new int[3];
  1737. KeyStroke[][] strokes = new KeyStroke[3][];
  1738. for (int counter = 0; counter < 3; counter++) {
  1739. InputMap km = getInputMap(counter, false);
  1740. strokes[counter] = (km != null) ? km.allKeys() : null;
  1741. counts[counter] = (strokes[counter] != null) ?
  1742. strokes[counter].length : 0;
  1743. }
  1744. KeyStroke[] retValue = new KeyStroke[counts[0] + counts[1] +
  1745. counts[2]];
  1746. for (int counter = 0, last = 0; counter < 3; counter++) {
  1747. if (counts[counter] > 0) {
  1748. System.arraycopy(strokes[counter], 0, retValue, last,
  1749. counts[counter]);
  1750. last += counts[counter];
  1751. }
  1752. }
  1753. return retValue;
  1754. }
  1755. /**
  1756. * Returns the condition that determines whether a registered action
  1757. * occurs in response to the specified keystroke.
  1758. * <p>
  1759. * For Java 2 platform v1.3, a <code>KeyStroke</code> can be associated
  1760. * with more than one condition.
  1761. * For example, 'a' could be bound for the two
  1762. * conditions <code>WHEN_FOCUSED</code> and
  1763. * <code>WHEN_IN_FOCUSED_WINDOW</code> condition.
  1764. *
  1765. * @return the action-keystroke condition
  1766. */
  1767. public int getConditionForKeyStroke(KeyStroke aKeyStroke) {
  1768. for (int counter = 0; counter < 3; counter++) {
  1769. InputMap inputMap = getInputMap(counter, false);
  1770. if (inputMap != null && inputMap.get(aKeyStroke) != null) {
  1771. return counter;
  1772. }
  1773. }
  1774. return UNDEFINED_CONDITION;
  1775. }
  1776. /**
  1777. * Returns the object that will perform the action registered for a
  1778. * given keystroke.
  1779. *
  1780. * @return the <code>ActionListener</code>
  1781. * object invoked when the keystroke occurs
  1782. */
  1783. public ActionListener getActionForKeyStroke(KeyStroke aKeyStroke) {
  1784. ActionMap am = getActionMap(false);
  1785. if (am == null) {
  1786. return null;
  1787. }
  1788. for (int counter = 0; counter < 3; counter++) {
  1789. InputMap inputMap = getInputMap(counter, false);
  1790. if (inputMap != null) {
  1791. Object actionBinding = inputMap.get(aKeyStroke);
  1792. if (actionBinding != null) {
  1793. Action action = am.get(actionBinding);
  1794. if (action instanceof ActionStandin) {
  1795. return ((ActionStandin)action).actionListener;
  1796. }
  1797. return action;
  1798. }
  1799. }
  1800. }
  1801. return null;
  1802. }
  1803. /**
  1804. * Unregisters all the bindings in the first tier <code>InputMaps</code>
  1805. * and <code>ActionMap</code>. This has the effect of removing any
  1806. * local bindings, and allowing the bindings defined in parent
  1807. * <code>InputMap/ActionMaps</code>
  1808. * (the UI is usually defined in the second tier) to persist.
  1809. */
  1810. public void resetKeyboardActions() {
  1811. // Keys
  1812. for (int counter = 0; counter < 3; counter++) {
  1813. InputMap inputMap = getInputMap(counter, false);
  1814. if (inputMap != null) {
  1815. inputMap.clear();
  1816. }
  1817. }
  1818. // Actions
  1819. ActionMap am = getActionMap(false);
  1820. if (am != null) {
  1821. am.clear();
  1822. }
  1823. }
  1824. /**
  1825. * Sets the <code>InputMap</code> to use under the condition
  1826. * <code>condition</code> to
  1827. * <code>map</code>. A <code>null</code> value implies you
  1828. * do not want any bindings to be used, even from the UI. This will
  1829. * not reinstall the UI <code>InputMap</code> (if there was one).
  1830. * <code>condition</code> has one of the following values:
  1831. * <ul>
  1832. * <li><code>WHEN_IN_FOCUSED_WINDOW</code>
  1833. * <li><code>WHEN_FOCUSED</code>
  1834. * <li><code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code>
  1835. * </ul>
  1836. * If <code>condition</code> is <code>WHEN_IN_FOCUSED_WINDOW</code>
  1837. * and <code>map</code> is not a <code>ComponentInputMap</code>, an
  1838. * <code>IllegalArgumentException</code> will be thrown.
  1839. * Similarly, if <code>condition</code> is not one of the values
  1840. * listed, an <code>IllegalArgumentException</code> will be thrown.
  1841. *
  1842. * @param condition one of the values listed above
  1843. * @param map the <code>InputMap</code> to use for the given condition
  1844. * @exception IllegalArgumentException if <code>condition</code> is
  1845. * <code>WHEN_IN_FOCUSED_WINDOW</code> and <code>map</code>
  1846. * is not an instance of <code>ComponentInputMap</code> or
  1847. * if <code>condition</code> is not one of the legal values
  1848. * specified above
  1849. * @since 1.3
  1850. */
  1851. public final void setInputMap(int condition, InputMap map) {
  1852. switch (condition) {
  1853. case WHEN_IN_FOCUSED_WINDOW:
  1854. if (map != null && !(map instanceof ComponentInputMap)) {
  1855. throw new IllegalArgumentException("WHEN_IN_FOCUSED_WINDOW InputMaps must be of type ComponentInputMap");
  1856. }
  1857. windowInputMap = (ComponentInputMap)map;
  1858. setFlag(WIF_INPUTMAP_CREATED, true);
  1859. registerWithKeyboardManager(false);
  1860. break;
  1861. case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
  1862. ancestorInputMap = map;
  1863. setFlag(ANCESTOR_INPUTMAP_CREATED, true);
  1864. break;
  1865. case WHEN_FOCUSED:
  1866. focusInputMap = map;
  1867. setFlag(FOCUS_INPUTMAP_CREATED, true);
  1868. break;
  1869. default:
  1870. throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
  1871. }
  1872. }
  1873. /**
  1874. * Returns the <code>InputMap</code> that is used during
  1875. * <code>condition</code>.
  1876. *
  1877. * @param condition one of WHEN_IN_FOCUSED_WINDOW, WHEN_FOCUSED,
  1878. * WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  1879. * @return the <code>InputMap</code> for the specified
  1880. * <code>condition</code>
  1881. * @since 1.3
  1882. */
  1883. public final InputMap getInputMap(int condition) {
  1884. return getInputMap(condition, true);
  1885. }
  1886. /**
  1887. * Returns the <code>InputMap</code> that is used when the
  1888. * component has focus.
  1889. * This is convenience method for <code>getInputMap(WHEN_FOCUSED)</code>.
  1890. *
  1891. * @return the <code>InputMap</code> used when the component has focus
  1892. * @since JDK1.3
  1893. */
  1894. public final InputMap getInputMap() {
  1895. return getInputMap(WHEN_FOCUSED, true);
  1896. }
  1897. /**
  1898. * Sets the <code>ActionMap</code> to <code>am</code>. This does not set
  1899. * the parent of the <code>am</code> to be the <code>ActionMap</code>
  1900. * from the UI (if there was one), it is up to the caller to have done this.
  1901. *
  1902. * @param am the new <code>ActionMap</code>
  1903. * @since 1.3
  1904. */
  1905. public final void setActionMap(ActionMap am) {
  1906. actionMap = am;
  1907. setFlag(ACTIONMAP_CREATED, true);
  1908. }
  1909. /**
  1910. * Returns the <code>ActionMap</code> used to determine what
  1911. * <code>Action</code> to fire for particular <code>KeyStroke</code>
  1912. * binding. The returned <code>ActionMap</code>, unless otherwise
  1913. * set, will have the <code>ActionMap</code> from the UI set as the parent.
  1914. *
  1915. * @return the <code>ActionMap</code> containing the key/action bindings
  1916. * @since 1.3
  1917. */
  1918. public final ActionMap getActionMap() {
  1919. return getActionMap(true);
  1920. }
  1921. /**
  1922. * Returns the <code>InputMap</code> to use for condition
  1923. * <code>condition</code>. If the <code>InputMap</code> hasn't
  1924. * been created, and <code>create</code> is
  1925. * true, it will be created.
  1926. *
  1927. * @param condition one of the following values:
  1928. * <ul>
  1929. * <li>JComponent.FOCUS_INPUTMAP_CREATED
  1930. * <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  1931. * <li>JComponent.WHEN_IN_FOCUSED_WINDOW
  1932. * </ul>
  1933. * @param create if true, create the <code>InputMap</code> if it
  1934. * is not already created
  1935. * @return the <code>InputMap</code> for the given <code>condition</code>
  1936. * if <code>create</code> is false and the <code>InputMap</code>
  1937. * hasn't been created, returns <code>null</code>
  1938. * @exception IllegalArgumentException if <code>condition</code>
  1939. * is not one of the legal values listed above
  1940. */
  1941. final InputMap getInputMap(int condition, boolean create) {
  1942. switch (condition) {
  1943. case WHEN_FOCUSED:
  1944. if (getFlag(FOCUS_INPUTMAP_CREATED)) {
  1945. return focusInputMap;
  1946. }
  1947. // Hasn't been created yet.
  1948. if (create) {
  1949. InputMap km = new InputMap();
  1950. setInputMap(condition, km);
  1951. return km;
  1952. }
  1953. break;
  1954. case WHEN_ANCESTOR_OF_FOCUSED_COMPONENT:
  1955. if (getFlag(ANCESTOR_INPUTMAP_CREATED)) {
  1956. return ancestorInputMap;
  1957. }
  1958. // Hasn't been created yet.
  1959. if (create) {
  1960. InputMap km = new InputMap();
  1961. setInputMap(condition, km);
  1962. return km;
  1963. }
  1964. break;
  1965. case WHEN_IN_FOCUSED_WINDOW:
  1966. if (getFlag(WIF_INPUTMAP_CREATED)) {
  1967. return windowInputMap;
  1968. }
  1969. // Hasn't been created yet.
  1970. if (create) {
  1971. ComponentInputMap km = new ComponentInputMap(this);
  1972. setInputMap(condition, km);
  1973. return km;
  1974. }
  1975. break;
  1976. default:
  1977. throw new IllegalArgumentException("condition must be one of JComponent.WHEN_IN_FOCUSED_WINDOW, JComponent.WHEN_FOCUSED or JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT");
  1978. }
  1979. return null;
  1980. }
  1981. /**
  1982. * Finds and returns the appropriate <code>ActionMap</code>.
  1983. *
  1984. * @param create if true, create the <code>ActionMap</code> if it
  1985. * is not already created
  1986. * @return the <code>ActionMap</code> for this component; if the
  1987. * <code>create</code> flag is false and there is no
  1988. * current <code>ActionMap</code>, returns <code>null</code>
  1989. */
  1990. final ActionMap getActionMap(boolean create) {
  1991. if (getFlag(ACTIONMAP_CREATED)) {
  1992. return actionMap;
  1993. }
  1994. // Hasn't been created.
  1995. if (create) {
  1996. ActionMap am = new ActionMap();
  1997. setActionMap(am);
  1998. return am;
  1999. }
  2000. return null;
  2001. }
  2002. /**
  2003. * Requests focus on this <code>JComponent</code>'s
  2004. * <code>FocusTraversalPolicy</code>'s default <code>Component</code>.
  2005. * If this <code>JComponent</code> is a focus cycle root, then its
  2006. * <code>FocusTraversalPolicy</code> is used. Otherwise, the
  2007. * <code>FocusTraversalPolicy</code> of this <code>JComponent</code>'s
  2008. * focus-cycle-root ancestor is used.
  2009. *
  2010. * @see java.awt.FocusTraversalPolicy#getDefaultComponent
  2011. * @deprecated As of 1.4, replaced by
  2012. * <code>FocusTraversalPolicy.getDefaultComponent(Container).requestFocus()</code>
  2013. */
  2014. public boolean requestDefaultFocus() {
  2015. Container nearestRoot =
  2016. (isFocusCycleRoot()) ? this : getFocusCycleRootAncestor();
  2017. if (nearestRoot == null) {
  2018. return false;
  2019. }
  2020. Component comp = nearestRoot.getFocusTraversalPolicy().
  2021. getDefaultComponent(nearestRoot);
  2022. if (comp != null) {
  2023. comp.requestFocus();
  2024. return true;
  2025. } else {
  2026. return false;
  2027. }
  2028. }
  2029. /**
  2030. * Makes the component visible or invisible.
  2031. * Overrides <code>Component.setVisible</code>.
  2032. *
  2033. * @param aFlag true to make the component visible; false to
  2034. * make it invisible
  2035. *
  2036. * @beaninfo
  2037. * attribute: visualUpdate true
  2038. */
  2039. public void setVisible(boolean aFlag) {
  2040. if(aFlag != isVisible()) {
  2041. super.setVisible(aFlag);
  2042. Container parent = getParent();
  2043. if(parent != null) {
  2044. Rectangle r = getBounds();
  2045. parent.repaint(r.x,r.y,r.width,r.height);
  2046. }
  2047. // Some (all should) LayoutManagers do not consider components
  2048. // that are not visible. As such we need to revalidate when the
  2049. // visible bit changes.
  2050. revalidate();
  2051. }
  2052. }
  2053. /**
  2054. * Sets whether or not this component is enabled.
  2055. * A component that is enabled may respond to user input,
  2056. * while a component that is not enabled cannot respond to
  2057. * user input. Some components may alter their visual
  2058. * representation when they are disabled in order to
  2059. * provide feedback to the user that they cannot take input.
  2060. * <p>Note: Disabling a component does not disable it's children.
  2061. *
  2062. * <p>Note: Disabling a lightweight component does not prevent it from
  2063. * receiving MouseEvents.
  2064. *
  2065. * @param enabled true if this component should be enabled, false otherwise
  2066. * @see java.awt.Component#isEnabled
  2067. * @see java.awt.Component#isLightweight
  2068. *
  2069. * @beaninfo
  2070. * preferred: true
  2071. * bound: true
  2072. * attribute: visualUpdate true
  2073. * description: The enabled state of the component.
  2074. */
  2075. public void setEnabled(boolean enabled) {
  2076. boolean oldEnabled = isEnabled();
  2077. super.setEnabled(enabled);
  2078. firePropertyChange("enabled", oldEnabled, enabled);
  2079. if (enabled != oldEnabled) {
  2080. repaint();
  2081. }
  2082. }
  2083. /**
  2084. * Sets the foreground color of this component.
  2085. *
  2086. * @param fg the desired foreground <code>Color</code>
  2087. * @see java.awt.Component#getForeground
  2088. *
  2089. * @beaninfo
  2090. * preferred: true
  2091. * bound: true
  2092. * attribute: visualUpdate true
  2093. * description: The foreground color of the component.
  2094. */
  2095. public void setForeground(Color fg) {
  2096. Color oldFg = getForeground();
  2097. super.setForeground(fg);
  2098. if ((oldFg != null) ? !oldFg.equals(fg) : ((fg != null) && !fg.equals(oldFg))) {
  2099. // foreground already bound in AWT1.2
  2100. repaint();
  2101. }
  2102. }
  2103. /**
  2104. * Sets the background color of this component.
  2105. *
  2106. * @param bg the desired background <code>Color</code>
  2107. * @see java.awt.Component#getBackground
  2108. *
  2109. * @beaninfo
  2110. * preferred: true
  2111. * bound: true
  2112. * attribute: visualUpdate true
  2113. * description: The background color of the component.
  2114. */
  2115. public void setBackground(Color bg) {
  2116. Color oldBg = getBackground();
  2117. super.setBackground(bg);
  2118. if ((oldBg != null) ? !oldBg.equals(bg) : ((bg != null) && !bg.equals(oldBg))) {
  2119. // background already bound in AWT1.2
  2120. repaint();
  2121. }
  2122. }
  2123. /**
  2124. * Sets the font for this component.
  2125. *
  2126. * @param font the desired <code>Font</code> for this component
  2127. * @see java.awt.Component#getFont
  2128. *
  2129. * @beaninfo
  2130. * preferred: true
  2131. * bound: true
  2132. * attribute: visualUpdate true
  2133. * description: The font for the component.
  2134. */
  2135. public void setFont(Font font) {
  2136. Font oldFont = getFont();
  2137. super.setFont(font);
  2138. // font already bound in AWT1.2
  2139. if (font != oldFont) {
  2140. revalidate();
  2141. repaint();
  2142. }
  2143. }
  2144. /**
  2145. * Returns the default locale used to initialize each JComponent's
  2146. * locale property upon creation.
  2147. *
  2148. * The default locale has "AppContext" scope so that applets (and
  2149. * potentially multiple lightweight applications running in a single VM)
  2150. * can have their own setting. An applet can safely alter its default
  2151. * locale because it will have no affect on other applets (or the browser).
  2152. *
  2153. * @return the default <code>Locale</code>.
  2154. * @see #setDefaultLocale
  2155. * @see java.awt.Component#getLocale
  2156. * @see #setLocale
  2157. * @since 1.4
  2158. */
  2159. static public Locale getDefaultLocale() {
  2160. Locale l = (Locale) SwingUtilities.appContextGet(defaultLocale);
  2161. if( l == null ) {
  2162. //REMIND(bcb) choosing the default value is more complicated
  2163. //than this.
  2164. l = Locale.getDefault();
  2165. JComponent.setDefaultLocale( l );
  2166. }
  2167. return l;
  2168. }
  2169. /**
  2170. * Sets the default locale used to initialize each JComponent's locale
  2171. * property upon creation. The initial value is the VM's default locale.
  2172. *
  2173. * The default locale has "AppContext" scope so that applets (and
  2174. * potentially multiple lightweight applications running in a single VM)
  2175. * can have their own setting. An applet can safely alter its default
  2176. * locale because it will have no affect on other applets (or the browser).
  2177. *
  2178. * @param l the desired default <code>Locale</code> for new components.
  2179. * @see #getDefaultLocale
  2180. * @see java.awt.Component#getLocale
  2181. * @see #setLocale
  2182. * @since 1.4
  2183. */
  2184. static public void setDefaultLocale( Locale l ) {
  2185. SwingUtilities.appContextPut(defaultLocale, l);
  2186. }
  2187. /**
  2188. * Processes any key events that the component itself
  2189. * recognizes. This is called after the focus
  2190. * manager and any interested listeners have been
  2191. * given a chance to steal away the event. This
  2192. * method is called only if the event has not
  2193. * yet been consumed. This method is called prior
  2194. * to the keyboard UI logic.
  2195. * <p>
  2196. * This method is implemented to do nothing. Subclasses would
  2197. * normally override this method if they process some
  2198. * key events themselves. If the event is processed,
  2199. * it should be consumed.
  2200. */
  2201. protected void processComponentKeyEvent(KeyEvent e) {
  2202. }
  2203. /** Overrides <code>processKeyEvent</code> to process events. **/
  2204. protected void processKeyEvent(KeyEvent e) {
  2205. boolean result;
  2206. boolean shouldProcessKey;
  2207. // This gives the key event listeners a crack at the event
  2208. super.processKeyEvent(e);
  2209. // give the component itself a crack at the event
  2210. if (! e.isConsumed()) {
  2211. processComponentKeyEvent(e);
  2212. }
  2213. shouldProcessKey = KeyboardState.shouldProcess(e);
  2214. if(e.isConsumed()) {
  2215. return;
  2216. }
  2217. if (shouldProcessKey && processKeyBindings(e, e.getID() ==
  2218. KeyEvent.KEY_PRESSED)) {
  2219. e.consume();
  2220. }
  2221. }
  2222. /**
  2223. * Invoked to process the key bindings for <code>ks</code> as the result
  2224. * of the <code>KeyEvent</code> <code>e</code>. This obtains
  2225. * the appropriate <code>InputMap</code>,
  2226. * gets the binding, gets the action from the <code>ActionMap</code>,
  2227. * and then (if the action is found and the component
  2228. * is enabled) invokes <code>notifyAction</code> to notify the action.
  2229. *
  2230. * @param ks the <code>KeyStroke</code> queried
  2231. * @param e the <code>KeyEvent</code>
  2232. * @param condition one of the following values:
  2233. * <ul>
  2234. * <li>JComponent.WHEN_FOCUSED
  2235. * <li>JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  2236. * <li>JComponent.WHEN_IN_FOCUSED_WINDOW
  2237. * </ul>
  2238. * @param pressed true if the key is pressed
  2239. * @return true if there was a binding to an action, and the action
  2240. * was enabled
  2241. *
  2242. * @since 1.3
  2243. */
  2244. protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
  2245. int condition, boolean pressed) {
  2246. InputMap map = getInputMap(condition, false);
  2247. ActionMap am = getActionMap(false);
  2248. if(map != null && am != null && isEnabled()) {
  2249. Object binding = map.get(ks);
  2250. Action action = (binding == null) ? null : am.get(binding);
  2251. if (action != null) {
  2252. return SwingUtilities.notifyAction(action, ks, e, this,
  2253. e.getModifiers());
  2254. }
  2255. }
  2256. return false;
  2257. }
  2258. /**
  2259. * This is invoked as the result of a <code>KeyEvent</code>
  2260. * that was not consumed by the <code>FocusManager</code>,
  2261. * <code>KeyListeners</code>, or the component. It will first try
  2262. * <code>WHEN_FOCUSED</code> bindings,
  2263. * then <code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT</code> bindings,
  2264. * and finally <code>WHEN_IN_FOCUSED_WINDOW</code> bindings.
  2265. *
  2266. * @param e the unconsumed <code>KeyEvent</code>
  2267. * @param pressed true if the key is pressed
  2268. * @return true if there is a key binding for <code>e</code>
  2269. */
  2270. boolean processKeyBindings(KeyEvent e, boolean pressed) {
  2271. if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) {
  2272. return false;
  2273. }
  2274. // Get the KeyStroke
  2275. KeyStroke ks;
  2276. if (e.getID() == KeyEvent.KEY_TYPED) {
  2277. ks = KeyStroke.getKeyStroke(e.getKeyChar());
  2278. }
  2279. else {
  2280. ks = KeyStroke.getKeyStroke(e.getKeyCode(),e.getModifiers(),
  2281. (pressed ? false:true));
  2282. }
  2283. /* Do we have a key binding for e? */
  2284. if(processKeyBinding(ks, e, WHEN_FOCUSED, pressed))
  2285. return true;
  2286. /* We have no key binding. Let's try the path from our parent to the
  2287. * window excluded. We store the path components so we can avoid
  2288. * asking the same component twice.
  2289. */
  2290. Container parent = this;
  2291. while (parent != null && !(parent instanceof Window) &&
  2292. !(parent instanceof Applet)) {
  2293. if(parent instanceof JComponent) {
  2294. if(((JComponent)parent).processKeyBinding(ks, e,
  2295. WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, pressed))
  2296. return true;
  2297. }
  2298. // This is done so that the children of a JInternalFrame are
  2299. // given precedence for WHEN_IN_FOCUSED_WINDOW bindings before
  2300. // other components WHEN_IN_FOCUSED_WINDOW bindings. This also gives
  2301. // more precedence to the WHEN_IN_FOCUSED_WINDOW bindings of the
  2302. // JInternalFrame's children vs the
  2303. // WHEN_ANCESTOR_OF_FOCUSED_COMPONENT bindings of the parents.
  2304. // maybe generalize from JInternalFrame (like isFocusCycleRoot).
  2305. if ((parent instanceof JInternalFrame) &&
  2306. JComponent.processKeyBindingsForAllComponents(e,parent,pressed)){
  2307. return true;
  2308. }
  2309. parent = parent.getParent();
  2310. }
  2311. /* No components between the focused component and the window is
  2312. * actually interested by the key event. Let's try the other
  2313. * JComponent in this window.
  2314. */
  2315. if(parent != null) {
  2316. return JComponent.processKeyBindingsForAllComponents(e,parent,pressed);
  2317. }
  2318. return false;
  2319. }
  2320. static boolean processKeyBindingsForAllComponents(KeyEvent e,
  2321. Container container, boolean pressed) {
  2322. while (true) {
  2323. if (KeyboardManager.getCurrentManager().fireKeyboardAction(
  2324. e, pressed, container)) {
  2325. return true;
  2326. }
  2327. if (container instanceof Popup.HeavyWeightWindow) {
  2328. container = ((Window)container).getOwner();
  2329. }
  2330. else {
  2331. return false;
  2332. }
  2333. }
  2334. }
  2335. /**
  2336. * Registers the text to display in a tool tip.
  2337. * The text displays when the cursor lingers over the component.
  2338. * <p>
  2339. * See <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tooltip.html">How to Use Tool Tips</a>
  2340. * in <em>The Java Tutorial</em>
  2341. * for further documentation.
  2342. *
  2343. * @param text the string to display; if the text is <code>null</code>,
  2344. * the tool tip is turned off for this component
  2345. * @see #TOOL_TIP_TEXT_KEY
  2346. * @beaninfo
  2347. * preferred: true
  2348. * description: The text to display in a tool tip.
  2349. */
  2350. public void setToolTipText(String text) {
  2351. String oldText = getToolTipText();
  2352. putClientProperty(TOOL_TIP_TEXT_KEY, text);
  2353. ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
  2354. if (text != null) {
  2355. if (oldText == null) {
  2356. toolTipManager.registerComponent(this);
  2357. }
  2358. } else {
  2359. toolTipManager.unregisterComponent(this);
  2360. }
  2361. }
  2362. /**
  2363. * Returns the tooltip string that has been set with
  2364. * <code>setToolTipText</code>.
  2365. *
  2366. * @return the text of the tool tip
  2367. * @see #TOOL_TIP_TEXT_KEY
  2368. */
  2369. public String getToolTipText() {
  2370. return (String)getClientProperty(TOOL_TIP_TEXT_KEY);
  2371. }
  2372. /**
  2373. * Returns the string to be used as the tooltip for <i>event</i>.
  2374. * By default this returns any string set using
  2375. * <code>setToolTipText</code>. If a component provides
  2376. * more extensive API to support differing tooltips at different locations,
  2377. * this method should be overridden.
  2378. */
  2379. public String getToolTipText(MouseEvent event) {
  2380. return getToolTipText();
  2381. }
  2382. /**
  2383. * Returns the tooltip location in this component's coordinate system.
  2384. * If <code>null</code> is returned, Swing will choose a location.
  2385. * The default implementation returns <code>null</code>.
  2386. *
  2387. * @param event the <code>MouseEvent</code> that caused the
  2388. * <code>ToolTipManager</code> to show the tooltip
  2389. * @return always returns <code>null</code>
  2390. */
  2391. public Point getToolTipLocation(MouseEvent event) {
  2392. return null;
  2393. }
  2394. /**
  2395. * Returns the instance of <code>JToolTip</code> that should be used
  2396. * to display the tooltip.
  2397. * Components typically would not override this method,
  2398. * but it can be used to
  2399. * cause different tooltips to be displayed differently.
  2400. *
  2401. * @return the <code>JToolTip</code> used to display this toolTip
  2402. */
  2403. public JToolTip createToolTip() {
  2404. JToolTip tip = new JToolTip();
  2405. tip.setComponent(this);
  2406. return tip;
  2407. }
  2408. /**
  2409. * Forwards the <code>scrollRectToVisible()</code> message to the
  2410. * <code>JComponent</code>'s parent. Components that can service
  2411. * the request, such as <code>JViewport</code>,
  2412. * override this method and perform the scrolling.
  2413. *
  2414. * @param aRect the visible <code>Rectangle</code>
  2415. * @see JViewport
  2416. */
  2417. public void scrollRectToVisible(Rectangle aRect) {
  2418. Container parent;
  2419. int dx = getX(), dy = getY();
  2420. for (parent = getParent();
  2421. !(parent == null) &&
  2422. !(parent instanceof JComponent) &&
  2423. !(parent instanceof CellRendererPane);
  2424. parent = parent.getParent()) {
  2425. Rectangle bounds = parent.getBounds();
  2426. dx += bounds.x;
  2427. dy += bounds.y;
  2428. }
  2429. if (!(parent == null) && !(parent instanceof CellRendererPane)) {
  2430. aRect.x += dx;
  2431. aRect.y += dy;
  2432. ((JComponent)parent).scrollRectToVisible(aRect);
  2433. aRect.x -= dx;
  2434. aRect.y -= dy;
  2435. }
  2436. }
  2437. /**
  2438. * Sets the <code>autoscrolls</code> property.
  2439. * If <code>true</code> mouse dragged events will be
  2440. * synthetically generated when the mouse is dragged
  2441. * outside of the component's bounds and mouse motion
  2442. * has paused (while the button continues to be held
  2443. * down). The synthetic events make it appear that the
  2444. * drag gesture has resumed in the direction established when
  2445. * the component's boundary was crossed. Components that
  2446. * support autoscrolling must handle <code>mouseDragged</code>
  2447. * events by calling <code>scrollRectToVisible</code> with a
  2448. * rectangle that contains the mouse event's location. All of
  2449. * the Swing components that support item selection and are
  2450. * typically displayed in a <code>JScrollPane</code>
  2451. * (<code>JTable</code>, <code>JList</code>, <code>JTree</code>,
  2452. * <code>JTextArea</code>, and <code>JEditorPane</code>)
  2453. * already handle mouse dragged events in this way. To enable
  2454. * autoscrolling in any other component, add a mouse motion
  2455. * listener that calls <code>scrollRectToVisible</code>.
  2456. * For example, given a <code>JPanel</code>, <code>myPanel</code>:
  2457. * <pre>
  2458. * MouseMotionListener doScrollRectToVisible = new MouseMotionAdapter() {
  2459. * public void mouseDragged(MouseEvent e) {
  2460. * Rectangle r = new Rectangle(e.getX(), e.getY(), 1, 1);
  2461. * ((JPanel)e.getSource()).scrollRectToVisible(r);
  2462. * }
  2463. * };
  2464. * myPanel.addMouseMotionListener(doScrollRectToVisible);
  2465. * </pre>
  2466. * The default value of the <code>autoScrolls</code>
  2467. * property is <code>false</code>.
  2468. *
  2469. * @param autoscrolls if true, synthetic mouse dragged events
  2470. * are generated when the mouse is dragged outside of a component's
  2471. * bounds and the mouse button continues to be held down; otherwise
  2472. * false
  2473. * @see #getAutoscrolls
  2474. * @see JViewport
  2475. * @see JScrollPane
  2476. *
  2477. * @beaninfo
  2478. * expert: true
  2479. * description: Determines if this component automatically scrolls its contents when dragged.
  2480. */
  2481. public void setAutoscrolls(boolean autoscrolls) {
  2482. if (autoscrolls) {
  2483. if (autoscroller == null) {
  2484. autoscroller = new Autoscroller(this);
  2485. }
  2486. } else {
  2487. if (autoscroller != null) {
  2488. autoscroller.dispose();
  2489. autoscroller = null;
  2490. }
  2491. }
  2492. }
  2493. /**
  2494. * Gets the <code>autoscrolls</code> property.
  2495. *
  2496. * @return the value of the <code>autoscrolls</code> property
  2497. * @see JViewport
  2498. * @see #setAutoscrolls
  2499. */
  2500. public boolean getAutoscrolls() {
  2501. return autoscroller != null;
  2502. }
  2503. /**
  2504. * Sets the <code>transferHandler</code> property,
  2505. * which is <code>null</code> if the component does
  2506. * not support data transfer operations.
  2507. * <p>
  2508. * If <code>newHandler</code> is not null, and the system property
  2509. * <code>suppressSwingDropSupport</code> is not true, this will
  2510. * install a <code>DropTarget</code> on the <code>JComponent</code>.
  2511. * The default for the system property is false, so that a
  2512. * <code>DropTarget</code> will be added.
  2513. *
  2514. * @param newHandler mechanism for transfer of data to
  2515. * and from the component
  2516. *
  2517. * @see TransferHandler
  2518. * @see #getTransferHandler
  2519. * @since 1.4
  2520. * @beaninfo
  2521. * bound: true
  2522. * hidden: true
  2523. * description: Mechanism for transfer of data to and from the component
  2524. */
  2525. public void setTransferHandler(TransferHandler newHandler) {
  2526. TransferHandler oldHandler = transfer;
  2527. transfer = newHandler;
  2528. if (! getSuppressDropTarget()) {
  2529. DropTarget dropHandler = getDropTarget();
  2530. if ((dropHandler == null) || (dropHandler instanceof UIResource)) {
  2531. if (newHandler == null) {
  2532. setDropTarget(null);
  2533. } else if (!GraphicsEnvironment.isHeadless()) {
  2534. setDropTarget(new TransferHandler.SwingDropTarget(this));
  2535. }
  2536. }
  2537. }
  2538. firePropertyChange("transferHandler", oldHandler, transfer);
  2539. }
  2540. /**
  2541. * Gets the <code>transferHandler</code> property.
  2542. *
  2543. * @return the value of the <code>transferHandler</code> property
  2544. *
  2545. * @see TransferHandler
  2546. * @see #setTransferHandler
  2547. * @since 1.4
  2548. */
  2549. public TransferHandler getTransferHandler() {
  2550. return transfer;
  2551. }
  2552. /**
  2553. * Processes mouse motion events, such as MouseEvent.MOUSE_DRAGGED.
  2554. *
  2555. * @param e the <code>MouseEvent</code>
  2556. * @see MouseEvent
  2557. */
  2558. protected void processMouseMotionEvent(MouseEvent e) {
  2559. boolean dispatch = true;
  2560. if (autoscroller != null) {
  2561. if (e.getID() == MouseEvent.MOUSE_DRAGGED) {
  2562. // We don't want to do the drags when the mouse moves if we're
  2563. // autoscrolling. It makes it feel spastic.
  2564. dispatch = !autoscroller.timer.isRunning();
  2565. autoscroller.mouseDragged(e);
  2566. }
  2567. }
  2568. if (dispatch) {
  2569. super.processMouseMotionEvent(e);
  2570. }
  2571. }
  2572. // Inner classes can't get at this method from a super class
  2573. void superProcessMouseMotionEvent(MouseEvent e) {
  2574. super.processMouseMotionEvent(e);
  2575. }
  2576. /**
  2577. * This is invoked by the <code>RepaintManager</code> if
  2578. * <code>createImage</code> is called on the component.
  2579. *
  2580. * @param newValue true if the double buffer image was created from this component
  2581. */
  2582. void setCreatedDoubleBuffer(boolean newValue) {
  2583. setFlag(CREATED_DOUBLE_BUFFER, newValue);
  2584. }
  2585. /**
  2586. * Returns true if the <code>RepaintManager</code>
  2587. * created the double buffer image from the component.
  2588. *
  2589. * @return true if this component had a double buffer image, false otherwise
  2590. */
  2591. boolean getCreatedDoubleBuffer() {
  2592. return getFlag(CREATED_DOUBLE_BUFFER);
  2593. }
  2594. /**
  2595. * <code>ActionStandin</code> is used as a standin for
  2596. * <code>ActionListeners</code> that are
  2597. * added via <code>registerKeyboardAction</code>.
  2598. */
  2599. final class ActionStandin implements Action {
  2600. private final ActionListener actionListener;
  2601. private final String command;
  2602. // This will be non-null if actionListener is an Action.
  2603. private final Action action;
  2604. ActionStandin(ActionListener actionListener, String command) {
  2605. this.actionListener = actionListener;
  2606. if (actionListener instanceof Action) {
  2607. this.action = (Action)actionListener;
  2608. }
  2609. else {
  2610. this.action = null;
  2611. }
  2612. this.command = command;
  2613. }
  2614. public Object getValue(String key) {
  2615. if (key != null) {
  2616. if (key.equals(Action.ACTION_COMMAND_KEY)) {
  2617. return command;
  2618. }
  2619. if (action != null) {
  2620. return action.getValue(key);
  2621. }
  2622. if (key.equals(NAME)) {
  2623. return "ActionStandin";
  2624. }
  2625. }
  2626. return null;
  2627. }
  2628. public boolean isEnabled() {
  2629. if (actionListener == null) {
  2630. // This keeps the old semantics where
  2631. // registerKeyboardAction(null) would essentialy remove
  2632. // the binding. We don't remove the binding from the
  2633. // InputMap as that would still allow parent InputMaps
  2634. // bindings to be accessed.
  2635. return false;
  2636. }
  2637. if (action == null) {
  2638. return true;
  2639. }
  2640. return action.isEnabled();
  2641. }
  2642. public void actionPerformed(ActionEvent ae) {
  2643. if (actionListener != null) {
  2644. actionListener.actionPerformed(ae);
  2645. }
  2646. }
  2647. // We don't allow any values to be added.
  2648. public void putValue(String key, Object value) {}
  2649. // Does nothing, our enabledness is determiend from our asociated
  2650. // action.
  2651. public void setEnabled(boolean b) { }
  2652. public void addPropertyChangeListener
  2653. (PropertyChangeListener listener) {}
  2654. public void removePropertyChangeListener
  2655. (PropertyChangeListener listener) {}
  2656. }
  2657. // This class is used by the KeyboardState class to provide a single
  2658. // instance that can be stored in the AppContext.
  2659. static final class IntVector {
  2660. int array[] = null;
  2661. int count = 0;
  2662. int capacity = 0;
  2663. int size() {
  2664. return count;
  2665. }
  2666. int elementAt(int index) {
  2667. return array[index];
  2668. }
  2669. void addElement(int value) {
  2670. if (count == capacity) {
  2671. capacity = (capacity + 2) * 2;
  2672. int[] newarray = new int[capacity];
  2673. if (count > 0) {
  2674. System.arraycopy(array, 0, newarray, 0, count);
  2675. }
  2676. array = newarray;
  2677. }
  2678. array[count++] = value;
  2679. }
  2680. void setElementAt(int value, int index) {
  2681. array[index] = value;
  2682. }
  2683. }
  2684. static class KeyboardState implements Serializable {
  2685. private static final Object keyCodesKey =
  2686. JComponent.KeyboardState.class;
  2687. // Get the array of key codes from the AppContext.
  2688. static IntVector getKeyCodeArray() {
  2689. IntVector iv =
  2690. (IntVector)SwingUtilities.appContextGet(keyCodesKey);
  2691. if (iv == null) {
  2692. iv = new IntVector();
  2693. SwingUtilities.appContextPut(keyCodesKey, iv);
  2694. }
  2695. return iv;
  2696. }
  2697. static void registerKeyPressed(int keyCode) {
  2698. IntVector kca = getKeyCodeArray();
  2699. int count = kca.size();
  2700. int i;
  2701. for(i=0;i<count;i++) {
  2702. if(kca.elementAt(i) == -1){
  2703. kca.setElementAt(keyCode, i);
  2704. return;
  2705. }
  2706. }
  2707. kca.addElement(keyCode);
  2708. }
  2709. static void registerKeyReleased(int keyCode) {
  2710. IntVector kca = getKeyCodeArray();
  2711. int count = kca.size();
  2712. int i;
  2713. for(i=0;i<count;i++) {
  2714. if(kca.elementAt(i) == keyCode) {
  2715. kca.setElementAt(-1, i);
  2716. return;
  2717. }
  2718. }
  2719. }
  2720. static boolean keyIsPressed(int keyCode) {
  2721. IntVector kca = getKeyCodeArray();
  2722. int count = kca.size();
  2723. int i;
  2724. for(i=0;i<count;i++) {
  2725. if(kca.elementAt(i) == keyCode) {
  2726. return true;
  2727. }
  2728. }
  2729. return false;
  2730. }
  2731. /**
  2732. * Updates internal state of the KeyboardState and returns true
  2733. * if the event should be processed further.
  2734. */
  2735. static boolean shouldProcess(KeyEvent e) {
  2736. switch (e.getID()) {
  2737. case KeyEvent.KEY_PRESSED:
  2738. if (!keyIsPressed(e.getKeyCode())) {
  2739. registerKeyPressed(e.getKeyCode());
  2740. }
  2741. return true;
  2742. case KeyEvent.KEY_RELEASED:
  2743. if (keyIsPressed(e.getKeyCode())) {
  2744. registerKeyReleased(e.getKeyCode());
  2745. return true;
  2746. }
  2747. return false;
  2748. case KeyEvent.KEY_TYPED:
  2749. return true;
  2750. default:
  2751. // Not a known KeyEvent type, bail.
  2752. return false;
  2753. }
  2754. }
  2755. }
  2756. /*
  2757. * --- Accessibility Support ---
  2758. */
  2759. /**
  2760. * @deprecated As of JDK version 1.1,
  2761. * replaced by <code>java.awt.Component.setEnable(boolean)</code>.
  2762. */
  2763. public void enable() {
  2764. if (isEnabled() != true) {
  2765. super.enable();
  2766. if (accessibleContext != null) {
  2767. accessibleContext.firePropertyChange(
  2768. AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  2769. null, AccessibleState.ENABLED);
  2770. }
  2771. }
  2772. }
  2773. /**
  2774. * @deprecated As of JDK version 1.1,
  2775. * replaced by <code>java.awt.Component.setEnable(boolean)</code>.
  2776. */
  2777. public void disable() {
  2778. if (isEnabled() != false) {
  2779. super.disable();
  2780. if (accessibleContext != null) {
  2781. accessibleContext.firePropertyChange(
  2782. AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  2783. AccessibleState.ENABLED, null);
  2784. }
  2785. }
  2786. }
  2787. /**
  2788. * The <code>AccessibleContext</code> associated with this
  2789. * <code>JComponent</code>.
  2790. */
  2791. protected AccessibleContext accessibleContext = null;
  2792. /**
  2793. * Returns the <code>AccessibleContext</code> associated with this
  2794. * <code>JComponent</code>. The method implemented by this base
  2795. * class returns null. Classes that extend <code>JComponent</code>
  2796. * should implement this method to return the
  2797. * <code>AccessibleContext</code> associated with the subclass.
  2798. *
  2799. * @return the <code>AccessibleContext</code> of this
  2800. * <code>JComponent</code>
  2801. */
  2802. public AccessibleContext getAccessibleContext() {
  2803. return accessibleContext;
  2804. }
  2805. /**
  2806. * Inner class of JComponent used to provide default support for
  2807. * accessibility. This class is not meant to be used directly by
  2808. * application developers, but is instead meant only to be
  2809. * subclassed by component developers.
  2810. * <p>
  2811. * <strong>Warning:</strong>
  2812. * Serialized objects of this class will not be compatible with
  2813. * future Swing releases. The current serialization support is
  2814. * appropriate for short term storage or RMI between applications running
  2815. * the same version of Swing. As of 1.4, support for long term storage
  2816. * of all JavaBeans<sup><font size="-2">TM</font></sup>
  2817. * has been added to the <code>java.beans</code> package.
  2818. * Please see {@link java.beans.XMLEncoder}.
  2819. */
  2820. public abstract class AccessibleJComponent extends AccessibleAWTContainer
  2821. implements AccessibleExtendedComponent
  2822. {
  2823. /**
  2824. * Though the class is abstract, this should be called by
  2825. * all sub-classes.
  2826. */
  2827. protected AccessibleJComponent() {
  2828. super();
  2829. }
  2830. protected ContainerListener accessibleContainerHandler = null;
  2831. protected FocusListener accessibleFocusHandler = null;
  2832. /**
  2833. * Fire PropertyChange listener, if one is registered,
  2834. * when children added/removed.
  2835. */
  2836. protected class AccessibleContainerHandler
  2837. implements ContainerListener {
  2838. public void componentAdded(ContainerEvent e) {
  2839. Component c = e.getChild();
  2840. if (c != null && c instanceof Accessible) {
  2841. AccessibleJComponent.this.firePropertyChange(
  2842. AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
  2843. null, ((Accessible) c).getAccessibleContext());
  2844. }
  2845. }
  2846. public void componentRemoved(ContainerEvent e) {
  2847. Component c = e.getChild();
  2848. if (c != null && c instanceof Accessible) {
  2849. AccessibleJComponent.this.firePropertyChange(
  2850. AccessibleContext.ACCESSIBLE_CHILD_PROPERTY,
  2851. ((Accessible) c).getAccessibleContext(), null);
  2852. }
  2853. }
  2854. }
  2855. /**
  2856. * Fire PropertyChange listener, if one is registered,
  2857. * when focus events happen
  2858. */
  2859. protected class AccessibleFocusHandler implements FocusListener {
  2860. public void focusGained(FocusEvent event) {
  2861. if (accessibleContext != null) {
  2862. accessibleContext.firePropertyChange(
  2863. AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  2864. null, AccessibleState.FOCUSED);
  2865. }
  2866. }
  2867. public void focusLost(FocusEvent event) {
  2868. if (accessibleContext != null) {
  2869. accessibleContext.firePropertyChange(
  2870. AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  2871. AccessibleState.FOCUSED, null);
  2872. }
  2873. }
  2874. } // inner class AccessibleFocusHandler
  2875. /**
  2876. * Adds a PropertyChangeListener to the listener list.
  2877. *
  2878. * @param listener the PropertyChangeListener to be added
  2879. */
  2880. public void addPropertyChangeListener(PropertyChangeListener listener) {
  2881. if (accessibleFocusHandler == null) {
  2882. accessibleFocusHandler = new AccessibleFocusHandler();
  2883. JComponent.this.addFocusListener(accessibleFocusHandler);
  2884. }
  2885. if (accessibleContainerHandler == null) {
  2886. accessibleContainerHandler = new AccessibleContainerHandler();
  2887. JComponent.this.addContainerListener(accessibleContainerHandler);
  2888. }
  2889. super.addPropertyChangeListener(listener);
  2890. }
  2891. /**
  2892. * Removes a PropertyChangeListener from the listener list.
  2893. * This removes a PropertyChangeListener that was registered
  2894. * for all properties.
  2895. *
  2896. * @param listener the PropertyChangeListener to be removed
  2897. */
  2898. public void removePropertyChangeListener(PropertyChangeListener listener) {
  2899. if (accessibleFocusHandler != null) {
  2900. JComponent.this.removeFocusListener(accessibleFocusHandler);
  2901. accessibleFocusHandler = null;
  2902. }
  2903. super.removePropertyChangeListener(listener);
  2904. }
  2905. /**
  2906. * Recursively search through the border hierarchy (if it exists)
  2907. * for a TitledBorder with a non-null title. This does a depth
  2908. * first search on first the inside borders then the outside borders.
  2909. * The assumption is that titles make really pretty inside borders
  2910. * but not very pretty outside borders in compound border situations.
  2911. * It's rather arbitrary, but hopefully decent UI programmers will
  2912. * not create multiple titled borders for the same component.
  2913. */
  2914. protected String getBorderTitle(Border b) {
  2915. String s;
  2916. if (b instanceof TitledBorder) {
  2917. return ((TitledBorder) b).getTitle();
  2918. } else if (b instanceof CompoundBorder) {
  2919. s = getBorderTitle(((CompoundBorder) b).getInsideBorder());
  2920. if (s == null) {
  2921. s = getBorderTitle(((CompoundBorder) b).getOutsideBorder());
  2922. }
  2923. return s;
  2924. } else {
  2925. return null;
  2926. }
  2927. }
  2928. // AccessibleContext methods
  2929. //
  2930. /**
  2931. * Gets the accessible name of this object. This should almost never
  2932. * return java.awt.Component.getName(), as that generally isn't
  2933. * a localized name, and doesn't have meaning for the user. If the
  2934. * object is fundamentally a text object (such as a menu item), the
  2935. * accessible name should be the text of the object (for example,
  2936. * "save").
  2937. * If the object has a tooltip, the tooltip text may also be an
  2938. * appropriate String to return.
  2939. *
  2940. * @return the localized name of the object -- can be null if this
  2941. * object does not have a name
  2942. * @see AccessibleContext#setAccessibleName
  2943. */
  2944. public String getAccessibleName() {
  2945. String name = accessibleName;
  2946. // fallback to the titled border if it exists
  2947. //
  2948. if (name == null) {
  2949. name = getBorderTitle(getBorder());
  2950. }
  2951. // fallback to the label labeling us if it exists
  2952. //
  2953. if (name == null) {
  2954. Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
  2955. if (o instanceof Accessible) {
  2956. AccessibleContext ac = ((Accessible) o).getAccessibleContext();
  2957. if (ac != null) {
  2958. name = ac.getAccessibleName();
  2959. }
  2960. }
  2961. }
  2962. return name;
  2963. }
  2964. /**
  2965. * Gets the accessible description of this object. This should be
  2966. * a concise, localized description of what this object is - what
  2967. * is its meaning to the user. If the object has a tooltip, the
  2968. * tooltip text may be an appropriate string to return, assuming
  2969. * it contains a concise description of the object (instead of just
  2970. * the name of the object - for example a "Save" icon on a toolbar that
  2971. * had "save" as the tooltip text shouldn't return the tooltip
  2972. * text as the description, but something like "Saves the current
  2973. * text document" instead).
  2974. *
  2975. * @return the localized description of the object -- can be null if
  2976. * this object does not have a description
  2977. * @see AccessibleContext#setAccessibleDescription
  2978. */
  2979. public String getAccessibleDescription() {
  2980. String description = accessibleDescription;
  2981. // fallback to the tool tip text if it exists
  2982. //
  2983. if (description == null) {
  2984. try {
  2985. description = getToolTipText();
  2986. } catch (Exception e) {
  2987. // Just in case the subclass overrode the
  2988. // getToolTipText method and actually
  2989. // requires a MouseEvent.
  2990. // [[[FIXME: WDW - we probably should require this
  2991. // method to take a MouseEvent and just pass it on
  2992. // to getToolTipText. The swing-feedback traffic
  2993. // leads me to believe getToolTipText might change,
  2994. // though, so I was hesitant to make this change at
  2995. // this time.]]]
  2996. }
  2997. }
  2998. // fallback to the label labeling us if it exists
  2999. //
  3000. if (description == null) {
  3001. Object o = getClientProperty(JLabel.LABELED_BY_PROPERTY);
  3002. if (o instanceof Accessible) {
  3003. AccessibleContext ac = ((Accessible) o).getAccessibleContext();
  3004. if (ac != null) {
  3005. description = ac.getAccessibleDescription();
  3006. }
  3007. }
  3008. }
  3009. return description;
  3010. }
  3011. /**
  3012. * Gets the role of this object.
  3013. *
  3014. * @return an instance of AccessibleRole describing the role of the
  3015. * object
  3016. * @see AccessibleRole
  3017. */
  3018. public AccessibleRole getAccessibleRole() {
  3019. return AccessibleRole.SWING_COMPONENT;
  3020. }
  3021. /**
  3022. * Gets the state of this object.
  3023. *
  3024. * @return an instance of AccessibleStateSet containing the current
  3025. * state set of the object
  3026. * @see AccessibleState
  3027. */
  3028. public AccessibleStateSet getAccessibleStateSet() {
  3029. AccessibleStateSet states = super.getAccessibleStateSet();
  3030. if (JComponent.this.isOpaque()) {
  3031. states.add(AccessibleState.OPAQUE);
  3032. }
  3033. return states;
  3034. }
  3035. /**
  3036. * Returns the number of accessible children in the object. If all
  3037. * of the children of this object implement Accessible, than this
  3038. * method should return the number of children of this object.
  3039. *
  3040. * @return the number of accessible children in the object.
  3041. */
  3042. public int getAccessibleChildrenCount() {
  3043. return super.getAccessibleChildrenCount();
  3044. }
  3045. /**
  3046. * Returns the nth Accessible child of the object.
  3047. *
  3048. * @param i zero-based index of child
  3049. * @return the nth Accessible child of the object
  3050. */
  3051. public Accessible getAccessibleChild(int i) {
  3052. return super.getAccessibleChild(i);
  3053. }
  3054. // ----- AccessibleExtendedComponent
  3055. /**
  3056. * Returns the AccessibleExtendedComponent
  3057. *
  3058. * @return the AccessibleExtendedComponent
  3059. */
  3060. AccessibleExtendedComponent getAccessibleExtendedComponent() {
  3061. return this;
  3062. }
  3063. /**
  3064. * Returns the tool tip text
  3065. *
  3066. * @return the tool tip text, if supported, of the object;
  3067. * otherwise, null
  3068. */
  3069. public String getToolTipText() {
  3070. return null;
  3071. }
  3072. /**
  3073. * Returns the titled border text
  3074. *
  3075. * @return the titled border text, if supported, of the object;
  3076. * otherwise, null
  3077. */
  3078. public String getTitledBorderText() {
  3079. Border border = JComponent.this.getBorder();
  3080. if (border instanceof TitledBorder) {
  3081. return ((TitledBorder)border).getTitle();
  3082. } else {
  3083. return null;
  3084. }
  3085. }
  3086. /**
  3087. * Returns key bindings associated with this object
  3088. *
  3089. * @return the key bindings, if supported, of the object;
  3090. * otherwise, null
  3091. * @see AccessibleKeyBinding
  3092. */
  3093. public AccessibleKeyBinding getAccessibleKeyBinding() {
  3094. return null;
  3095. }
  3096. } // inner class AccessibleJComponent
  3097. /**
  3098. * Returns a <code>HashTable</code> containing all of the
  3099. * key/value "client properties" for this component. If the
  3100. * <code>clientProperties</code> hash table doesn't previously
  3101. * exist, an empty one (of size 2) will be created.
  3102. *
  3103. * @return a small <code>Hashtable</code>
  3104. * @see #putClientProperty
  3105. * @see #getClientProperty
  3106. */
  3107. private Dictionary getClientProperties() {
  3108. if (clientProperties == null) {
  3109. clientProperties = new Hashtable(2);
  3110. }
  3111. return clientProperties;
  3112. }
  3113. private static final String htmlKey = "html";
  3114. private Object htmlView;
  3115. /**
  3116. * Returns the value of the property with the specified key. Only
  3117. * properties added with <code>putClientProperty</code> will return
  3118. * a non-<code>null</code> value.
  3119. *
  3120. * @param key the being queried
  3121. * @return the value of this property or <code>null</code>
  3122. * @see #putClientProperty
  3123. */
  3124. public final Object getClientProperty(Object key) {
  3125. if(clientProperties == null) {
  3126. return null;
  3127. } else if (key==htmlKey) {
  3128. // System.out.println("Retrieving HTML Key");
  3129. return htmlView;
  3130. } else {
  3131. return getClientProperties().get(key);
  3132. }
  3133. }
  3134. /**
  3135. * Adds an arbitrary key/value "client property" to this component.
  3136. * <p>
  3137. * The <code>get/putClientProperty</code> methods provide access to
  3138. * a small per-instance hashtable. Callers can use get/putClientProperty
  3139. * to annotate components that were created by another module.
  3140. * For example, a
  3141. * layout manager might store per child constraints this way. For example:
  3142. * <pre>
  3143. * componentA.putClientProperty("to the left of", componentB);
  3144. * </pre>
  3145. * If value is <code>null</code> this method will remove the property.
  3146. * Changes to client properties are reported with
  3147. * <code>PropertyChange</code> events.
  3148. * The name of the property (for the sake of PropertyChange
  3149. * events) is <code>key.toString()</code>.
  3150. * <p>
  3151. * The <code>clientProperty</code> dictionary is not intended to
  3152. * support large
  3153. * scale extensions to JComponent nor should be it considered an
  3154. * alternative to subclassing when designing a new component.
  3155. *
  3156. * @param key the new client property key
  3157. * @param value the new client property value; if <code>null</code>
  3158. * this method will remove the property
  3159. * @see #getClientProperty
  3160. * @see #addPropertyChangeListener
  3161. */
  3162. public final void putClientProperty(Object key, Object value) {
  3163. if (value == null && clientProperties == null) {
  3164. // Both the value and Hashtable are null, implying we don't
  3165. // have to do anything.
  3166. return;
  3167. }
  3168. Object oldValue = getClientProperties().get(key);
  3169. if (value != null) {
  3170. if (key==htmlKey) {
  3171. htmlView=value;
  3172. } else {
  3173. getClientProperties().put(key, value);
  3174. firePropertyChange(key.toString(), oldValue, value);
  3175. }
  3176. } else if (oldValue != null) {
  3177. getClientProperties().remove(key);
  3178. firePropertyChange(key.toString(), oldValue, value);
  3179. }
  3180. else if (key == htmlKey) {
  3181. htmlView = null;
  3182. }
  3183. }
  3184. /* --- Transitional java.awt.Component Support ---
  3185. * The methods and fields in this section will migrate to
  3186. * java.awt.Component in the next JDK release.
  3187. */
  3188. private SwingPropertyChangeSupport changeSupport;
  3189. /**
  3190. * Returns true if this component is lightweight, that is, if it doesn't
  3191. * have a native window system peer.
  3192. *
  3193. * @return true if this component is lightweight
  3194. */
  3195. public static boolean isLightweightComponent(Component c) {
  3196. return c.getPeer() instanceof LightweightPeer;
  3197. }
  3198. /**
  3199. * Moves and resizes this component.
  3200. *
  3201. * @param x the new horizontal location
  3202. * @param y the new vertical location
  3203. * @param w the new width
  3204. * @param h the new height
  3205. * @see java.awt.Component#setBounds
  3206. */
  3207. public void reshape(int x, int y, int w, int h) {
  3208. if (_bounds.x == x && _bounds.y == y && _bounds.width == w &&
  3209. _bounds.height == h) {
  3210. // No change.
  3211. return;
  3212. }
  3213. if(isShowing()) {
  3214. /* If there is an intersection between the new bounds and the old
  3215. * one, refresh only the visible rects
  3216. */
  3217. if(!((_bounds.x + _bounds.width <= x) ||
  3218. (_bounds.y + _bounds.height <= y) ||
  3219. (_bounds.x >= (x + w)) ||
  3220. (_bounds.y >= (y + h)))) {
  3221. Rectangle[] rev = SwingUtilities.computeDifference(getBounds(),
  3222. new Rectangle(x,y,w,h));
  3223. int i,c;
  3224. Container parent = getParent();
  3225. for(i=0,c=rev.length ; i < c ; i++) {
  3226. parent.repaint(rev[i].x,rev[i].y,rev[i].width,rev[i].height);
  3227. // System.out.println("Repaint " + rev[i]);
  3228. }
  3229. } else {
  3230. Component parent = getParent();
  3231. if (parent != null) {
  3232. parent.repaint(_bounds.x, _bounds.y, _bounds.width,
  3233. _bounds.height);
  3234. }
  3235. }
  3236. }
  3237. _bounds.setBounds(x, y, w, h);
  3238. super.reshape(x, y, w, h);
  3239. }
  3240. /**
  3241. * Stores the bounds of this component into "return value"
  3242. * <code>rv</code> and returns <code>rv</code>.
  3243. * If <code>rv</code> is <code>null</code> a new <code>Rectangle</code>
  3244. * is allocated. This version of <code>getBounds</code> is useful
  3245. * if the caller wants to avoid allocating a new <code>Rectangle</code>
  3246. * object on the heap.
  3247. *
  3248. * @param rv the return value, modified to the component's bounds
  3249. * @return <code>rv</code> if <code>rv</code> is <code>null</code>
  3250. * return a newly created <code>Rectangle</code> with this
  3251. * component's bounds
  3252. */
  3253. public Rectangle getBounds(Rectangle rv) {
  3254. if (rv == null) {
  3255. return new Rectangle(getX(), getY(), getWidth(), getHeight());
  3256. }
  3257. else {
  3258. rv.setBounds(getX(), getY(), getWidth(), getHeight());
  3259. return rv;
  3260. }
  3261. }
  3262. /**
  3263. * Stores the width/height of this component into "return value"
  3264. * <code>rv</code> and returns <code>rv</code>.
  3265. * If <code>rv</code> is <code>null</code> a new <code>Dimension</code>
  3266. * object is allocated. This version of <code>getSize</code>
  3267. * is useful if the caller wants to avoid allocating a new
  3268. * <code>Dimension</code> object on the heap.
  3269. *
  3270. * @param rv the return value, modified to the component's size
  3271. * @return <code>rv</code>
  3272. */
  3273. public Dimension getSize(Dimension rv) {
  3274. if (rv == null) {
  3275. return new Dimension(getWidth(), getHeight());
  3276. }
  3277. else {
  3278. rv.setSize(getWidth(), getHeight());
  3279. return rv;
  3280. }
  3281. }
  3282. /**
  3283. * Stores the x,y origin of this component into "return value"
  3284. * <code>rv</code> and returns <code>rv</code>.
  3285. * If <code>rv</code> is <code>null</code> a new <code>Point</code>
  3286. * is allocated. This version of <code>getLocation</code> is useful
  3287. * if the caller wants to avoid allocating a new <code>Point</code>
  3288. * object on the heap.
  3289. *
  3290. * @param rv the return value, modified to the component's location
  3291. * @return <code>rv</code>
  3292. */
  3293. public Point getLocation(Point rv) {
  3294. if (rv == null) {
  3295. return new Point(getX(), getY());
  3296. }
  3297. else {
  3298. rv.setLocation(getX(), getY());
  3299. return rv;
  3300. }
  3301. }
  3302. /**
  3303. * Returns the current x coordinate of the component's origin.
  3304. * This method is preferable to writing
  3305. * <code>component.getBounds().x</code>, or
  3306. * <code>component.getLocation().x</code> because it doesn't cause any
  3307. * heap allocations.
  3308. *
  3309. * @return the current x coordinate of the component's origin
  3310. */
  3311. public int getX() { return _bounds.x; }
  3312. /**
  3313. * Returns the current y coordinate of the component's origin.
  3314. * This method is preferable to writing
  3315. * <code>component.getBounds().y</code>, or
  3316. * <code>component.getLocation().y</code> because it doesn't cause any
  3317. * heap allocations.
  3318. *
  3319. * @return the current y coordinate of the component's origin
  3320. */
  3321. public int getY() { return _bounds.y; }
  3322. /**
  3323. * Returns the current width of this component.
  3324. * This method is preferable to writing
  3325. * <code>component.getBounds().width</code>, or
  3326. * <code>component.getSize().width</code> because it doesn't cause any
  3327. * heap allocations.
  3328. *
  3329. * @return the current width of this component
  3330. */
  3331. public int getWidth() { return _bounds.width; }
  3332. /**
  3333. * Returns the current height of this component.
  3334. * This method is preferable to writing
  3335. * <code>component.getBounds().height</code>, or
  3336. * <code>component.getSize().height</code> because it doesn't cause any
  3337. * heap allocations.
  3338. *
  3339. * @return the current height of this component
  3340. */
  3341. public int getHeight() { return _bounds.height; }
  3342. /**
  3343. * Returns true if this component is completely opaque.
  3344. * <p>
  3345. * An opaque component paints every pixel within its
  3346. * rectangular bounds. A non-opaque component paints only a subset of
  3347. * its pixels or none at all, allowing the pixels underneath it to
  3348. * "show through". Therefore, a component that does not fully paint
  3349. * its pixels provides a degree of transparency.
  3350. * <p>
  3351. * Subclasses that guarantee to always completely paint their contents
  3352. * should override this method and return true.
  3353. *
  3354. * @return true if this component is completely opaque
  3355. * @see #setOpaque
  3356. */
  3357. public boolean isOpaque() {
  3358. return getFlag(IS_OPAQUE);
  3359. }
  3360. /**
  3361. * If true the component paints every pixel within its bounds.
  3362. * Otherwise, the component may not paint some or all of its
  3363. * pixels, allowing the underlying pixels to show through.
  3364. * <p>
  3365. * The default value of this property is false for <code>JComponent</code>.
  3366. * However, the default value for this property on most standard
  3367. * <code>JComponent</code> subclasses (such as <code>JButton</code> and
  3368. * <code>JTree</code>) is look-and-feel dependent.
  3369. *
  3370. * @param isOpaque true if this component should be opaque
  3371. * @see #isOpaque
  3372. * @beaninfo
  3373. * bound: true
  3374. * expert: true
  3375. * description: The component's opacity
  3376. */
  3377. public void setOpaque(boolean isOpaque) {
  3378. boolean oldValue = getFlag(IS_OPAQUE);
  3379. setFlag(IS_OPAQUE, isOpaque);
  3380. firePropertyChange("opaque", oldValue, isOpaque);
  3381. }
  3382. /**
  3383. * If the specified rectangle is completely obscured by any of this
  3384. * component's opaque children then returns true. Only direct children
  3385. * are considered, more distant descendants are ignored. A
  3386. * <code>JComponent</code> is opaque if
  3387. * <code>JComponent.isOpaque()</code> returns true, other lightweight
  3388. * components are always considered transparent, and heavyweight components
  3389. * are always considered opaque.
  3390. *
  3391. * @param x x value of specified rectangle
  3392. * @param y y value of specified rectangle
  3393. * @param width width of specified rectangle
  3394. * @param height height of specified rectangle
  3395. * @return true if the specified rectangle is obscured by an opaque child
  3396. */
  3397. boolean rectangleIsObscured(int x,int y,int width,int height)
  3398. {
  3399. int numChildren = getComponentCount();
  3400. for(int i = 0; i < numChildren; i++) {
  3401. Component child = getComponent(i);
  3402. Rectangle childBounds;
  3403. if (child instanceof JComponent) {
  3404. childBounds = ((JComponent)child)._bounds;
  3405. } else {
  3406. childBounds = child.getBounds();
  3407. }
  3408. if (x >= childBounds.x && (x + width) <= (childBounds.x + childBounds.width) &&
  3409. y >= childBounds.y && (y + height) <= (childBounds.y + childBounds.height) && child.isVisible()) {
  3410. if(child instanceof JComponent) {
  3411. // System.out.println("A) checking opaque: " + ((JComponent)child).isOpaque() + " " + child);
  3412. // System.out.print("B) ");
  3413. // Thread.dumpStack();
  3414. return ((JComponent)child).isOpaque();
  3415. } else {
  3416. /** Sometimes a heavy weight can have a bound larger than its peer size
  3417. * so we should always draw under heavy weights
  3418. */
  3419. return false;
  3420. }
  3421. }
  3422. }
  3423. return false;
  3424. }
  3425. /**
  3426. * Returns the <code>Component</code>'s "visible rect rectangle" - the
  3427. * intersection of the visible rectangles for the component <code>c</code>
  3428. * and all of its ancestors. The return value is stored in
  3429. * <code>visibleRect</code>.
  3430. *
  3431. * @param c the component
  3432. * @param visibleRect a <code>Rectangle</code> computed as the
  3433. * intersection of all visible rectangles for the component
  3434. * <code>c</code> and all of its ancestors -- this is the
  3435. * return value for this method
  3436. * @see #getVisibleRect
  3437. */
  3438. static final void computeVisibleRect(Component c, Rectangle visibleRect) {
  3439. Container p = c.getParent();
  3440. Rectangle bounds = c.getBounds();
  3441. if (p == null || p instanceof Window || p instanceof Applet) {
  3442. visibleRect.setBounds(0, 0, bounds.width, bounds.height);
  3443. } else {
  3444. computeVisibleRect(p, visibleRect);
  3445. visibleRect.x -= bounds.x;
  3446. visibleRect.y -= bounds.y;
  3447. SwingUtilities.computeIntersection(0,0,bounds.width,bounds.height,visibleRect);
  3448. }
  3449. }
  3450. /**
  3451. * Returns the <code>Component</code>'s "visible rect rectangle" - the
  3452. * intersection of the visible rectangles for this component
  3453. * and all of its ancestors. The return value is stored in
  3454. * <code>visibleRect</code>.
  3455. *
  3456. * @param visibleRect a <code>Rectangle</code> computed as the
  3457. * intersection of all visible rectangles for this
  3458. * component and all of its ancestors -- this is the return
  3459. * value for this method
  3460. * @see #getVisibleRect
  3461. */
  3462. public void computeVisibleRect(Rectangle visibleRect) {
  3463. computeVisibleRect(this, visibleRect);
  3464. }
  3465. /**
  3466. * Returns the <code>Component</code>'s "visible rectangle" - the
  3467. * intersection of this component's visible rectangle:
  3468. * <pre>
  3469. * new Rectangle(0, 0, getWidth(), getHeight());
  3470. * </pre>
  3471. * and all of its ancestors' visible rectangles.
  3472. *
  3473. * @return the visible rectangle
  3474. */
  3475. public Rectangle getVisibleRect() {
  3476. Rectangle visibleRect = new Rectangle();
  3477. computeVisibleRect(visibleRect);
  3478. return visibleRect;
  3479. }
  3480. /**
  3481. * Supports reporting bound property changes. If <code>oldValue</code>
  3482. * and <code>newValue</code> are not equal and the
  3483. * <code>PropertyChangeEvent</code> listener list isn't empty,
  3484. * then fire a <code>PropertyChange</code> event to each listener.
  3485. * This method has an overloaded method for each primitive type. For
  3486. * example, here's how to write a bound property set method whose
  3487. * value is an integer:
  3488. * <pre>
  3489. * public void setFoo(int newValue) {
  3490. * int oldValue = foo;
  3491. * foo = newValue;
  3492. * firePropertyChange("foo", oldValue, newValue);
  3493. * }
  3494. * </pre>
  3495. *
  3496. * @param propertyName the programmatic name of the property
  3497. * that was changed
  3498. * @param oldValue the old value of the property (as an Object)
  3499. * @param newValue the new value of the property (as an Object)
  3500. * @see java.beans.PropertyChangeSupport
  3501. */
  3502. protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
  3503. if (changeSupport != null) {
  3504. changeSupport.firePropertyChange(propertyName, oldValue, newValue);
  3505. }
  3506. }
  3507. /*
  3508. * PENDING(hmuller) in JDK1.2 the following firePropertyChange overloads
  3509. * should additional check for a non-empty listener list with
  3510. * changeSupport.hasListeners(propertyName) before calling
  3511. * firePropertyChange.
  3512. */
  3513. /**
  3514. * Reports a bound property change.
  3515. *
  3516. * @param propertyName the programmatic name of the property
  3517. * that was changed
  3518. * @param oldValue the old value of the property (as a byte)
  3519. * @param newValue the new value of the property (as a byte)
  3520. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3521. * java.lang.Object)
  3522. */
  3523. public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {
  3524. if ((changeSupport != null) && (oldValue != newValue)) {
  3525. changeSupport.firePropertyChange(propertyName, new Byte(oldValue), new Byte(newValue));
  3526. }
  3527. }
  3528. /**
  3529. * Reports a bound property change.
  3530. *
  3531. * @param propertyName the programmatic name of the property
  3532. * that was changed
  3533. * @param oldValue the old value of the property (as a char)
  3534. * @param newValue the new value of the property (as a char)
  3535. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3536. * java.lang.Object)
  3537. */
  3538. public void firePropertyChange(String propertyName, char oldValue, char newValue) {
  3539. if ((changeSupport != null) && (oldValue != newValue)) {
  3540. changeSupport.firePropertyChange(propertyName, new Character(oldValue), new Character(newValue));
  3541. }
  3542. }
  3543. /**
  3544. * Reports a bound property change.
  3545. *
  3546. * @param propertyName the programmatic name of the property
  3547. * that was changed
  3548. * @param oldValue the old value of the property (as a short)
  3549. * @param newValue the old value of the property (as a short)
  3550. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3551. * java.lang.Object)
  3552. */
  3553. public void firePropertyChange(String propertyName, short oldValue, short newValue) {
  3554. if ((changeSupport != null) && (oldValue != newValue)) {
  3555. changeSupport.firePropertyChange(propertyName, new Short(oldValue), new Short(newValue));
  3556. }
  3557. }
  3558. /**
  3559. * Reports a bound property change.
  3560. *
  3561. * @param propertyName the programmatic name of the property
  3562. * that was changed
  3563. * @param oldValue the old value of the property (as an int)
  3564. * @param newValue the new value of the property (as an int)
  3565. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3566. * java.lang.Object)
  3567. */
  3568. public void firePropertyChange(String propertyName, int oldValue, int newValue) {
  3569. if ((changeSupport != null) && (oldValue != newValue)) {
  3570. changeSupport.firePropertyChange(propertyName, new Integer(oldValue), new Integer(newValue));
  3571. }
  3572. }
  3573. /**
  3574. * Reports a bound property change.
  3575. *
  3576. * @param propertyName the programmatic name of the property
  3577. * that was changed
  3578. * @param oldValue the old value of the property (as a long)
  3579. * @param newValue the new value of the property (as a long)
  3580. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3581. * java.lang.Object)
  3582. */
  3583. public void firePropertyChange(String propertyName, long oldValue, long newValue) {
  3584. if ((changeSupport != null) && (oldValue != newValue)) {
  3585. changeSupport.firePropertyChange(propertyName, new Long(oldValue), new Long(newValue));
  3586. }
  3587. }
  3588. /**
  3589. * Reports a bound property change.
  3590. *
  3591. * @param propertyName the programmatic name of the property
  3592. * that was changed
  3593. * @param oldValue the old value of the property (as a float)
  3594. * @param newValue the new value of the property (as a float)
  3595. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3596. * java.lang.Object)
  3597. */
  3598. public void firePropertyChange(String propertyName, float oldValue, float newValue) {
  3599. if ((changeSupport != null) && (oldValue != newValue)) {
  3600. changeSupport.firePropertyChange(propertyName, new Float(oldValue), new Float(newValue));
  3601. }
  3602. }
  3603. /**
  3604. * Reports a bound property change.
  3605. *
  3606. * @param propertyName the programmatic name of the property
  3607. * that was changed
  3608. * @param oldValue the old value of the property (as a double)
  3609. * @param newValue the new value of the property (as a double)
  3610. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3611. * java.lang.Object)
  3612. */
  3613. public void firePropertyChange(String propertyName, double oldValue, double newValue) {
  3614. if ((changeSupport != null) && (oldValue != newValue)) {
  3615. changeSupport.firePropertyChange(propertyName, new Double(oldValue), new Double(newValue));
  3616. }
  3617. }
  3618. /**
  3619. * Reports a bound property change.
  3620. *
  3621. * @param propertyName the programmatic name of the property
  3622. * that was changed
  3623. * @param oldValue the old value of the property (as a boolean)
  3624. * @param newValue the new value of the property (as a boolean)
  3625. * @see #firePropertyChange(java.lang.String, java.lang.Object,
  3626. * java.lang.Object)
  3627. */
  3628. public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
  3629. if ((changeSupport != null) && (oldValue != newValue)) {
  3630. changeSupport.firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
  3631. }
  3632. }
  3633. /**
  3634. * Adds a <code>PropertyChangeListener</code> to the listener list.
  3635. * The listener is registered for all properties.
  3636. * <p>
  3637. * A <code>PropertyChangeEvent</code> will get fired in response
  3638. * to setting a bound property, such as <code>setFont</code>,
  3639. * <code>setBackground</code>, or <code>setForeground</code>.
  3640. * <p>
  3641. * Note that if the current component is inheriting its foreground,
  3642. * background, or font from its container, then no event will be
  3643. * fired in response to a change in the inherited property.
  3644. *
  3645. * @param listener the <code>PropertyChangeListener</code> to be added
  3646. */
  3647. public synchronized void addPropertyChangeListener(PropertyChangeListener listener) {
  3648. if (changeSupport == null) {
  3649. changeSupport = new SwingPropertyChangeSupport(this);
  3650. }
  3651. changeSupport.addPropertyChangeListener(listener);
  3652. }
  3653. /**
  3654. * Adds a <code>PropertyChangeListener</code> for a specific property.
  3655. * The listener will be invoked only when a call on
  3656. * <code>firePropertyChange</code> names that specific property.
  3657. * <p>
  3658. * If listener is <code>null</code>, no exception is thrown and no
  3659. * action is performed.
  3660. *
  3661. * @param propertyName the name of the property to listen on
  3662. * @param listener the <code>PropertyChangeListener</code> to be added
  3663. */
  3664. public synchronized void addPropertyChangeListener(
  3665. String propertyName,
  3666. PropertyChangeListener listener) {
  3667. if (listener == null) {
  3668. return;
  3669. }
  3670. if (changeSupport == null) {
  3671. changeSupport = new SwingPropertyChangeSupport(this);
  3672. }
  3673. changeSupport.addPropertyChangeListener(propertyName, listener);
  3674. }
  3675. /**
  3676. * Removes a <code>PropertyChangeListener</code> from the listener list.
  3677. * This removes a <code>PropertyChangeListener</code> that was registered
  3678. * for all properties.
  3679. *
  3680. * @param listener the <code>PropertyChangeListener</code> to be removed
  3681. */
  3682. public synchronized void removePropertyChangeListener(PropertyChangeListener listener) {
  3683. if (changeSupport != null) {
  3684. changeSupport.removePropertyChangeListener(listener);
  3685. }
  3686. }
  3687. /**
  3688. * Removes a <code>PropertyChangeListener</code> for a specific property.
  3689. * If listener is <code>null</code>, no exception is thrown and no
  3690. * action is performed.
  3691. *
  3692. * @param propertyName the name of the property that was listened on
  3693. * @param listener the <code>PropertyChangeListener</code> to be removed
  3694. */
  3695. public synchronized void removePropertyChangeListener(
  3696. String propertyName,
  3697. PropertyChangeListener listener) {
  3698. if (listener == null) {
  3699. return;
  3700. }
  3701. if (changeSupport == null) {
  3702. return;
  3703. }
  3704. changeSupport.removePropertyChangeListener(propertyName, listener);
  3705. }
  3706. /**
  3707. * Returns an array of all the <code>PropertyChangeListener</code>s
  3708. * added to this Component with addPropertyChangeListener().
  3709. *
  3710. * @return all of the <code>PropertyChangeListener</code>s added or
  3711. * an empty array if no listeners have been added
  3712. *
  3713. * @see #addPropertyChangeListener
  3714. * @see #removePropertyChangeListener
  3715. * @see #getPropertyChangeListeners(java.lang.String)
  3716. * @see java.beans.PropertyChangeSupport#getPropertyChangeListeners
  3717. * @since 1.4
  3718. */
  3719. public synchronized PropertyChangeListener[] getPropertyChangeListeners() {
  3720. if (changeSupport == null) {
  3721. return new PropertyChangeListener[0];
  3722. }
  3723. return changeSupport.getPropertyChangeListeners();
  3724. }
  3725. /**
  3726. * Returns an array of all the listeners which have been associated
  3727. * with the named property.
  3728. *
  3729. * @return all of the <code>PropertyChangeListeners</code> associated with
  3730. * the named property or an empty array if no listeners have
  3731. * been added
  3732. * @see #getPropertyChangeListeners
  3733. * @since 1.4
  3734. */
  3735. public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
  3736. if (changeSupport == null) {
  3737. return new PropertyChangeListener[0];
  3738. }
  3739. return changeSupport.getPropertyChangeListeners(propertyName);
  3740. }
  3741. /**
  3742. * Supports reporting constrained property changes.
  3743. * This method can be called when a constrained property has changed
  3744. * and it will send the appropriate <code>PropertyChangeEvent</code>
  3745. * to any registered <code>VetoableChangeListeners</code>.
  3746. *
  3747. * @param propertyName the name of the property that was listened on
  3748. * @param oldValue the old value of the property
  3749. * @param newValue the new value of the property
  3750. * @exception PropertyVetoException when the attempt to set the
  3751. * property is vetoed by the component
  3752. */
  3753. protected void fireVetoableChange(String propertyName, Object oldValue, Object newValue)
  3754. throws java.beans.PropertyVetoException
  3755. {
  3756. if (vetoableChangeSupport == null) {
  3757. return;
  3758. }
  3759. vetoableChangeSupport.fireVetoableChange(propertyName, oldValue, newValue);
  3760. }
  3761. /**
  3762. * Adds a <code>VetoableChangeListener</code> to the listener list.
  3763. * The listener is registered for all properties.
  3764. *
  3765. * @param listener the <code>VetoableChangeListener</code> to be added
  3766. */
  3767. public synchronized void addVetoableChangeListener(VetoableChangeListener listener) {
  3768. if (vetoableChangeSupport == null) {
  3769. vetoableChangeSupport = new java.beans.VetoableChangeSupport(this);
  3770. }
  3771. vetoableChangeSupport.addVetoableChangeListener(listener);
  3772. }
  3773. /**
  3774. * Removes a <code>VetoableChangeListener</code> from the listener list.
  3775. * This removes a <code>VetoableChangeListener</code> that was registered
  3776. * for all properties.
  3777. *
  3778. * @param listener the <code>VetoableChangeListener</code> to be removed
  3779. */
  3780. public synchronized void removeVetoableChangeListener(VetoableChangeListener listener) {
  3781. if (vetoableChangeSupport == null) {
  3782. return;
  3783. }
  3784. vetoableChangeSupport.removeVetoableChangeListener(listener);
  3785. }
  3786. /**
  3787. * Returns an array of all the vetoable change listeners
  3788. * registered on this component.
  3789. *
  3790. * @return all of the component's <code>VetoableChangeListener</code>s
  3791. * or an empty
  3792. * array if no vetoable change listeners are currently registered
  3793. *
  3794. * @see #addVetoableChangeListener
  3795. * @see #removeVetoableChangeListener
  3796. *
  3797. * @since 1.4
  3798. */
  3799. public synchronized VetoableChangeListener[] getVetoableChangeListeners() {
  3800. if (vetoableChangeSupport == null) {
  3801. return new VetoableChangeListener[0];
  3802. }
  3803. return vetoableChangeSupport.getVetoableChangeListeners();
  3804. }
  3805. /**
  3806. * Returns the top-level ancestor of this component (either the
  3807. * containing <code>Window</code> or <code>Applet</code>),
  3808. * or <code>null</code> if this component has not
  3809. * been added to any container.
  3810. *
  3811. * @return the top-level <code>Container</code> that this component is in,
  3812. * or <code>null</code> if not in any container
  3813. */
  3814. public Container getTopLevelAncestor() {
  3815. for(Container p = this; p != null; p = p.getParent()) {
  3816. if(p instanceof Window || p instanceof Applet) {
  3817. return p;
  3818. }
  3819. }
  3820. return null;
  3821. }
  3822. /**
  3823. * Registers <code>listener</code> so that it will receive
  3824. * <code>AncestorEvents</code> when it or any of its ancestors
  3825. * move or are made visible or invisible.
  3826. * Events are also sent when the component or its ancestors are added
  3827. * or removed from the containment hierarchy.
  3828. *
  3829. * @param listener the <code>AncestorListener</code> to register
  3830. * @see AncestorEvent
  3831. */
  3832. public void addAncestorListener(AncestorListener listener) {
  3833. if (ancestorNotifier == null) {
  3834. ancestorNotifier = new AncestorNotifier(this);
  3835. }
  3836. ancestorNotifier.addAncestorListener(listener);
  3837. }
  3838. /**
  3839. * Unregisters <code>listener</code> so that it will no longer receive
  3840. * <code>AncestorEvents</code>.
  3841. *
  3842. * @param listener the <code>AncestorListener</code> to be removed
  3843. * @see #addAncestorListener
  3844. */
  3845. public void removeAncestorListener(AncestorListener listener) {
  3846. if (ancestorNotifier == null) {
  3847. return;
  3848. }
  3849. ancestorNotifier.removeAncestorListener(listener);
  3850. if (ancestorNotifier.listenerList.getListenerList().length == 0) {
  3851. ancestorNotifier.removeAllListeners();
  3852. ancestorNotifier = null;
  3853. }
  3854. }
  3855. /**
  3856. * Returns an array of all the ancestor listeners
  3857. * registered on this component.
  3858. *
  3859. * @return all of the component's <code>AncestorListener</code>s
  3860. * or an empty
  3861. * array if no ancestor listeners are currently registered
  3862. *
  3863. * @see #addAncestorListener
  3864. * @see #removeAncestorListener
  3865. *
  3866. * @since 1.4
  3867. */
  3868. public AncestorListener[] getAncestorListeners() {
  3869. if (ancestorNotifier == null) {
  3870. return new AncestorListener[0];
  3871. }
  3872. return ancestorNotifier.getAncestorListeners();
  3873. }
  3874. /**
  3875. * Returns an array of all the objects currently registered
  3876. * as <code><em>Foo</em>Listener</code>s
  3877. * upon this <code>JComponent</code>.
  3878. * <code><em>Foo</em>Listener</code>s are registered using the
  3879. * <code>add<em>Foo</em>Listener</code> method.
  3880. *
  3881. * <p>
  3882. *
  3883. * You can specify the <code>listenerType</code> argument
  3884. * with a class literal,
  3885. * such as
  3886. * <code><em>Foo</em>Listener.class</code>.
  3887. * For example, you can query a
  3888. * <code>JComponent</code> <code>c</code>
  3889. * for its mouse listeners with the following code:
  3890. * <pre>MouseListener[] mls = (MouseListener[])(c.getListeners(MouseListener.class));</pre>
  3891. * If no such listeners exist, this method returns an empty array.
  3892. *
  3893. * @param listenerType the type of listeners requested; this parameter
  3894. * should specify an interface that descends from
  3895. * <code>java.util.EventListener</code>
  3896. * @return an array of all objects registered as
  3897. * <code><em>Foo</em>Listener</code>s on this component,
  3898. * or an empty array if no such
  3899. * listeners have been added
  3900. * @exception ClassCastException if <code>listenerType</code>
  3901. * doesn't specify a class or interface that implements
  3902. * <code>java.util.EventListener</code>
  3903. *
  3904. * @since 1.3
  3905. *
  3906. * @see #getVetoableChangeListeners
  3907. * @see #getAncestorListeners
  3908. */
  3909. public EventListener[] getListeners(Class listenerType) {
  3910. EventListener[] result;
  3911. if (listenerType == AncestorListener.class) {
  3912. // AncestorListeners are handled by the AncestorNotifier
  3913. result = getAncestorListeners();
  3914. }
  3915. else if (listenerType == VetoableChangeListener.class) {
  3916. // VetoableChangeListeners are handled by VetoableChangeSupport
  3917. result = getVetoableChangeListeners();
  3918. }
  3919. else if (listenerType == PropertyChangeListener.class) {
  3920. // PropertyChangeListeners are handled by PropertyChangeSupport
  3921. result = getPropertyChangeListeners();
  3922. }
  3923. else {
  3924. result = listenerList.getListeners(listenerType);
  3925. }
  3926. if (result.length == 0) {
  3927. return super.getListeners(listenerType);
  3928. }
  3929. return result;
  3930. }
  3931. /**
  3932. * Notifies this component that it now has a parent component.
  3933. * When this method is invoked, the chain of parent components is
  3934. * set up with <code>KeyboardAction</code> event listeners.
  3935. *
  3936. * @see #registerKeyboardAction
  3937. */
  3938. public void addNotify() {
  3939. super.addNotify();
  3940. firePropertyChange("ancestor", null, getParent());
  3941. registerWithKeyboardManager(false);
  3942. registerNextFocusableComponent();
  3943. }
  3944. /**
  3945. * Notifies this component that it no longer has a parent component.
  3946. * When this method is invoked, any <code>KeyboardAction</code>s
  3947. * set up in the the chain of parent components are removed.
  3948. *
  3949. * @see #registerKeyboardAction
  3950. */
  3951. public void removeNotify() {
  3952. super.removeNotify();
  3953. // This isn't strictly correct. The event shouldn't be
  3954. // fired until *after* the parent is set to null. But
  3955. // we only get notified before that happens
  3956. firePropertyChange("ancestor", getParent(), null);
  3957. unregisterWithKeyboardManager();
  3958. deregisterNextFocusableComponent();
  3959. if (getCreatedDoubleBuffer()) {
  3960. RepaintManager.currentManager(this).resetDoubleBuffer();
  3961. setCreatedDoubleBuffer(false);
  3962. }
  3963. }
  3964. /**
  3965. * Adds the specified region to the dirty region list if the component
  3966. * is showing. The component will be repainted after all of the
  3967. * currently pending events have been dispatched.
  3968. *
  3969. * @param tm this parameter is not used
  3970. * @param x the x value of the dirty region
  3971. * @param y the y value of the dirty region
  3972. * @param width the width of the dirty region
  3973. * @param height the height of the dirty region
  3974. * @see java.awt.Component#isShowing
  3975. * @see RepaintManager#addDirtyRegion
  3976. */
  3977. public void repaint(long tm, int x, int y, int width, int height) {
  3978. RepaintManager.currentManager(this).addDirtyRegion(this, x, y, width, height);
  3979. }
  3980. /**
  3981. * Adds the specified region to the dirty region list if the component
  3982. * is showing. The component will be repainted after all of the
  3983. * currently pending events have been dispatched.
  3984. *
  3985. * @param r a <code>Rectangle</code> containing the dirty region
  3986. * @see java.awt.Component#isShowing
  3987. * @see RepaintManager#addDirtyRegion
  3988. */
  3989. public void repaint(Rectangle r) {
  3990. repaint(0,r.x,r.y,r.width,r.height);
  3991. }
  3992. /**
  3993. * Supports deferred automatic layout.
  3994. * <p>
  3995. * Calls <code>invalidate</code> and then adds this component's
  3996. * <code>validateRoot</code> to a list of components that need to be
  3997. * validated. Validation will occur after all currently pending
  3998. * events have been dispatched. In other words after this method
  3999. * is called, the first validateRoot (if any) found when walking
  4000. * up the containment hierarchy of this component will be validated.
  4001. * By default, <code>JRootPane</code>, <code>JScrollPane</code>,
  4002. * and <code>JTextField</code> return true
  4003. * from <code>isValidateRoot</code>.
  4004. * <p>
  4005. * This method will automatically be called on this component
  4006. * when a property value changes such that size, location, or
  4007. * internal layout of this component has been affected. This automatic
  4008. * updating differs from the AWT because programs generally no
  4009. * longer need to invoke <code>validate</code> to get the contents of the
  4010. * GUI to update.
  4011. * <p>
  4012. *
  4013. * @see java.awt.Component#invalidate
  4014. * @see java.awt.Container#validate
  4015. * @see #isValidateRoot
  4016. * @see RepaintManager#addInvalidComponent
  4017. */
  4018. public void revalidate() {
  4019. if (getParent() == null) {
  4020. // Note: We don't bother invalidating here as once added
  4021. // to a valid parent invalidate will be invoked (addImpl
  4022. // invokes addNotify which will invoke invalidate on the
  4023. // new Component). Also, if we do add a check to isValid
  4024. // here it can potentially be called before the constructor
  4025. // which was causing some people grief.
  4026. return;
  4027. }
  4028. if (SwingUtilities.isEventDispatchThread()) {
  4029. invalidate();
  4030. RepaintManager.currentManager(this).addInvalidComponent(this);
  4031. }
  4032. else {
  4033. Runnable callRevalidate = new Runnable() {
  4034. public void run() {
  4035. revalidate();
  4036. }
  4037. };
  4038. SwingUtilities.invokeLater(callRevalidate);
  4039. }
  4040. }
  4041. /**
  4042. * If this method returns true, <code>revalidate</code> calls by
  4043. * descendants of this component will cause the entire tree
  4044. * beginning with this root to be validated.
  4045. * Returns false by default. <code>JScrollPane</code> overrides
  4046. * this method and returns true.
  4047. *
  4048. * @return always returns false
  4049. * @see #revalidate
  4050. * @see java.awt.Component#invalidate
  4051. * @see java.awt.Container#validate
  4052. */
  4053. public boolean isValidateRoot() {
  4054. return false;
  4055. }
  4056. /**
  4057. * Returns true if this component tiles its children -- that is, if
  4058. * it can guarantee that the children will not overlap. The
  4059. * repainting system is substantially more efficient in this
  4060. * common case. <code>JComponent</code> subclasses that can't make this
  4061. * guarantee, such as <code>JLayeredPane</code>,
  4062. * should override this method to return false.
  4063. *
  4064. * @return always returns true
  4065. */
  4066. public boolean isOptimizedDrawingEnabled() {
  4067. return true;
  4068. }
  4069. /**
  4070. * Returns true if a paint triggered on a child component should cause
  4071. * painting to originate from this Component, or one of its ancestors.
  4072. *
  4073. * @return true if painting should originate from this Component or
  4074. * one of its ancestors.
  4075. */
  4076. boolean isPaintingOrigin() {
  4077. return false;
  4078. }
  4079. /**
  4080. * Paints the specified region in this component and all of its
  4081. * descendants that overlap the region, immediately.
  4082. * <p>
  4083. * It's rarely necessary to call this method. In most cases it's
  4084. * more efficient to call repaint, which defers the actual painting
  4085. * and can collapse redundant requests into a single paint call.
  4086. * This method is useful if one needs to update the display while
  4087. * the current event is being dispatched.
  4088. *
  4089. * @param x the x value of the region to be painted
  4090. * @param y the y value of the region to be painted
  4091. * @param w the width of the region to be painted
  4092. * @param h the height of the region to be painted
  4093. * @see #repaint
  4094. */
  4095. public void paintImmediately(int x,int y,int w, int h) {
  4096. Component c = this;
  4097. Component parent;
  4098. Rectangle bounds;
  4099. if(!isShowing()) {
  4100. return;
  4101. }
  4102. while(!((JComponent)c).isOpaque()) {
  4103. parent = c.getParent();
  4104. if(parent != null) {
  4105. if(c instanceof JComponent) {
  4106. bounds = ((JComponent)c)._bounds;
  4107. } else {
  4108. bounds = c.getBounds();
  4109. }
  4110. x += bounds.x;
  4111. y += bounds.y;
  4112. c = parent;
  4113. } else {
  4114. break;
  4115. }
  4116. if(!(c instanceof JComponent)) {
  4117. break;
  4118. }
  4119. }
  4120. if(c instanceof JComponent) {
  4121. ((JComponent)c)._paintImmediately(x,y,w,h);
  4122. } else {
  4123. c.repaint(x,y,w,h);
  4124. }
  4125. }
  4126. /**
  4127. * Paints the specified region now.
  4128. *
  4129. * @param r a <code>Rectangle</code> containing the region to be painted
  4130. */
  4131. public void paintImmediately(Rectangle r) {
  4132. paintImmediately(r.x,r.y,r.width,r.height);
  4133. }
  4134. /**
  4135. * Returns whether this component should be guaranteed to be on top.
  4136. * For example, it would make no sense for <code>Menu</code>s to pop up
  4137. * under another component, so they would always return true.
  4138. * Most components will want to return false, hence that is the default.
  4139. *
  4140. * @return always returns false
  4141. */
  4142. // package private
  4143. boolean alwaysOnTop() {
  4144. return false;
  4145. }
  4146. private Rectangle paintImmediatelyClip = new Rectangle(0,0,0,0);
  4147. void setPaintingChild(Component paintingChild) {
  4148. this.paintingChild = paintingChild;
  4149. }
  4150. void _paintImmediately(int x, int y, int w, int h) {
  4151. Graphics g;
  4152. Container c;
  4153. Rectangle b;
  4154. int tmpX, tmpY, tmpWidth, tmpHeight;
  4155. int offsetX=0,offsetY=0;
  4156. boolean hasBuffer = false;
  4157. JComponent bufferedComponent = null;
  4158. JComponent paintingComponent = this;
  4159. RepaintManager repaintManager = RepaintManager.currentManager(this);
  4160. // parent Container's up to Window or Applet. First container is
  4161. // the direct parent. Note that in testing it was faster to
  4162. // alloc a new Vector vs keeping a stack of them around, and gc
  4163. // seemed to have a minimal effect on this.
  4164. Vector path = new Vector(7);
  4165. int pIndex = -1;
  4166. int pCount = 0;
  4167. tmpX = tmpY = tmpWidth = tmpHeight = 0;
  4168. paintImmediatelyClip.x = x;
  4169. paintImmediatelyClip.y = y;
  4170. paintImmediatelyClip.width = w;
  4171. paintImmediatelyClip.height = h;
  4172. // System.out.println("1) ************* in _paintImmediately for " + this);
  4173. boolean ontop = alwaysOnTop() && isOpaque();
  4174. Component child;
  4175. for (c = this, child = null;
  4176. c != null && !(c instanceof Window) && !(c instanceof Applet);
  4177. child = c, c = c.getParent()) {
  4178. JComponent jc = (c instanceof JComponent) ? (JComponent)c :
  4179. null;
  4180. path.addElement(c);
  4181. if(!ontop && jc != null && !jc.isOptimizedDrawingEnabled()) {
  4182. boolean resetPC;
  4183. // Children of c may overlap, three possible cases for the
  4184. // painting region:
  4185. // . Completely obscured by an opaque sibling, in which
  4186. // case there is no need to paint.
  4187. // . Partially obscured by a sibling: need to start
  4188. // painting from c.
  4189. // . Otherwise we aren't obscured and thus don't need to
  4190. // start painting from parent.
  4191. if (c != this) {
  4192. if (jc.isPaintingOrigin()) {
  4193. resetPC = true;
  4194. }
  4195. else {
  4196. Component[] children = c.getComponents();
  4197. int i = 0;
  4198. for (; i<children.length; i++) {
  4199. if (children[i] == child) break;
  4200. }
  4201. switch (jc.getObscuredState(i,
  4202. paintImmediatelyClip.x,
  4203. paintImmediatelyClip.y,
  4204. paintImmediatelyClip.width,
  4205. paintImmediatelyClip.height)) {
  4206. case NOT_OBSCURED:
  4207. resetPC = false;
  4208. break;
  4209. case COMPLETELY_OBSCURED:
  4210. return;
  4211. default:
  4212. resetPC = true;
  4213. break;
  4214. }
  4215. }
  4216. }
  4217. else {
  4218. resetPC = false;
  4219. }
  4220. if (resetPC) {
  4221. // Get rid of any buffer since we draw from here and
  4222. // we might draw something larger
  4223. paintingComponent = jc;
  4224. pIndex = pCount;
  4225. offsetX = offsetY = 0;
  4226. hasBuffer = false;
  4227. }
  4228. }
  4229. pCount++;
  4230. // look to see if the parent (and therefor this component)
  4231. // is double buffered
  4232. if(repaintManager.isDoubleBufferingEnabled() && jc != null &&
  4233. jc.isDoubleBuffered()) {
  4234. hasBuffer = true;
  4235. bufferedComponent = jc;
  4236. }
  4237. // if we aren't on top, include the parent's clip
  4238. if (!ontop) {
  4239. if (jc != null) {
  4240. b = jc._bounds;
  4241. } else {
  4242. b = c.getBounds();
  4243. }
  4244. tmpWidth = b.width;
  4245. tmpHeight = b.height;
  4246. SwingUtilities.computeIntersection(tmpX,tmpY,tmpWidth,tmpHeight,paintImmediatelyClip);
  4247. paintImmediatelyClip.x += b.x;
  4248. paintImmediatelyClip.y += b.y;
  4249. offsetX += b.x;
  4250. offsetY += b.y;
  4251. }
  4252. }
  4253. if(c == null || c.getPeer() == null) {
  4254. return;
  4255. }
  4256. // If the clip width or height is negative, don't bother painting
  4257. if(paintImmediatelyClip.width <= 0 || paintImmediatelyClip.height <= 0) {
  4258. return;
  4259. }
  4260. paintingComponent.setFlag(IS_REPAINTING, true);
  4261. paintImmediatelyClip.x -= offsetX;
  4262. paintImmediatelyClip.y -= offsetY;
  4263. // Notify the Components that are going to be painted of the
  4264. // child component to paint to.
  4265. if(paintingComponent != this) {
  4266. Component comp;
  4267. int i = pIndex;
  4268. for(; i > 0 ; i--) {
  4269. comp = (Component) path.elementAt(i);
  4270. if(comp instanceof JComponent) {
  4271. ((JComponent)comp).setPaintingChild
  4272. ((Component)path.elementAt(i-1));
  4273. }
  4274. }
  4275. }
  4276. try {
  4277. try {
  4278. Graphics pcg = paintingComponent.getGraphics();
  4279. g = SwingGraphics.createSwingGraphics(pcg);
  4280. pcg.dispose();
  4281. } catch(NullPointerException e) {
  4282. g = null;
  4283. e.printStackTrace();
  4284. }
  4285. if (g == null) {
  4286. System.err.println("In paintImmediately null graphics");
  4287. return;
  4288. }
  4289. try {
  4290. boolean paintCompleted = false;
  4291. if (hasBuffer) {
  4292. paintCompleted = paintDoubleBuffered(paintingComponent, bufferedComponent, g,
  4293. paintImmediatelyClip.x,
  4294. paintImmediatelyClip.y,
  4295. paintImmediatelyClip.width,
  4296. paintImmediatelyClip.height);
  4297. }
  4298. if (!paintCompleted) {
  4299. //System.out.println("has no buffer");
  4300. g.setClip(paintImmediatelyClip.x,paintImmediatelyClip.y,
  4301. paintImmediatelyClip.width,paintImmediatelyClip.height);
  4302. paintingComponent.paint(g);
  4303. }
  4304. } finally {
  4305. g.dispose();
  4306. }
  4307. }
  4308. finally {
  4309. // Reset the painting child for the parent components.
  4310. if(paintingComponent != this) {
  4311. Component comp;
  4312. int i = pIndex;
  4313. for(; i > 0 ; i--) {
  4314. comp = (Component) path.elementAt(i);
  4315. if(comp instanceof JComponent) {
  4316. ((JComponent)comp).setPaintingChild(null);
  4317. }
  4318. }
  4319. }
  4320. path.removeAllElements();
  4321. paintingComponent.setFlag(IS_REPAINTING, false);
  4322. }
  4323. }
  4324. private boolean paintDoubleBuffered(JComponent paintingComponent, Component bufferComponent,
  4325. Graphics g, int clipX, int clipY, int clipW, int clipH) {
  4326. RepaintManager repaintManager = RepaintManager.currentManager(paintingComponent);
  4327. boolean paintCompleted = false;
  4328. Image offscreen = null;
  4329. // First attempt to use VolatileImage buffer for performance. If this fails
  4330. // (which should rarely occur), fallback to a standard Image buffer.
  4331. //
  4332. if (repaintManager.useVolatileDoubleBuffer() &&
  4333. (offscreen = repaintManager.getVolatileOffscreenBuffer(
  4334. bufferComponent,clipW,clipH)) != null &&
  4335. (offscreen.getWidth(null) > 0 && offscreen.getHeight(null) > 0)) {
  4336. VolatileImage vImage = (java.awt.image.VolatileImage)offscreen;
  4337. GraphicsConfiguration gc = bufferComponent.getGraphicsConfiguration();
  4338. for (int i = 0; !paintCompleted && i < RepaintManager.VOLATILE_LOOP_MAX; i++) {
  4339. if (vImage.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) {
  4340. repaintManager.resetVolatileDoubleBuffer(gc);
  4341. offscreen = repaintManager.getVolatileOffscreenBuffer(bufferComponent,clipW, clipH);
  4342. vImage = (java.awt.image.VolatileImage)offscreen;
  4343. }
  4344. paintWithOffscreenBuffer(paintingComponent, g, clipX, clipY, clipW, clipH, offscreen);
  4345. paintCompleted = !vImage.contentsLost();
  4346. }
  4347. }
  4348. if (!paintCompleted) {
  4349. // VolatileImage painting loop failed, fallback to regular offscreen buffer
  4350. if ((offscreen =
  4351. repaintManager.getOffscreenBuffer(bufferComponent, clipW, clipH)) != null &&
  4352. (offscreen.getWidth(null) > 0 && offscreen.getHeight(null) > 0)) {
  4353. paintWithOffscreenBuffer(paintingComponent, g, clipX, clipY, clipW, clipH, offscreen);
  4354. paintCompleted = true;
  4355. }
  4356. }
  4357. return paintCompleted;
  4358. }
  4359. private void paintWithOffscreenBuffer(JComponent paintingComponent, Graphics g,
  4360. int clipX, int clipY, int clipW, int clipH,
  4361. Image offscreen) {
  4362. Graphics og = offscreen.getGraphics();
  4363. Graphics osg = SwingGraphics.createSwingGraphics(og);
  4364. og.dispose();
  4365. int bw = offscreen.getWidth(null);
  4366. int bh = offscreen.getHeight(null);
  4367. int x,y,maxx,maxy;
  4368. if (bw > clipW) {
  4369. bw = clipW;
  4370. }
  4371. if (bh > clipH) {
  4372. bh = clipH;
  4373. }
  4374. try {
  4375. paintingComponent.setFlag(ANCESTOR_USING_BUFFER,true);
  4376. paintingComponent.setFlag(IS_PAINTING_TILE,true);
  4377. for(x = clipX, maxx = clipX+clipW; x < maxx ; x += bw ) {
  4378. for(y=clipY, maxy = clipY + clipH; y < maxy ; y += bh) {
  4379. if ((y+bh) >= maxy && (x+bw) >= maxx) {
  4380. paintingComponent.setFlag(IS_PAINTING_TILE,false);
  4381. }
  4382. osg.translate(-x,-y);
  4383. osg.setClip(x,y,bw,bh);
  4384. if (paintingComponent.getFlag(IS_REPAINTING)) {
  4385. // Called from paintImmediately (RepaintManager) to fill
  4386. // repaint request
  4387. paintingComponent.paint(osg);
  4388. } else {
  4389. // Called from paint() (AWT) to repair damage
  4390. if(!paintingComponent.rectangleIsObscured(clipX,clipY,bw,bh)) {
  4391. paintingComponent.paintComponent(osg);
  4392. paintingComponent.paintBorder(osg);
  4393. }
  4394. paintingComponent.paintChildren(osg);
  4395. }
  4396. g.setClip(x,y,bw,bh);
  4397. g.drawImage(offscreen,x,y,paintingComponent);
  4398. osg.translate(x,y);
  4399. }
  4400. }
  4401. } finally {
  4402. paintingComponent.setFlag(ANCESTOR_USING_BUFFER,false);
  4403. paintingComponent.setFlag(IS_PAINTING_TILE,false);
  4404. osg.dispose();
  4405. }
  4406. }
  4407. /**
  4408. * Returns whether or not the region of the specified component is
  4409. * obscured by a sibling.
  4410. *
  4411. * @return NOT_OBSCURED if non of the siblings above the Component obscure
  4412. * it, COMPLETELY_OBSCURED if one of the siblings completely
  4413. * obscures the Component or PARTIALLY_OBSCURED if the Comonent is
  4414. * only partially obscured.
  4415. */
  4416. // NOTE: This will tweak tmpRect!
  4417. private int getObscuredState(int compIndex, int x, int y, int width,
  4418. int height) {
  4419. int retValue = NOT_OBSCURED;
  4420. for (int i = compIndex - 1 ; i >= 0 ; i--) {
  4421. Component sibling = getComponent(i);
  4422. if (!sibling.isVisible()) {
  4423. continue;
  4424. }
  4425. Rectangle siblingRect;
  4426. boolean opaque;
  4427. if (sibling instanceof JComponent) {
  4428. opaque = ((JComponent)sibling).isOpaque();
  4429. if (!opaque) {
  4430. if (retValue == PARTIALLY_OBSCURED) {
  4431. continue;
  4432. }
  4433. }
  4434. siblingRect = ((JComponent)sibling).getBounds(tmpRect);
  4435. }
  4436. else {
  4437. siblingRect = sibling.getBounds();
  4438. opaque = true;
  4439. }
  4440. if (opaque && x >= siblingRect.x && (x + width) <=
  4441. (siblingRect.x + siblingRect.width) &&
  4442. y >= siblingRect.y && (y + height) <=
  4443. (siblingRect.y + siblingRect.height)) {
  4444. return COMPLETELY_OBSCURED;
  4445. }
  4446. else if (retValue == NOT_OBSCURED &&
  4447. !((x + width <= siblingRect.x) ||
  4448. (y + height <= siblingRect.y) ||
  4449. (x >= siblingRect.x + siblingRect.width) ||
  4450. (y >= siblingRect.y + siblingRect.height))) {
  4451. retValue = PARTIALLY_OBSCURED;
  4452. }
  4453. }
  4454. return retValue;
  4455. }
  4456. /**
  4457. * Returns true, which implies that before checking if a child should
  4458. * be painted it is first check that the child is not obscured by another
  4459. * sibling. This is only checked if <code>isOptimizedDrawingEnabled</code>
  4460. * returns false.
  4461. *
  4462. * @return always returns true
  4463. */
  4464. boolean checkIfChildObscuredBySibling() {
  4465. return true;
  4466. }
  4467. private void setFlag(int aFlag, boolean aValue) {
  4468. if(aValue) {
  4469. flags |= (1 << aFlag);
  4470. } else {
  4471. flags &= ~(1 << aFlag);
  4472. }
  4473. }
  4474. private boolean getFlag(int aFlag) {
  4475. int mask = (1 << aFlag);
  4476. return ((flags & mask) == mask);
  4477. }
  4478. // These functions must be static so that they can be called from
  4479. // subclasses inside the package, but whose inheritance hierarhcy includes
  4480. // classes outside of the package below JComponent (e.g., JTextArea).
  4481. static void setWriteObjCounter(JComponent comp, byte count) {
  4482. comp.flags = (comp.flags & ~(0xFF << WRITE_OBJ_COUNTER_FIRST)) |
  4483. (count << WRITE_OBJ_COUNTER_FIRST);
  4484. }
  4485. static byte getWriteObjCounter(JComponent comp) {
  4486. return (byte)((comp.flags >> WRITE_OBJ_COUNTER_FIRST) & 0xFF);
  4487. }
  4488. /** Buffering **/
  4489. /**
  4490. * Sets whether the this component should use a buffer to paint.
  4491. * If set to true, all the drawing from this component will be done
  4492. * in an offscreen painting buffer. The offscreen painting buffer will
  4493. * the be copied onto the screen.
  4494. * Swings painting system always uses a maximum of one double buffer.
  4495. * If a <code>Component</code> is buffered and one of its ancestor
  4496. * is also buffered, the ancestor buffer will be used.
  4497. *
  4498. * @param aFlag if true, set this component to be double buffered
  4499. */
  4500. public void setDoubleBuffered(boolean aFlag) {
  4501. setFlag(IS_DOUBLE_BUFFERED,aFlag);
  4502. }
  4503. /**
  4504. * Returns whether this component should use a buffer to paint.
  4505. *
  4506. * @return true if this component is double buffered, otherwise false
  4507. */
  4508. public boolean isDoubleBuffered() {
  4509. return getFlag(IS_DOUBLE_BUFFERED);
  4510. }
  4511. /**
  4512. * Returns the <code>JRootPane</code> ancestor for this component.
  4513. *
  4514. * @return the <code>JRootPane</code> that contains this component,
  4515. * or <code>null</code> if no <code>JRootPane</code> is found
  4516. */
  4517. public JRootPane getRootPane() {
  4518. return SwingUtilities.getRootPane(this);
  4519. }
  4520. /** Serialization **/
  4521. /**
  4522. * This class is used to give us an opportunity to uninstall the UI
  4523. * before <code>java.awt.Container.writeObject</code> runs.
  4524. * The <code>enableSerialization</code> method below adds an
  4525. * instance of this class to the <code>FocusListener</code>
  4526. * field in <code>java.awt.Component</code>.
  4527. * The <code>java.awt.Component.writeObject</code> method,
  4528. * which always runs before <code>java.awt.Container.writeObject</code>,
  4529. * effectively calls our <code>writeObject</code> method,
  4530. * which takes care of uninstalling the UI.
  4531. * <p>
  4532. * A <code>FocusListener</code> is used (any listener would do)
  4533. * because all Swing components listen for <code>Focus</code> events anyway.
  4534. * <p>
  4535. * Yes this is a hack. Unfortunately we don't know of a better way to make
  4536. * the UI property transient and work correctly on JDK1.1 VMs.
  4537. */
  4538. private class EnableSerializationFocusListener implements FocusListener, Serializable
  4539. {
  4540. public void focusGained(FocusEvent e) {}
  4541. public void focusLost(FocusEvent e) {}
  4542. private void writeObject(ObjectOutputStream s) throws IOException {
  4543. s.defaultWriteObject();
  4544. JComponent.this.compWriteObjectNotify();
  4545. }
  4546. }
  4547. /* Called from the <code>EnableSerializationFocusListener</code>
  4548. * to do any Swing-specific pre-serialization configuration.
  4549. */
  4550. void compWriteObjectNotify() {
  4551. byte count = JComponent.getWriteObjCounter(this);
  4552. JComponent.setWriteObjCounter(this, (byte)(count + 1));
  4553. if (count != 0) {
  4554. return;
  4555. }
  4556. if (ui != null) {
  4557. ui.uninstallUI(this);
  4558. }
  4559. /* JTableHeader is in a separate package, which prevents it from
  4560. * being able to override this package-private method the way the
  4561. * other components can. We don't want to make this method protected
  4562. * because it would introduce public-api for a less-than-desirable
  4563. * serialization scheme, so we compromise with this 'instanceof' hack
  4564. * for now.
  4565. */
  4566. if (getToolTipText() != null ||
  4567. this instanceof javax.swing.table.JTableHeader) {
  4568. ToolTipManager.sharedInstance().unregisterComponent(JComponent.this);
  4569. }
  4570. }
  4571. /**
  4572. * Called by the <code>JComponent</code> constructor.
  4573. * Adds a fake <code>FocusListener</code>
  4574. * whose real purpose is to uninstall the component's UI early.
  4575. */
  4576. void enableSerialization() {
  4577. addFocusListener(new EnableSerializationFocusListener());
  4578. }
  4579. /**
  4580. * This object is the <code>ObjectInputStream</code> callback
  4581. * that's called after a complete graph of objects (including at least
  4582. * one <code>JComponent</code>) has been read.
  4583. * It sets the UI property of each Swing component
  4584. * that was read to the current default with <code>updateUI</code>.
  4585. * <p>
  4586. * As each component is read in we keep track of the current set of
  4587. * root components here, in the roots vector. Note that there's only one
  4588. * <code>ReadObjectCallback</code> per <code>ObjectInputStream</code>,
  4589. * they're stored in the static <code>readObjectCallbacks</code>
  4590. * hashtable.
  4591. *
  4592. * @see java.io.ObjectInputStream#registerValidation
  4593. * @see SwingUtilities#updateComponentTreeUI
  4594. */
  4595. private class ReadObjectCallback implements ObjectInputValidation
  4596. {
  4597. private final Vector roots = new Vector(1);
  4598. private final ObjectInputStream inputStream;
  4599. ReadObjectCallback(ObjectInputStream s) throws Exception {
  4600. inputStream = s;
  4601. s.registerValidation(this, 0);
  4602. }
  4603. /**
  4604. * This is the method that's called after the entire graph
  4605. * of objects has been read in. It initializes
  4606. * the UI property of all of the copmonents with
  4607. * <code>SwingUtilities.updateComponentTreeUI</code>.
  4608. */
  4609. public void validateObject() throws InvalidObjectException {
  4610. try {
  4611. for(int i = 0; i < roots.size(); i++) {
  4612. JComponent root = (JComponent)(roots.elementAt(i));
  4613. SwingUtilities.updateComponentTreeUI(root);
  4614. }
  4615. }
  4616. finally {
  4617. readObjectCallbacks.remove(inputStream);
  4618. }
  4619. }
  4620. /**
  4621. * If <code>c</code> isn't a descendant of a component we've already
  4622. * seen, then add it to the roots <code>Vector</code>.
  4623. *
  4624. * @param c the <code>JComponent</code> to add
  4625. */
  4626. private void registerComponent(JComponent c)
  4627. {
  4628. /* If the Component c is a descendant of one of the
  4629. * existing roots (or it IS an existing root), we're done.
  4630. */
  4631. for(int i = 0; i < roots.size(); i++) {
  4632. JComponent root = (JComponent)roots.elementAt(i);
  4633. for(Component p = c; p != null; p = p.getParent()) {
  4634. if (p == root) {
  4635. return;
  4636. }
  4637. }
  4638. }
  4639. /* Otherwise: if Component c is an ancestor of any of the
  4640. * existing roots then remove them and add c (the "new root")
  4641. * to the roots vector.
  4642. */
  4643. for(int i = 0; i < roots.size(); i++) {
  4644. JComponent root = (JComponent)roots.elementAt(i);
  4645. for(Component p = root.getParent(); p != null; p = p.getParent()) {
  4646. if (p == c) {
  4647. roots.removeElementAt(i--); // !!
  4648. break;
  4649. }
  4650. }
  4651. }
  4652. roots.addElement(c);
  4653. }
  4654. }
  4655. /**
  4656. * We use the <code>ObjectInputStream</code> "registerValidation"
  4657. * callback to update the UI for the entire tree of components
  4658. * after they've all been read in.
  4659. *
  4660. * @param s the <code>ObjectInputStream</code> from which to read
  4661. * @see ReadObjectCallback
  4662. */
  4663. private void readObject(ObjectInputStream s)
  4664. throws IOException, ClassNotFoundException
  4665. {
  4666. s.defaultReadObject();
  4667. /* If there's no ReadObjectCallback for this stream yet, that is, if
  4668. * this is the first call to JComponent.readObject() for this
  4669. * graph of objects, then create a callback and stash it
  4670. * in the readObjectCallbacks table. Note that the ReadObjectCallback
  4671. * constructor takes care of calling s.registerValidation().
  4672. */
  4673. ReadObjectCallback cb = (ReadObjectCallback)(readObjectCallbacks.get(s));
  4674. if (cb == null) {
  4675. try {
  4676. readObjectCallbacks.put(s, cb = new ReadObjectCallback(s));
  4677. }
  4678. catch (Exception e) {
  4679. throw new IOException(e.toString());
  4680. }
  4681. }
  4682. cb.registerComponent(this);
  4683. if (getToolTipText() != null) {
  4684. ToolTipManager.sharedInstance().registerComponent(this);
  4685. }
  4686. setWriteObjCounter(this, (byte)0);
  4687. }
  4688. /**
  4689. * Before writing a <code>JComponent</code> to an
  4690. * <code>ObjectOutputStream</code> we temporarily uninstall its UI.
  4691. * This is tricky to do because we want to uninstall
  4692. * the UI before any of the <code>JComponent</code>'s children
  4693. * (or its <code>LayoutManager</code> etc.) are written,
  4694. * and we don't want to restore the UI until the most derived
  4695. * <code>JComponent</code> subclass has been been stored.
  4696. *
  4697. * @param s the <code>ObjectOutputStream</code> in which to write
  4698. */
  4699. private void writeObject(ObjectOutputStream s) throws IOException {
  4700. s.defaultWriteObject();
  4701. if (getUIClassID().equals(uiClassID)) {
  4702. byte count = JComponent.getWriteObjCounter(this);
  4703. JComponent.setWriteObjCounter(this, --count);
  4704. if (count == 0 && ui != null) {
  4705. ui.installUI(this);
  4706. }
  4707. }
  4708. }
  4709. /**
  4710. * Returns a string representation of this <code>JComponent</code>.
  4711. * This method
  4712. * is intended to be used only for debugging purposes, and the
  4713. * content and format of the returned string may vary between
  4714. * implementations. The returned string may be empty but may not
  4715. * be <code>null</code>.
  4716. *
  4717. * @return a string representation of this <code>JComponent</code>
  4718. */
  4719. protected String paramString() {
  4720. String preferredSizeString = (preferredSize != null ?
  4721. preferredSize.toString() : "");
  4722. String minimumSizeString = (minimumSize != null ?
  4723. minimumSize.toString() : "");
  4724. String maximumSizeString = (maximumSize != null ?
  4725. maximumSize.toString() : "");
  4726. String borderString = (border != null ?
  4727. border.toString() : "");
  4728. return super.paramString() +
  4729. ",alignmentX=" + alignmentX +
  4730. ",alignmentY=" + alignmentY +
  4731. ",border=" + borderString +
  4732. ",flags=" + flags + // should beef this up a bit
  4733. ",maximumSize=" + maximumSizeString +
  4734. ",minimumSize=" + minimumSizeString +
  4735. ",preferredSize=" + preferredSizeString;
  4736. }
  4737. }