1. /*
  2. * @(#)JTree.java 1.135 00/04/06
  3. *
  4. * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
  5. *
  6. * This software is the proprietary information of Sun Microsystems, Inc.
  7. * Use is subject to license terms.
  8. *
  9. */
  10. package javax.swing;
  11. import java.awt.*;
  12. import java.awt.event.*;
  13. import java.beans.*;
  14. import java.io.*;
  15. import java.util.*;
  16. import javax.swing.event.*;
  17. import javax.swing.plaf.TreeUI;
  18. import javax.swing.tree.*;
  19. import javax.accessibility.*;
  20. /**
  21. * <a name="jtree_description">
  22. * A control that displays a set of hierarchical data as an outline.
  23. * You can find task-oriented documentation and examples of using trees in
  24. * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html">How to Use Trees</a>,
  25. * a section in <em>The Java Tutorial.</em>
  26. * <p>
  27. * A specific node in a tree can be identified either by a
  28. * <code>TreePath</code> (an object
  29. * that encapsulates a node and all of its ancestors), or by its
  30. * display row, where each row in the display area displays one node.
  31. * An <i>expanded</i> node is one displays its children. A <i>collapsed</i>
  32. * node is one which hides them. A <i>hidden</i> node is one which is
  33. * under a collapsed ancestor. All of a <i>viewable</i> nodes parents
  34. * are expanded, but may or may not be displayed. A <i>displayed</i> node
  35. * is both viewable and in the display area, where it can be seen.
  36. * <p>
  37. * The following <code>JTree</code> methods use "visible" to mean "displayed":
  38. * <ul>
  39. * <li><code>isRootVisible()</code>
  40. * <li><code>setRootVisible()</code>
  41. * <li><code>scrollPathToVisible()</code>
  42. * <li><code>scrollRowToVisible()</code>
  43. * <li><code>getVisibleRowCount()</code>
  44. * <li><code>setVisibleRowCount()</code>
  45. * </ul>
  46. * <p>
  47. * The next group of <code>JTree</code> methods use "visible" to mean
  48. * "viewable" (under an expanded parent):
  49. * <ul>
  50. * <li><code>isVisible()</code>
  51. * <li><code>makeVisible()</code>
  52. * </ul>
  53. * <p>
  54. * If you are interested in knowing when the selection changes implement
  55. * the <code>TreeSelectionListener</code> interface and add the instance
  56. * using the method <code>addTreeSelectionListener</code>.
  57. * <code>valueChanged</code> will be invoked when the
  58. * selection changes, that is if the user clicks twice on the same
  59. * node <code>valueChanged</code> will only be invoked once.
  60. * <p>
  61. * If you are interested in detecting either double-click events or when
  62. * a user clicks on a node, regardless of whether or not it was selected,
  63. * we recommend you do the following:
  64. * <pre>
  65. * final JTree tree = ...;
  66. *
  67. * MouseListener ml = new MouseAdapter() {
  68. * public void <b>mousePressed</b>(MouseEvent e) {
  69. * int selRow = tree.getRowForLocation(e.getX(), e.getY());
  70. * TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
  71. * if(selRow != -1) {
  72. * if(e.getClickCount() == 1) {
  73. * mySingleClick(selRow, selPath);
  74. * }
  75. * else if(e.getClickCount() == 2) {
  76. * myDoubleClick(selRow, selPath);
  77. * }
  78. * }
  79. * }
  80. * };
  81. * tree.addMouseListener(ml);
  82. * </pre>
  83. * NOTE: This example obtains both the path and row, but you only need to
  84. * get the one you're interested in.
  85. * <p>
  86. * To use <code>JTree</code> to display compound nodes
  87. * (for example, nodes containing both
  88. * a graphic icon and text), subclass {@link TreeCellRenderer} and use
  89. * {@link #setCellRenderer} to tell the tree to use it. To edit such nodes,
  90. * subclass {@link TreeCellEditor} and use {@link #setCellEditor}.
  91. * <p>
  92. * Like all <code>JComponent</code> classes, you can use {@link InputMap} and
  93. * {@link ActionMap}
  94. * to associate an {@link Action} object with a {@link KeyStroke}
  95. * and execute the action under specified conditions.
  96. * <p>
  97. * For the keyboard keys used by this component in the standard Look and
  98. * Feel (L&F) renditions, see the
  99. * <a href="doc-files/Key-Index.html#JTree">JTree</a> key assignments.
  100. * <p>
  101. * <strong>Warning:</strong>
  102. * Serialized objects of this class will not be compatible with
  103. * future Swing releases. The current serialization support is appropriate
  104. * for short term storage or RMI between applications running the same
  105. * version of Swing. A future release of Swing will provide support for
  106. * long term persistence.
  107. *
  108. * @beaninfo
  109. * attribute: isContainer false
  110. * description: A component that displays a set of hierarchical data as an outline.
  111. *
  112. * @version $I% 04/06/00
  113. * @author Rob Davis
  114. * @author Ray Ryan
  115. * @author Scott Violet
  116. */
  117. public class JTree extends JComponent implements Scrollable, Accessible
  118. {
  119. /**
  120. * @see #getUIClassID
  121. * @see #readObject
  122. */
  123. private static final String uiClassID = "TreeUI";
  124. /**
  125. * The model that defines the tree displayed by this object.
  126. */
  127. transient protected TreeModel treeModel;
  128. /**
  129. * Models the set of selected nodes in this tree.
  130. */
  131. transient protected TreeSelectionModel selectionModel;
  132. /**
  133. * True if the root node is displayed, false if its children are
  134. * the highest visible nodes.
  135. */
  136. protected boolean rootVisible;
  137. /**
  138. * The cell used to draw nodes. If <code>null</code>, the UI uses a default
  139. * <code>cellRenderer</code>.
  140. */
  141. transient protected TreeCellRenderer cellRenderer;
  142. /**
  143. * Height to use for each display row. If this is <= 0 the renderer
  144. * determines the height for each row.
  145. */
  146. protected int rowHeight;
  147. /**
  148. * Maps from <code>TreePath</code> to <code>Boolean</code>
  149. * indicating whether or not the
  150. * particular path is expanded. This ONLY indicates whether a
  151. * given path is expanded, and NOT if it is visible or not. That
  152. * information must be determined by visiting all the parent
  153. * paths and seeing if they are visible.
  154. */
  155. transient private Hashtable expandedState;
  156. /**
  157. * True if handles are displayed at the topmost level of the tree.
  158. * <p>
  159. * A handle is a small icon that displays adjacent to the node which
  160. * allows the user to click once to expand or collapse the node. A
  161. * common interface shows a plus sign (+) for a node which can be
  162. * expanded and a minus sign (-) for a node which can be collapsed.
  163. * Handles are always shown for nodes below the topmost level.
  164. * <p>
  165. * If the <code>rootVisible</code> setting specifies that the root
  166. * node is to be displayed, then that is the only node at the topmost
  167. * level. If the root node is not displayed, then all of its
  168. * children are at the topmost level of the tree. Handles are
  169. * always displayed for nodes other than the topmost.
  170. * <p>
  171. * If the root node isn't visible, it is generally a good to make
  172. * this value true. Otherwise, the tree looks exactly like a list,
  173. * and users may not know that the "list entries" are actually
  174. * tree nodes.
  175. *
  176. * @see #rootVisible
  177. */
  178. protected boolean showsRootHandles;
  179. /**
  180. * Creates a new event and passed it off the
  181. * <code>selectionListeners</code>.
  182. */
  183. protected transient TreeSelectionRedirector selectionRedirector;
  184. /**
  185. * Editor for the entries. Default is <code>null</code>
  186. * (tree is not editable).
  187. */
  188. transient protected TreeCellEditor cellEditor;
  189. /**
  190. * Is the tree editable? Default is false.
  191. */
  192. protected boolean editable;
  193. /**
  194. * Is this tree a large model? This is a code-optimization setting.
  195. * A large model can be used when the cell height is the same for all
  196. * nodes. The UI will then cache very little information and instead
  197. * continually message the model. Without a large model the UI caches
  198. * most of the information, resulting in fewer method calls to the model.
  199. * <p>
  200. * This value is only a suggestion to the UI. Not all UIs will
  201. * take advantage of it. Default value is false.
  202. */
  203. protected boolean largeModel;
  204. /**
  205. * Number of rows to make visible at one time. This value is used for
  206. * the <code>Scrollable</code> interface. It determines the preferred
  207. * size of the display area.
  208. */
  209. protected int visibleRowCount;
  210. /**
  211. * If true, when editing is to be stopped by way of selection changing,
  212. * data in tree changing or other means <code>stopCellEditing</code>
  213. * is invoked, and changes are saved. If false,
  214. * <code>cancelCellEditing</code> is invoked, and changes
  215. * are discarded. Default is false.
  216. */
  217. protected boolean invokesStopCellEditing;
  218. /**
  219. * If true, when a node is expanded, as many of the descendants are
  220. * scrolled to be visible.
  221. */
  222. protected boolean scrollsOnExpand;
  223. /**
  224. * Number of mouse clicks before a node is expanded.
  225. */
  226. protected int toggleClickCount;
  227. /**
  228. * Updates the <code>expandedState</code>.
  229. */
  230. transient protected TreeModelListener treeModelListener;
  231. /**
  232. * Used when <code>setExpandedState</code> is invoked,
  233. * will be a <code>Stack</code> of <code>Stack</code>s.
  234. */
  235. transient private Stack expandedStack;
  236. /**
  237. * Lead selection path, may not be <code>null</code>.
  238. */
  239. private TreePath leadPath;
  240. /**
  241. * Anchor path.
  242. */
  243. private TreePath anchorPath;
  244. /**
  245. * True if paths in the selection should be expanded.
  246. */
  247. private boolean expandsSelectedPaths;
  248. /**
  249. * This is set to true for the life of the setUI call.
  250. */
  251. private boolean settingUI;
  252. /**
  253. * When <code>addTreeExpansionListener</code> is invoked,
  254. * and settingUI is true, this ivar gets set to the passed in
  255. * <code>Listener</code>. This listener is then notified first in
  256. * <code>fireTreeCollapsed</code> and <code>fireTreeExpanded</code>.
  257. * <p>This is an ugly workaround for a way to have the UI listener
  258. * get notified before other listeners.
  259. */
  260. private transient TreeExpansionListener uiTreeExpansionListener;
  261. /**
  262. * Max number of stacks to keep around.
  263. */
  264. private static int TEMP_STACK_SIZE = 11;
  265. //
  266. // Bound propery names
  267. //
  268. /** Bound property name for <code>cellRenderer</code>. */
  269. public final static String CELL_RENDERER_PROPERTY = "cellRenderer";
  270. /** Bound property name for <code>treeModel</code>. */
  271. public final static String TREE_MODEL_PROPERTY = "model";
  272. /** Bound property name for <code>rootVisible</code>. */
  273. public final static String ROOT_VISIBLE_PROPERTY = "rootVisible";
  274. /** Bound property name for <code>showsRootHandles</code>. */
  275. public final static String SHOWS_ROOT_HANDLES_PROPERTY = "showsRootHandles";
  276. /** Bound property name for <code>rowHeight</code>. */
  277. public final static String ROW_HEIGHT_PROPERTY = "rowHeight";
  278. /** Bound property name for <code>cellEditor</code>. */
  279. public final static String CELL_EDITOR_PROPERTY = "cellEditor";
  280. /** Bound property name for <code>editable</code>. */
  281. public final static String EDITABLE_PROPERTY = "editable";
  282. /** Bound property name for <code>largeModel</code>. */
  283. public final static String LARGE_MODEL_PROPERTY = "largeModel";
  284. /** Bound property name for selectionModel. */
  285. public final static String SELECTION_MODEL_PROPERTY = "selectionModel";
  286. /** Bound property name for <code>visibleRowCount</code>. */
  287. public final static String VISIBLE_ROW_COUNT_PROPERTY = "visibleRowCount";
  288. /** Bound property name for <code>messagesStopCellEditing</code>. */
  289. public final static String INVOKES_STOP_CELL_EDITING_PROPERTY = "invokesStopCellEditing";
  290. /** Bound property name for <code>scrollsOnExpand</code>. */
  291. public final static String SCROLLS_ON_EXPAND_PROPERTY = "scrollsOnExpand";
  292. /** Bound property name for <code>toggleClickCount</code>. */
  293. public final static String TOGGLE_CLICK_COUNT_PROPERTY = "toggleClickCount";
  294. /** Bound property name for <code>leadSelectionPath</code>.
  295. * @since 1.3 */
  296. public final static String LEAD_SELECTION_PATH_PROPERTY = "leadSelectionPath";
  297. /** Bound property name for anchor selection path.
  298. * @since 1.3 */
  299. public final static String ANCHOR_SELECTION_PATH_PROPERTY = "anchorSelectionPath";
  300. /** Bound property name for expands selected paths property
  301. * @since 1.3 */
  302. public final static String EXPANDS_SELECTED_PATHS_PROPERTY = "expandsSelectedPaths";
  303. /**
  304. * Creates and returns a sample <code>TreeModel</code>.
  305. * Used primarily for beanbuilders to show something interesting.
  306. *
  307. * @return the default <code>TreeModel</code>
  308. */
  309. protected static TreeModel getDefaultTreeModel() {
  310. DefaultMutableTreeNode root = new DefaultMutableTreeNode("JTree");
  311. DefaultMutableTreeNode parent;
  312. parent = new DefaultMutableTreeNode("colors");
  313. root.add(parent);
  314. parent.add(new DefaultMutableTreeNode("blue"));
  315. parent.add(new DefaultMutableTreeNode("violet"));
  316. parent.add(new DefaultMutableTreeNode("red"));
  317. parent.add(new DefaultMutableTreeNode("yellow"));
  318. parent = new DefaultMutableTreeNode("sports");
  319. root.add(parent);
  320. parent.add(new DefaultMutableTreeNode("basketball"));
  321. parent.add(new DefaultMutableTreeNode("soccer"));
  322. parent.add(new DefaultMutableTreeNode("football"));
  323. parent.add(new DefaultMutableTreeNode("hockey"));
  324. parent = new DefaultMutableTreeNode("food");
  325. root.add(parent);
  326. parent.add(new DefaultMutableTreeNode("hot dogs"));
  327. parent.add(new DefaultMutableTreeNode("pizza"));
  328. parent.add(new DefaultMutableTreeNode("ravioli"));
  329. parent.add(new DefaultMutableTreeNode("bananas"));
  330. return new DefaultTreeModel(root);
  331. }
  332. /**
  333. * Returns a <code>TreeModel</code> wrapping the specified object.
  334. * If the object
  335. * is:<ul>
  336. * <li>an array of <code>Object</code>s,
  337. * <li>a <code>Hashtable</code>, or
  338. * <li>a <code>Vector</code>
  339. * </ul>then a new root node is created with each of the incoming
  340. * objects as children. Otherwise, a new root is created with the
  341. * specified object as its value.
  342. *
  343. * @param value the <code>Object</code> used as the foundation for
  344. * the <code>TreeModel</code>
  345. * @return a <code>TreeModel</code> wrapping the specified object
  346. */
  347. protected static TreeModel createTreeModel(Object value) {
  348. DefaultMutableTreeNode root;
  349. if((value instanceof Object[]) || (value instanceof Hashtable) ||
  350. (value instanceof Vector)) {
  351. root = new DefaultMutableTreeNode("root");
  352. DynamicUtilTreeNode.createChildren(root, value);
  353. }
  354. else {
  355. root = new DynamicUtilTreeNode("root", value);
  356. }
  357. return new DefaultTreeModel(root, false);
  358. }
  359. /**
  360. * Returns a <code>JTree</code> with a sample model.
  361. * The default model used by the tree defines a leaf node as any node
  362. * without children.
  363. *
  364. * @return a <code>JTree</code> with the default model,
  365. * which defines a leaf node as any node without children.
  366. * @see DefaultTreeModel#asksAllowsChildren
  367. */
  368. public JTree() {
  369. this(getDefaultTreeModel());
  370. }
  371. /**
  372. * Returns a <code>JTree</code> with each element of the
  373. * specified array as the
  374. * child of a new root node which is not displayed.
  375. * By default, the tree defines a leaf node as any node without
  376. * children.
  377. *
  378. * @param value an array of <code>Object</code>s
  379. * @return a <code>JTree</code> with the contents of the array as
  380. * children of the root node
  381. * @see DefaultTreeModel#asksAllowsChildren
  382. */
  383. public JTree(Object[] value) {
  384. this(createTreeModel(value));
  385. this.setRootVisible(false);
  386. this.setShowsRootHandles(true);
  387. }
  388. /**
  389. * Returns a <code>JTree</code> with each element of the specified
  390. * <code>Vector</code> as the
  391. * child of a new root node which is not displayed. By default, the
  392. * tree defines a leaf node as any node without children.
  393. *
  394. * @param value a <code>Vector</code>
  395. * @return a <code>JTree</code> with the contents of the
  396. * <code>Vector</code> as children of the root node
  397. * @see DefaultTreeModel#asksAllowsChildren
  398. */
  399. public JTree(Vector value) {
  400. this(createTreeModel(value));
  401. this.setRootVisible(false);
  402. this.setShowsRootHandles(true);
  403. }
  404. /**
  405. * Returns a <code>JTree</code> created from a <code>Hashtable</code>
  406. * which does not display with root.
  407. * Each value-half of the key/value pairs in the <code>HashTable</code>
  408. * becomes a child of the new root node. By default, the tree defines
  409. * a leaf node as any node without children.
  410. *
  411. * @param value a <code>Hashtable</code>
  412. * @return a <code>JTree</code> with the contents of the
  413. * <code>Hashtable</code> as children of the root node
  414. * @see DefaultTreeModel#asksAllowsChildren
  415. */
  416. public JTree(Hashtable value) {
  417. this(createTreeModel(value));
  418. this.setRootVisible(false);
  419. this.setShowsRootHandles(true);
  420. }
  421. /**
  422. * Returns a <code>JTree</code> with the specified TreeNode as its root,
  423. * which displays the root node.
  424. * By default, the tree defines a leaf node as any node without children.
  425. *
  426. * @param root a <code>TreeNode</code> object
  427. * @return a <code>JTree</code> with the specified root node
  428. * @see DefaultTreeModel#asksAllowsChildren
  429. */
  430. public JTree(TreeNode root) {
  431. this(root, false);
  432. }
  433. /**
  434. * Returns a <code>JTree</code> with the specified <code>TreeNode</code>
  435. * as its root, which
  436. * displays the root node and which decides whether a node is a
  437. * leaf node in the specified manner.
  438. *
  439. * @param root a <code>TreeNode</code> object
  440. * @param asksAllowsChildren if false, any node without children is a
  441. * leaf node; if true, only nodes that do not allow
  442. * children are leaf nodes
  443. * @return a <code>JTree</code> with the specified root node
  444. * @see DefaultTreeModel#asksAllowsChildren
  445. */
  446. public JTree(TreeNode root, boolean asksAllowsChildren) {
  447. this(new DefaultTreeModel(root, asksAllowsChildren));
  448. }
  449. /**
  450. * Returns an instance of <code>JTree</code> which displays the root node
  451. * -- the tree is created using the specified data model.
  452. *
  453. * @param newModel the <code>TreeModel</code> to use as the data model
  454. * @return a <code>JTree</code> based on the <code>TreeModel</code>
  455. */
  456. public JTree(TreeModel newModel) {
  457. super();
  458. expandedStack = new Stack();
  459. toggleClickCount = 2;
  460. expandedState = new Hashtable();
  461. setLayout(null);
  462. rowHeight = 16;
  463. visibleRowCount = 20;
  464. rootVisible = true;
  465. selectionModel = new DefaultTreeSelectionModel();
  466. cellRenderer = null;
  467. scrollsOnExpand = true;
  468. setOpaque(true);
  469. expandsSelectedPaths = true;
  470. updateUI();
  471. setModel(newModel);
  472. }
  473. /**
  474. * Returns the L&F object that renders this component.
  475. *
  476. * @return the TreeUI object that renders this component
  477. */
  478. public TreeUI getUI() {
  479. return (TreeUI)ui;
  480. }
  481. /**
  482. * Sets the L&F object that renders this component.
  483. *
  484. * @param ui the TreeUI L&F object
  485. * @see UIDefaults#getUI
  486. */
  487. public void setUI(TreeUI ui) {
  488. if ((TreeUI)this.ui != ui) {
  489. settingUI = true;
  490. uiTreeExpansionListener = null;
  491. try {
  492. super.setUI(ui);
  493. }
  494. finally {
  495. settingUI = false;
  496. }
  497. }
  498. }
  499. /**
  500. * Notification from the <code>UIManager</code> that the L&F has changed.
  501. * Replaces the current UI object with the latest version from the
  502. * <code>UIManager</code>.
  503. *
  504. * @see JComponent#updateUI
  505. */
  506. public void updateUI() {
  507. setUI((TreeUI)UIManager.getUI(this));
  508. invalidate();
  509. }
  510. /**
  511. * Returns the name of the L&F class that renders this component.
  512. *
  513. * @return the string "TreeUI"
  514. * @see JComponent#getUIClassID
  515. * @see UIDefaults#getUI
  516. */
  517. public String getUIClassID() {
  518. return uiClassID;
  519. }
  520. /**
  521. * Returns the current <code>TreeCellRenderer</code>
  522. * that is rendering each cell.
  523. *
  524. * @return the <code>TreeCellRenderer</code> that is rendering each cell
  525. */
  526. public TreeCellRenderer getCellRenderer() {
  527. return cellRenderer;
  528. }
  529. /**
  530. * Sets the <code>TreeCellRenderer</code> that will be used to
  531. * draw each cell.
  532. *
  533. * @param x the <code>TreeCellRenderer</code> that is to render each cell
  534. * @beaninfo
  535. * bound: true
  536. * description: The TreeCellRenderer that will be used to draw
  537. * each cell.
  538. */
  539. public void setCellRenderer(TreeCellRenderer x) {
  540. TreeCellRenderer oldValue = cellRenderer;
  541. cellRenderer = x;
  542. firePropertyChange(CELL_RENDERER_PROPERTY, oldValue, cellRenderer);
  543. invalidate();
  544. }
  545. /**
  546. * Determines whether the tree is editable. Fires a property
  547. * change event if the new setting is different from the existing
  548. * setting.
  549. *
  550. * @param flag a boolean value, true if the tree is editable
  551. * @beaninfo
  552. * bound: true
  553. * description: Whether the tree is editable.
  554. */
  555. public void setEditable(boolean flag) {
  556. boolean oldValue = this.editable;
  557. this.editable = flag;
  558. firePropertyChange(EDITABLE_PROPERTY, oldValue, flag);
  559. if (accessibleContext != null) {
  560. accessibleContext.firePropertyChange(
  561. AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  562. (oldValue ? AccessibleState.EDITABLE : null),
  563. (flag ? AccessibleState.EDITABLE : null));
  564. }
  565. }
  566. /**
  567. * Returns true if the tree is editable.
  568. *
  569. * @return true if the tree is editable
  570. */
  571. public boolean isEditable() {
  572. return editable;
  573. }
  574. /**
  575. * Sets the cell editor. A <code>null</code> value implies that the
  576. * tree cannot be edited. If this represents a change in the
  577. * <code>cellEditor</code>, the <code>propertyChange</code>
  578. * method is invoked on all listeners.
  579. *
  580. * @param cellEditor the <code>TreeCellEditor</code> to use
  581. * @beaninfo
  582. * bound: true
  583. * description: The cell editor. A null value implies the tree
  584. * cannot be edited.
  585. */
  586. public void setCellEditor(TreeCellEditor cellEditor) {
  587. TreeCellEditor oldEditor = this.cellEditor;
  588. this.cellEditor = cellEditor;
  589. firePropertyChange(CELL_EDITOR_PROPERTY, oldEditor, cellEditor);
  590. invalidate();
  591. }
  592. /**
  593. * Returns the editor used to edit entries in the tree.
  594. *
  595. * @return the <code>TreeCellEditor</code> in use,
  596. * or <code>null</code> if the tree cannot be edited
  597. */
  598. public TreeCellEditor getCellEditor() {
  599. return cellEditor;
  600. }
  601. /**
  602. * Returns the <code>TreeModel</code> that is providing the data.
  603. *
  604. * @return the <code>TreeModel</code> that is providing the data
  605. */
  606. public TreeModel getModel() {
  607. return treeModel;
  608. }
  609. /**
  610. * Sets the <code>TreeModel</code> that will provide the data.
  611. *
  612. * @param newModel the <code>TreeModel</code> that is to provide the data
  613. * @beaninfo
  614. * bound: true
  615. * description: The TreeModel that will provide the data.
  616. */
  617. public void setModel(TreeModel newModel) {
  618. TreeModel oldModel = treeModel;
  619. if(treeModel != null && treeModelListener != null)
  620. treeModel.removeTreeModelListener(treeModelListener);
  621. if (accessibleContext != null) {
  622. if (treeModel != null) {
  623. treeModel.removeTreeModelListener((TreeModelListener)accessibleContext);
  624. }
  625. if (newModel != null) {
  626. newModel.addTreeModelListener((TreeModelListener)accessibleContext);
  627. }
  628. }
  629. treeModel = newModel;
  630. clearToggledPaths();
  631. if(treeModel != null) {
  632. if(treeModelListener == null)
  633. treeModelListener = createTreeModelListener();
  634. if(treeModelListener != null)
  635. treeModel.addTreeModelListener(treeModelListener);
  636. // Mark the root as expanded, if it isn't a leaf.
  637. if(!treeModel.isLeaf(treeModel.getRoot()))
  638. expandedState.put(new TreePath(treeModel.getRoot()),
  639. Boolean.TRUE);
  640. }
  641. firePropertyChange(TREE_MODEL_PROPERTY, oldModel, treeModel);
  642. invalidate();
  643. }
  644. /**
  645. * Returns true if the root node of the tree is displayed.
  646. *
  647. * @return true if the root node of the tree is displayed
  648. * @see #rootVisible
  649. */
  650. public boolean isRootVisible() {
  651. return rootVisible;
  652. }
  653. /**
  654. * Determines whether or not the root node from
  655. * the <code>TreeModel</code> is visible.
  656. *
  657. * @param rootVisible true if the root node of the tree is to be displayed
  658. * @see #rootVisible
  659. * @beaninfo
  660. * bound: true
  661. * description: Whether or not the root node
  662. * from the TreeModel is visible.
  663. */
  664. public void setRootVisible(boolean rootVisible) {
  665. boolean oldValue = this.rootVisible;
  666. this.rootVisible = rootVisible;
  667. firePropertyChange(ROOT_VISIBLE_PROPERTY, oldValue, this.rootVisible);
  668. if (accessibleContext != null) {
  669. ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
  670. }
  671. }
  672. /**
  673. * Determines whether the node handles are to be displayed.
  674. *
  675. * @param newValue true if root handles are to be displayed
  676. * @see #showsRootHandles
  677. * @beaninfo
  678. * bound: true
  679. * description: Whether the node handles are to be
  680. * displayed.
  681. */
  682. public void setShowsRootHandles(boolean newValue) {
  683. boolean oldValue = showsRootHandles;
  684. TreeModel model = getModel();
  685. showsRootHandles = newValue;
  686. firePropertyChange(SHOWS_ROOT_HANDLES_PROPERTY, oldValue,
  687. showsRootHandles);
  688. if (accessibleContext != null) {
  689. ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
  690. }
  691. // Make SURE the root is expanded
  692. if(model != null) {
  693. expandPath(new TreePath(model.getRoot()));
  694. }
  695. invalidate();
  696. }
  697. /**
  698. * Returns true if handles for the root nodes are displayed.
  699. *
  700. * @return true if root handles are displayed
  701. * @see #showsRootHandles
  702. */
  703. public boolean getShowsRootHandles()
  704. {
  705. return showsRootHandles;
  706. }
  707. /**
  708. * Sets the height of each cell, in pixels. If the specified value
  709. * is less than or equal to zero the current cell renderer is
  710. * queried for each row's height.
  711. *
  712. * @param rowHeight the height of each cell, in pixels
  713. * @beaninfo
  714. * bound: true
  715. * description: The height of each cell.
  716. */
  717. public void setRowHeight(int rowHeight)
  718. {
  719. int oldValue = this.rowHeight;
  720. this.rowHeight = rowHeight;
  721. firePropertyChange(ROW_HEIGHT_PROPERTY, oldValue, this.rowHeight);
  722. invalidate();
  723. }
  724. /**
  725. * Returns the height of each row. If the returned value is less than
  726. * or equal to 0 the height for each row is determined by the
  727. * renderer.
  728. *
  729. * @param the height of each cell, in pixels; zero or negative if the
  730. * height of each row is determined by the tree cell renderer
  731. */
  732. public int getRowHeight()
  733. {
  734. return rowHeight;
  735. }
  736. /**
  737. * Returns true if the height of each display row is a fixed size.
  738. *
  739. * @return true if the height of each row is a fixed size
  740. */
  741. public boolean isFixedRowHeight()
  742. {
  743. return (rowHeight > 0);
  744. }
  745. /**
  746. * Specifies whether the UI should use a large model.
  747. * (Not all UIs will implement this.) Fires a property change
  748. * for the LARGE_MODEL_PROPERTY.
  749. *
  750. * @param newValue true to suggest a large model to the UI
  751. * @see #largeModel
  752. * @beaninfo
  753. * bound: true
  754. * description: Whether the UI should use a
  755. * large model.
  756. */
  757. public void setLargeModel(boolean newValue) {
  758. boolean oldValue = largeModel;
  759. largeModel = newValue;
  760. firePropertyChange(LARGE_MODEL_PROPERTY, oldValue, newValue);
  761. }
  762. /**
  763. * Returns true if the tree is configured for a large model.
  764. *
  765. * @return true if a large model is suggested
  766. * @see #largeModel
  767. */
  768. public boolean isLargeModel() {
  769. return largeModel;
  770. }
  771. /**
  772. * Determines what happens when editing is interrupted by selecting
  773. * another node in the tree, a change in the tree's data, or by some
  774. * other means. Setting this property to <code>true</code> causes the
  775. * changes to be automatically saved when editing is interrupted.
  776. * <p>
  777. * Fires a property change for the INVOKES_STOP_CELL_EDITING_PROPERTY.
  778. *
  779. * @param newValue true means that <code>stopCellEditing</code> is invoked
  780. * when editing is interruped, and data is saved; false means that
  781. * <code>cancelCellEditing</code> is invoked, and changes are lost
  782. * @beaninfo
  783. * bound: true
  784. * description: Determines what happens when editing is interrupted,
  785. * selecting another node in the tree, a change in the
  786. * tree's data, or some other means.
  787. */
  788. public void setInvokesStopCellEditing(boolean newValue) {
  789. boolean oldValue = invokesStopCellEditing;
  790. invokesStopCellEditing = newValue;
  791. firePropertyChange(INVOKES_STOP_CELL_EDITING_PROPERTY, oldValue,
  792. newValue);
  793. }
  794. /**
  795. * Returns the indicator that tells what happens when editing is
  796. * interrupted.
  797. *
  798. * @return the indicator that tells what happens when editing is
  799. * interrupted
  800. * @see #setInvokesStopCellEditing
  801. */
  802. public boolean getInvokesStopCellEditing() {
  803. return invokesStopCellEditing;
  804. }
  805. /**
  806. * Determines whether or not when a node is expanded, as many of
  807. * the descendants are scrolled to be inside the viewport as
  808. * possible. The default is true.
  809. * @beaninfo
  810. * bound: true
  811. * description: Indicates if a node descendent should be scrolled when expanded.
  812. */
  813. public void setScrollsOnExpand(boolean newValue) {
  814. boolean oldValue = scrollsOnExpand;
  815. scrollsOnExpand = newValue;
  816. firePropertyChange(SCROLLS_ON_EXPAND_PROPERTY, oldValue,
  817. newValue);
  818. }
  819. /**
  820. * Returns true if the tree scrolls to show previously hidden children.
  821. *
  822. * @return true if when a node is expanded as many of the descendants
  823. * as possible are scrolled to be visible
  824. */
  825. public boolean getScrollsOnExpand() {
  826. return scrollsOnExpand;
  827. }
  828. /**
  829. * Sets the number of mouse clicks before a node will expand or close.
  830. * The default is two.
  831. *
  832. * @since 1.3
  833. * @beaninfo
  834. * bound: true
  835. * description: Number of clicks before a node will expand/collapse.
  836. */
  837. public void setToggleClickCount(int clickCount) {
  838. int oldCount = toggleClickCount;
  839. toggleClickCount = clickCount;
  840. firePropertyChange(TOGGLE_CLICK_COUNT_PROPERTY, oldCount,
  841. clickCount);
  842. }
  843. /**
  844. * Returns the number of mouse clicks needed to expand or close a node.
  845. *
  846. * @return number of mouse clicks before node is expanded
  847. * @since 1.3
  848. */
  849. public int getToggleClickCount() {
  850. return toggleClickCount;
  851. }
  852. /**
  853. * Configures the <code>expandsSelectedPaths</code> property. If
  854. * true, any time the selection is changed, either via the
  855. * <code>TreeSelectionModel</code>, or the cover methods provided by
  856. * <code>JTree</code>, the <code>TreePath</code>s parents will be
  857. * expanded to make them visible (visible meaning the parent path is
  858. * expanded, not necessarily in the visible rectangle of the
  859. * <code>JTree</code>). If false, when the selection
  860. * changes the nodes parent is not made visible (all its parents expanded).
  861. * This is useful if you wish to have your selection model maintain paths
  862. * that are not always visible (all parents expanded).
  863. *
  864. * @param newValue the new value for <code>expandsSelectedPaths</code>
  865. *
  866. * @since 1.3
  867. * @beaninfo
  868. * bound: true
  869. * description: Indicates whether changes to the selection should make
  870. * the parent of the path visible.
  871. */
  872. public void setExpandsSelectedPaths(boolean newValue) {
  873. boolean oldValue = expandsSelectedPaths;
  874. expandsSelectedPaths = newValue;
  875. firePropertyChange(EXPANDS_SELECTED_PATHS_PROPERTY, oldValue,
  876. newValue);
  877. }
  878. /**
  879. * Returns the <code>expandsSelectedPaths</code> property.
  880. * @return true if selection changes result in the parent path being
  881. * expanded
  882. * @since 1.3
  883. * @see #setExpandsSelectedPaths
  884. */
  885. public boolean getExpandsSelectedPaths() {
  886. return expandsSelectedPaths;
  887. }
  888. /**
  889. * Returns <code>isEditable</code>. This is invoked from the UI before
  890. * editing begins to insure that the given path can be edited. This
  891. * is provided as an entry point for subclassers to add filtered
  892. * editing without having to resort to creating a new editor.
  893. *
  894. * @return true if every parent node and the node itself is editabled
  895. * @see #isEditable
  896. */
  897. public boolean isPathEditable(TreePath path) {
  898. return isEditable();
  899. }
  900. /**
  901. * Overrides <code>JComponent</code>'s <code>getToolTipText</code>
  902. * method in order to allow
  903. * renderer's tips to be used if it has text set.
  904. * <p>
  905. * NOTE: For <code>JTree</code> to properly display tooltips of its
  906. * renderers, <code>JTree</code> must be a registered component with the
  907. * <code>ToolTipManager</code>. This can be done by invoking
  908. * <code>ToolTipManager.sharedInstance().registerComponent(tree)</code>.
  909. * This is not done automatically!
  910. *
  911. * @param event the <code>MouseEvent</code> that initiated the
  912. * <code>ToolTip</code> display
  913. * @return a string containing the tooltip or <code>null</code>
  914. * if <code>event</code> is null
  915. */
  916. public String getToolTipText(MouseEvent event) {
  917. if(event != null) {
  918. Point p = event.getPoint();
  919. int selRow = getRowForLocation(p.x, p.y);
  920. TreeCellRenderer r = getCellRenderer();
  921. if(selRow != -1 && r != null) {
  922. TreePath path = getPathForRow(selRow);
  923. Object lastPath = path.getLastPathComponent();
  924. Component rComponent = r.getTreeCellRendererComponent
  925. (this, lastPath, isRowSelected(selRow),
  926. isExpanded(selRow), getModel().isLeaf(lastPath), selRow,
  927. true);
  928. if(rComponent instanceof JComponent) {
  929. MouseEvent newEvent;
  930. Rectangle pathBounds = getPathBounds(path);
  931. p.translate(-pathBounds.x, -pathBounds.y);
  932. newEvent = new MouseEvent(rComponent, event.getID(),
  933. event.getWhen(),
  934. event.getModifiers(),
  935. p.x, p.y, event.getClickCount(),
  936. event.isPopupTrigger());
  937. return ((JComponent)rComponent).getToolTipText(newEvent);
  938. }
  939. }
  940. }
  941. return null;
  942. }
  943. /**
  944. * Called by the renderers to convert the specified value to
  945. * text. This implementation returns <code>value.toString</code>, ignoring
  946. * all other arguments. To control the conversion, subclass this
  947. * method and use any of the arguments you need.
  948. *
  949. * @param value the <code>Object</code> to convert to text
  950. * @param selected true if the node is selected
  951. * @param expanded true if the node is expanded
  952. * @param leaf true if the node is a leaf node
  953. * @param row an integer specifying the node's display row, where 0 is
  954. * the first row in the display
  955. * @param hasFocus true if the node has the focus
  956. * @return the <code>String</code> representation of the node's value
  957. */
  958. public String convertValueToText(Object value, boolean selected,
  959. boolean expanded, boolean leaf, int row,
  960. boolean hasFocus) {
  961. if(value != null)
  962. return value.toString();
  963. return "";
  964. }
  965. //
  966. // The following are convenience methods that get forwarded to the
  967. // current TreeUI.
  968. //
  969. /**
  970. * Returns the number of rows that are currently being displayed.
  971. *
  972. * @return the number of rows that are being displayed
  973. */
  974. public int getRowCount() {
  975. TreeUI tree = getUI();
  976. if(tree != null)
  977. return tree.getRowCount(this);
  978. return 0;
  979. }
  980. /**
  981. * Selects the node identified by the specified path. If any
  982. * component of the path is hidden (under a collapsed node), and
  983. * <code>getExpandsSelectedPaths</code> is true it is
  984. * exposed (made viewable).
  985. *
  986. * @param path the <code>TreePath</code> specifying the node to select
  987. */
  988. public void setSelectionPath(TreePath path) {
  989. getSelectionModel().setSelectionPath(path);
  990. }
  991. /**
  992. * Selects the nodes identified by the specified array of paths.
  993. * If any component in any of the paths is hidden (under a collapsed
  994. * node), and <code>getExpandsSelectedPaths</code> is true
  995. * it is exposed (made viewable).
  996. *
  997. * @param paths an array of <code>TreePath</code> objects that specifies
  998. * the nodes to select
  999. */
  1000. public void setSelectionPaths(TreePath[] paths) {
  1001. getSelectionModel().setSelectionPaths(paths);
  1002. }
  1003. /**
  1004. * Sets the path identifies as the lead. The lead may not be selected.
  1005. * The lead is not maintained by <code>JTree</code>,
  1006. * rather the UI will update it.
  1007. *
  1008. * @param newPath the new lead path
  1009. * @since 1.3
  1010. * @beaninfo
  1011. * bound: true
  1012. * description: Lead selection path
  1013. */
  1014. public void setLeadSelectionPath(TreePath newPath) {
  1015. TreePath oldValue = leadPath;
  1016. leadPath = newPath;
  1017. firePropertyChange(LEAD_SELECTION_PATH_PROPERTY, oldValue, newPath);
  1018. }
  1019. /**
  1020. * Sets the path identified as the anchor.
  1021. * The anchor is not maintained by <code>JTree</code>, rather the UI will
  1022. * update it.
  1023. *
  1024. * @param newPath the new anchor path
  1025. * @since 1.3
  1026. * @beaninfo
  1027. * bound: true
  1028. * description: Anchor selection path
  1029. */
  1030. public void setAnchorSelectionPath(TreePath newPath) {
  1031. TreePath oldValue = anchorPath;
  1032. anchorPath = newPath;
  1033. firePropertyChange(ANCHOR_SELECTION_PATH_PROPERTY, oldValue, newPath);
  1034. }
  1035. /**
  1036. * Selects the node at the specified row in the display.
  1037. *
  1038. * @param row the row to select, where 0 is the first row in
  1039. * the display
  1040. */
  1041. public void setSelectionRow(int row) {
  1042. int[] rows = { row };
  1043. setSelectionRows(rows);
  1044. }
  1045. /**
  1046. * Selects the nodes corresponding to each of the specified rows
  1047. * in the display. If a particular element of <code>rows</code> is
  1048. * < 0 or >= <code>getRowCount</code>, it will be ignored.
  1049. * If none of the elements
  1050. * in <code>rows</code> are valid rows, the selection will
  1051. * be cleared. That is it will be as if <code>clearSelection</code>
  1052. * was invoked.
  1053. *
  1054. * @param rows an array of ints specifying the rows to select,
  1055. * where 0 indicates the first row in the display
  1056. */
  1057. public void setSelectionRows(int[] rows) {
  1058. TreeUI ui = getUI();
  1059. if(ui != null && rows != null) {
  1060. int numRows = rows.length;
  1061. TreePath[] paths = new TreePath[numRows];
  1062. for(int counter = 0; counter < numRows; counter++) {
  1063. paths[counter] = ui.getPathForRow(this, rows[counter]);
  1064. }
  1065. setSelectionPaths(paths);
  1066. }
  1067. }
  1068. /**
  1069. * Adds the node identified by the specified <code>TreePath</code>
  1070. * to the current
  1071. * selection. If any component of the path isn't viewable, and
  1072. * <code>getExpandsSelectedPaths</code>is true it is
  1073. * made viewable.
  1074. *
  1075. * @param path the <code>TreePath</code> to add
  1076. */
  1077. public void addSelectionPath(TreePath path) {
  1078. getSelectionModel().addSelectionPath(path);
  1079. }
  1080. /**
  1081. * Adds each path in the array of paths to the current selection. If
  1082. * any component of any of the paths isn't viewable and
  1083. * <code>getExpandsSelectedPaths</code> is true, it is
  1084. * made viewable.
  1085. *
  1086. * @param paths an array of <code>TreePath</code> objects that specifies
  1087. * the nodes to add
  1088. */
  1089. public void addSelectionPaths(TreePath[] paths) {
  1090. getSelectionModel().addSelectionPaths(paths);
  1091. }
  1092. /**
  1093. * Adds the path at the specified row to the current selection.
  1094. *
  1095. * @param row an integer specifying the row of the node to add,
  1096. * where 0 is the first row in the display
  1097. */
  1098. public void addSelectionRow(int row) {
  1099. int[] rows = { row };
  1100. addSelectionRows(rows);
  1101. }
  1102. /**
  1103. * Adds the paths at each of the specified rows to the current selection.
  1104. *
  1105. * @param rows an array of ints specifying the rows to add,
  1106. * where 0 indicates the first row in the display
  1107. */
  1108. public void addSelectionRows(int[] rows) {
  1109. TreeUI ui = getUI();
  1110. if(ui != null && rows != null) {
  1111. int numRows = rows.length;
  1112. TreePath[] paths = new TreePath[numRows];
  1113. for(int counter = 0; counter < numRows; counter++)
  1114. paths[counter] = ui.getPathForRow(this, rows[counter]);
  1115. addSelectionPaths(paths);
  1116. }
  1117. }
  1118. /**
  1119. * Returns the last path component in the first node of the current
  1120. * selection.
  1121. *
  1122. * @return the last <code>Object</code> in the first selected node's
  1123. * <code>TreePath</code>,
  1124. * or <code>null</code> if nothing is selected
  1125. * @see TreePath#getLastPathComponent
  1126. */
  1127. public Object getLastSelectedPathComponent() {
  1128. TreePath selPath = getSelectionModel().getSelectionPath();
  1129. if(selPath != null)
  1130. return selPath.getLastPathComponent();
  1131. return null;
  1132. }
  1133. /**
  1134. * Returns the path identified as the lead.
  1135. * @return path identified as the lead
  1136. */
  1137. public TreePath getLeadSelectionPath() {
  1138. return leadPath;
  1139. }
  1140. /**
  1141. * Returns the path identified as the anchor.
  1142. * @return path identified as the anchor
  1143. * @since 1.3
  1144. */
  1145. public TreePath getAnchorSelectionPath() {
  1146. return anchorPath;
  1147. }
  1148. /**
  1149. * Returns the path to the first selected node.
  1150. *
  1151. * @return the <code>TreePath</code> for the first selected node,
  1152. * or <code>null</code> if nothing is currently selected
  1153. */
  1154. public TreePath getSelectionPath() {
  1155. return getSelectionModel().getSelectionPath();
  1156. }
  1157. /**
  1158. * Returns the paths of all selected values.
  1159. *
  1160. * @return an array of <code>TreePath</code> objects indicating the selected
  1161. * nodes, or <code>null</code> if nothing is currently selected
  1162. */
  1163. public TreePath[] getSelectionPaths() {
  1164. return getSelectionModel().getSelectionPaths();
  1165. }
  1166. /**
  1167. * Returns all of the currently selected rows. This method is simply
  1168. * forwarded to the <code>TreeSelectionModel</code>.
  1169. * If nothing is selected <code>null</code> or an empty array will
  1170. * be returned, based on the <code>TreeSelectionModel</code>
  1171. * implementation.
  1172. *
  1173. * @return an array of integers that identifies all currently selected rows
  1174. * where 0 is the first row in the display
  1175. */
  1176. public int[] getSelectionRows() {
  1177. return getSelectionModel().getSelectionRows();
  1178. }
  1179. /**
  1180. * Returns the number of nodes selected.
  1181. *
  1182. * @return the number of nodes selected
  1183. */
  1184. public int getSelectionCount() {
  1185. return selectionModel.getSelectionCount();
  1186. }
  1187. /**
  1188. * Gets the first selected row.
  1189. *
  1190. * @return an integer designating the first selected row, where 0 is the
  1191. * first row in the display
  1192. */
  1193. public int getMinSelectionRow() {
  1194. return getSelectionModel().getMinSelectionRow();
  1195. }
  1196. /**
  1197. * Returns the last selected row.
  1198. *
  1199. * @return an integer designating the last selected row, where 0 is the
  1200. * first row in the display
  1201. */
  1202. public int getMaxSelectionRow() {
  1203. return getSelectionModel().getMaxSelectionRow();
  1204. }
  1205. /**
  1206. * Returns the row index corresponding to the lead path.
  1207. *
  1208. * @return an integer giving the row index of the lead path,
  1209. * where 0 is the first row in the display; or -1
  1210. * if <code>leadPath</code> is <code>null</code>
  1211. */
  1212. public int getLeadSelectionRow() {
  1213. TreePath leadPath = getLeadSelectionPath();
  1214. if (leadPath != null) {
  1215. return getRowForPath(leadPath);
  1216. }
  1217. return -1;
  1218. }
  1219. /**
  1220. * Returns true if the item identified by the path is currently selected.
  1221. *
  1222. * @param path a <code>TreePath</code> identifying a node
  1223. * @return true if the node is selected
  1224. */
  1225. public boolean isPathSelected(TreePath path) {
  1226. return getSelectionModel().isPathSelected(path);
  1227. }
  1228. /**
  1229. * Returns true if the node identitifed by row is selected.
  1230. *
  1231. * @param row an integer specifying a display row, where 0 is the first
  1232. * row in the display
  1233. * @return true if the node is selected
  1234. */
  1235. public boolean isRowSelected(int row) {
  1236. return getSelectionModel().isRowSelected(row);
  1237. }
  1238. /**
  1239. * Returns an <code>Enumeration</code> of the descendants of the
  1240. * path <code>parent</code> that
  1241. * are currently expanded. If <code>parent</code> is not currently
  1242. * expanded, this will return <code>null</code>.
  1243. * If you expand/collapse nodes while
  1244. * iterating over the returned <code>Enumeration</code>
  1245. * this may not return all
  1246. * the expanded paths, or may return paths that are no longer expanded.
  1247. *
  1248. * @param parent the path which is to be examined
  1249. * @return an <code>Enumeration</code> of the descendents of
  1250. * <code>parent</code>, or <code>null</code> if
  1251. * <code>parent</code> is not currently expanded
  1252. */
  1253. public Enumeration getExpandedDescendants(TreePath parent) {
  1254. if(!isExpanded(parent))
  1255. return null;
  1256. Enumeration toggledPaths = expandedState.keys();
  1257. Vector elements = null;
  1258. TreePath path;
  1259. Object value;
  1260. if(toggledPaths != null) {
  1261. while(toggledPaths.hasMoreElements()) {
  1262. path = (TreePath)toggledPaths.nextElement();
  1263. value = expandedState.get(path);
  1264. // Add the path if it is expanded, a descendant of parent,
  1265. // and it is visible (all parents expanded). This is rather
  1266. // expensive!
  1267. if(path != parent && value != null &&
  1268. ((Boolean)value).booleanValue() &&
  1269. parent.isDescendant(path) && isVisible(path)) {
  1270. if (elements == null) {
  1271. elements = new Vector();
  1272. }
  1273. elements.addElement(path);
  1274. }
  1275. }
  1276. }
  1277. if (elements == null) {
  1278. return DefaultMutableTreeNode.EMPTY_ENUMERATION;
  1279. }
  1280. return elements.elements();
  1281. }
  1282. /**
  1283. * Returns true if the node identified by the path has ever been
  1284. * expanded.
  1285. * @return true if the <code>path</code> has ever been expanded
  1286. */
  1287. public boolean hasBeenExpanded(TreePath path) {
  1288. return (path != null && expandedState.get(path) != null);
  1289. }
  1290. /**
  1291. * Returns true if the node identified by the path is currently expanded,
  1292. *
  1293. * @param path the <code>TreePath</code> specifying the node to check
  1294. * @return false if any of the nodes in the node's path are collapsed,
  1295. * true if all nodes in the path are expanded
  1296. */
  1297. public boolean isExpanded(TreePath path) {
  1298. if(path == null)
  1299. return false;
  1300. // Is this node expanded?
  1301. Object value = expandedState.get(path);
  1302. if(value == null || !((Boolean)value).booleanValue())
  1303. return false;
  1304. // It is, make sure its parent is also expanded.
  1305. TreePath parentPath = path.getParentPath();
  1306. if(parentPath != null)
  1307. return isExpanded(parentPath);
  1308. return true;
  1309. }
  1310. /**
  1311. * Returns true if the node at the specified display row is currently
  1312. * expanded.
  1313. *
  1314. * @param row the row to check, where 0 is the first row in the
  1315. * display
  1316. * @return true if the node is currently expanded, otherwise false
  1317. */
  1318. public boolean isExpanded(int row) {
  1319. TreeUI tree = getUI();
  1320. if(tree != null) {
  1321. TreePath path = tree.getPathForRow(this, row);
  1322. if(path != null)
  1323. return isExpanded(path);
  1324. }
  1325. return false;
  1326. }
  1327. /**
  1328. * Returns true if the value identified by path is currently collapsed,
  1329. * this will return false if any of the values in path are currently
  1330. * not being displayed.
  1331. *
  1332. * @param path the <code>TreePath</code> to check
  1333. * @return true if any of the nodes in the node's path are collapsed,
  1334. * false if all nodes in the path are expanded
  1335. */
  1336. public boolean isCollapsed(TreePath path) {
  1337. return !isExpanded(path);
  1338. }
  1339. /**
  1340. * Returns true if the node at the specified display row is collapsed.
  1341. *
  1342. * @param row the row to check, where 0 is the first row in the
  1343. * display
  1344. * @return true if the node is currently collapsed, otherwise false
  1345. */
  1346. public boolean isCollapsed(int row) {
  1347. return !isExpanded(row);
  1348. }
  1349. /**
  1350. * Ensures that the node identified by path is currently viewable.
  1351. *
  1352. * @param path the <code>TreePath</code> to make visible
  1353. */
  1354. public void makeVisible(TreePath path) {
  1355. if(path != null) {
  1356. TreePath parentPath = path.getParentPath();
  1357. if(parentPath != null) {
  1358. expandPath(parentPath);
  1359. }
  1360. }
  1361. }
  1362. /**
  1363. * Returns true if the value identified by path is currently viewable,
  1364. * which means it is either the root or all of its parents are expanded.
  1365. * Otherwise, this method returns false.
  1366. *
  1367. * @return true if the node is viewable, otherwise false
  1368. */
  1369. public boolean isVisible(TreePath path) {
  1370. if(path != null) {
  1371. TreePath parentPath = path.getParentPath();
  1372. if(parentPath != null)
  1373. return isExpanded(parentPath);
  1374. // Root.
  1375. return true;
  1376. }
  1377. return false;
  1378. }
  1379. /**
  1380. * Returns the <code>Rectangle</code> that the specified node will be drawn
  1381. * into. Returns <code>null</code> if any component in the path is hidden
  1382. * (under a collapsed parent).
  1383. * <p>
  1384. * Note:<br>
  1385. * This method returns a valid rectangle, even if the specified
  1386. * node is not currently displayed.
  1387. *
  1388. * @param path the <code>TreePath</code> identifying the node
  1389. * @return the <code>Rectangle</code> the node is drawn in,
  1390. * or <code>null</code>
  1391. */
  1392. public Rectangle getPathBounds(TreePath path) {
  1393. TreeUI tree = getUI();
  1394. if(tree != null)
  1395. return tree.getPathBounds(this, path);
  1396. return null;
  1397. }
  1398. /**
  1399. * Returns the <code>Rectangle</code> that the node at the specified row is
  1400. * drawn in.
  1401. *
  1402. * @param row the row to be drawn, where 0 is the first row in the
  1403. * display
  1404. * @return the <code>Rectangle</code> the node is drawn in
  1405. */
  1406. public Rectangle getRowBounds(int row) {
  1407. TreePath path = getPathForRow(row);
  1408. return getPathBounds(getPathForRow(row));
  1409. }
  1410. /**
  1411. * Makes sure all the path components in path are expanded (except
  1412. * for the last path component) and scrolls so that the
  1413. * node identified by the path is displayed. Only works when this
  1414. * <code>JTree</code> is contained in a <code>JScrollPane</code>.
  1415. *
  1416. * @param path the <code>TreePath</code> identifying the node to
  1417. * bring into view
  1418. */
  1419. public void scrollPathToVisible(TreePath path) {
  1420. if(path != null) {
  1421. makeVisible(path);
  1422. Rectangle bounds = getPathBounds(path);
  1423. if(bounds != null) {
  1424. scrollRectToVisible(bounds);
  1425. if (accessibleContext != null) {
  1426. ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
  1427. }
  1428. }
  1429. }
  1430. }
  1431. /**
  1432. * Scrolls the item identified by row until it is displayed. The minimum
  1433. * of amount of scrolling necessary to bring the row into view
  1434. * is performed. Only works when this <code>JTree</code> is contained in a
  1435. * <code>JScrollPane</code>.
  1436. *
  1437. * @param row an integer specifying the row to scroll, where 0 is the
  1438. * first row in the display
  1439. */
  1440. public void scrollRowToVisible(int row) {
  1441. scrollPathToVisible(getPathForRow(row));
  1442. }
  1443. /**
  1444. * Returns the path for the specified row. If <code>row</code> is
  1445. * not visible, <code>null</code> is returned.
  1446. *
  1447. * @param row an integer specifying a row
  1448. * @return the <code>TreePath</code> to the specified node,
  1449. * <code>null</code> if <code>row < 0</code>
  1450. * or <code>row > getRowCount()</code>
  1451. */
  1452. public TreePath getPathForRow(int row) {
  1453. TreeUI tree = getUI();
  1454. if(tree != null)
  1455. return tree.getPathForRow(this, row);
  1456. return null;
  1457. }
  1458. /**
  1459. * Returns the row that displays the node identified by the specified
  1460. * path.
  1461. *
  1462. * @param path the <code>TreePath</code> identifying a node
  1463. * @return an integer specifying the display row, where 0 is the first
  1464. * row in the display, or -1 if any of the elements in path
  1465. * are hidden under a collapsed parent.
  1466. */
  1467. public int getRowForPath(TreePath path) {
  1468. TreeUI tree = getUI();
  1469. if(tree != null)
  1470. return tree.getRowForPath(this, path);
  1471. return -1;
  1472. }
  1473. /**
  1474. * Ensures that the node identified by the specified path is
  1475. * expanded and viewable.
  1476. *
  1477. * @param path the <code>TreePath</code> identifying a node
  1478. */
  1479. public void expandPath(TreePath path) {
  1480. // Only expand if not leaf!
  1481. TreeModel model = getModel();
  1482. if(path != null && model != null &&
  1483. !model.isLeaf(path.getLastPathComponent())) {
  1484. setExpandedState(path, true);
  1485. }
  1486. }
  1487. /**
  1488. * Ensures that the node in the specified row is expanded and
  1489. * viewable.
  1490. * <p>
  1491. * If <code>row</code> is < 0 or >= <code>getRowCount</code> this
  1492. * will have no effect.
  1493. *
  1494. * @param row an integer specifying a display row, where 0 is the
  1495. * first row in the display
  1496. */
  1497. public void expandRow(int row) {
  1498. expandPath(getPathForRow(row));
  1499. }
  1500. /**
  1501. * Ensures that the node identified by the specified path is
  1502. * collapsed and viewable.
  1503. *
  1504. * @param path the <code>TreePath</code> identifying a node
  1505. */
  1506. public void collapsePath(TreePath path) {
  1507. setExpandedState(path, false);
  1508. }
  1509. /**
  1510. * Ensures that the node in the specified row is collapsed.
  1511. * <p>
  1512. * If <code>row</code> is < 0 or >= <code>getRowCount</code> this
  1513. * will have no effect.
  1514. *
  1515. * @param row an integer specifying a display row, where 0 is the
  1516. * first row in the display
  1517. */
  1518. public void collapseRow(int row) {
  1519. collapsePath(getPathForRow(row));
  1520. }
  1521. /**
  1522. * Returns the path for the node at the specified location.
  1523. *
  1524. * @param x an integer giving the number of pixels horizontally from
  1525. * the left edge of the display area, minus any left margin
  1526. * @param y an integer giving the number of pixels vertically from
  1527. * the top of the display area, minus any top margin
  1528. * @return the <code>TreePath</code> for the node at that location
  1529. */
  1530. public TreePath getPathForLocation(int x, int y) {
  1531. TreePath closestPath = getClosestPathForLocation(x, y);
  1532. if(closestPath != null) {
  1533. Rectangle pathBounds = getPathBounds(closestPath);
  1534. if(x >= pathBounds.x && x < (pathBounds.x + pathBounds.width) &&
  1535. y >= pathBounds.y && y < (pathBounds.y + pathBounds.height))
  1536. return closestPath;
  1537. }
  1538. return null;
  1539. }
  1540. /**
  1541. * Returns the row for the specified location.
  1542. *
  1543. * @param x an integer giving the number of pixels horizontally from
  1544. * the left edge of the display area, minus any left margin
  1545. * @param y an integer giving the number of pixels vertically from
  1546. * the top of the display area, minus any top margin
  1547. * @return the row corresponding to the location, or -1 if the
  1548. * location is not within the bounds of a displayed cell
  1549. * @see #getClosestRowForLocation
  1550. */
  1551. public int getRowForLocation(int x, int y) {
  1552. return getRowForPath(getPathForLocation(x, y));
  1553. }
  1554. /**
  1555. * Returns the path to the node that is closest to x,y. If
  1556. * no nodes are currently viewable, or there is no model, returns
  1557. * <code>null</code>, otherwise it always returns a valid path. To test if
  1558. * the node is exactly at x, y, get the node's bounds and
  1559. * test x, y against that.
  1560. *
  1561. * @param x an integer giving the number of pixels horizontally from
  1562. * the left edge of the display area, minus any left margin
  1563. * @param y an integer giving the number of pixels vertically from
  1564. * the top of the display area, minus any top margin
  1565. * @return the <code>TreePath</code> for the node closest to that location,
  1566. * <code>null</code> if nothing is viewable or there is no model
  1567. *
  1568. * @see #getPathForLocation
  1569. * @see #getPathBounds
  1570. */
  1571. public TreePath getClosestPathForLocation(int x, int y) {
  1572. TreeUI tree = getUI();
  1573. if(tree != null)
  1574. return tree.getClosestPathForLocation(this, x, y);
  1575. return null;
  1576. }
  1577. /**
  1578. * Returns the row to the node that is closest to x,y. If no nodes
  1579. * are viewable or there is no model, returns -1. Otherwise,
  1580. * it always returns a valid row. To test if the returned object is
  1581. * exactly at x, y, get the bounds for the node at the returned
  1582. * row and test x, y against that.
  1583. *
  1584. * @param x an integer giving the number of pixels horizontally from
  1585. * the left edge of the display area, minus any left margin
  1586. * @param y an integer giving the number of pixels vertically from
  1587. * the top of the display area, minus any top margin
  1588. * @return the row closest to the location, -1 if nothing is
  1589. * viewable or there is no model
  1590. *
  1591. * @see #getRowForLocation
  1592. * @see #getRowBounds
  1593. */
  1594. public int getClosestRowForLocation(int x, int y) {
  1595. return getRowForPath(getClosestPathForLocation(x, y));
  1596. }
  1597. /**
  1598. * Returns true if the tree is being edited. The item that is being
  1599. * edited can be obtained using <code>getSelectionPath</code>.
  1600. *
  1601. * @return true if the user is currently editing a node
  1602. * @see #getSelectionPath
  1603. */
  1604. public boolean isEditing() {
  1605. TreeUI tree = getUI();
  1606. if(tree != null)
  1607. return tree.isEditing(this);
  1608. return false;
  1609. }
  1610. /**
  1611. * Ends the current editing session.
  1612. * (The <code>DefaultTreeCellEditor</code>
  1613. * object saves any edits that are currently in progress on a cell.
  1614. * Other implementations may operate differently.)
  1615. * Has no effect if the tree isn't being edited.
  1616. * <blockquote>
  1617. * <b>Note:</b><br>
  1618. * To make edit-saves automatic whenever the user changes
  1619. * their position in the tree, use {@link #setInvokesStopCellEditing}.
  1620. * </blockquote>
  1621. *
  1622. * @return true if editing was in progress and is now stopped,
  1623. * false if editing was not in progress
  1624. */
  1625. public boolean stopEditing() {
  1626. TreeUI tree = getUI();
  1627. if(tree != null)
  1628. return tree.stopEditing(this);
  1629. return false;
  1630. }
  1631. /**
  1632. * Cancels the current editing session. Has no effect if the
  1633. * tree isn't being edited.
  1634. */
  1635. public void cancelEditing() {
  1636. TreeUI tree = getUI();
  1637. if(tree != null)
  1638. tree.cancelEditing(this);
  1639. }
  1640. /**
  1641. * Selects the node identified by the specified path and initiates
  1642. * editing. The edit-attempt fails if the <code>CellEditor</code>
  1643. * does not allow
  1644. * editing for the specified item.
  1645. *
  1646. * @param path the <code>TreePath</code> identifying a node
  1647. */
  1648. public void startEditingAtPath(TreePath path) {
  1649. TreeUI tree = getUI();
  1650. if(tree != null)
  1651. tree.startEditingAtPath(this, path);
  1652. }
  1653. /**
  1654. * Returns the path to the element that is currently being edited.
  1655. *
  1656. * @return the <code>TreePath</code> for the node being edited
  1657. */
  1658. public TreePath getEditingPath() {
  1659. TreeUI tree = getUI();
  1660. if(tree != null)
  1661. return tree.getEditingPath(this);
  1662. return null;
  1663. }
  1664. //
  1665. // Following are primarily convenience methods for mapping from
  1666. // row based selections to path selections. Sometimes it is
  1667. // easier to deal with these than paths (mouse downs, key downs
  1668. // usually just deal with index based selections).
  1669. // Since row based selections require a UI many of these won't work
  1670. // without one.
  1671. //
  1672. /**
  1673. * Sets the tree's selection model. When a <code>null</code> value is
  1674. * specified an emtpy
  1675. * <code>selectionModel</code> is used, which does not allow selections.
  1676. *
  1677. * @param selectionModel the <code>TreeSelectionModel</code> to use,
  1678. * or <code>null</code> to disable selections
  1679. * @see TreeSelectionModel
  1680. * @beaninfo
  1681. * bound: true
  1682. * description: The tree's selection model.
  1683. */
  1684. public void setSelectionModel(TreeSelectionModel selectionModel) {
  1685. if(selectionModel == null)
  1686. selectionModel = EmptySelectionModel.sharedInstance();
  1687. TreeSelectionModel oldValue = this.selectionModel;
  1688. if (this.selectionModel != null && selectionRedirector != null) {
  1689. this.selectionModel.removeTreeSelectionListener
  1690. (selectionRedirector);
  1691. }
  1692. if (accessibleContext != null) {
  1693. this.selectionModel.removeTreeSelectionListener((TreeSelectionListener)accessibleContext);
  1694. selectionModel.addTreeSelectionListener((TreeSelectionListener)accessibleContext);
  1695. }
  1696. this.selectionModel = selectionModel;
  1697. if (selectionRedirector != null) {
  1698. this.selectionModel.addTreeSelectionListener(selectionRedirector);
  1699. }
  1700. firePropertyChange(SELECTION_MODEL_PROPERTY, oldValue,
  1701. this.selectionModel);
  1702. if (accessibleContext != null) {
  1703. accessibleContext.firePropertyChange(
  1704. AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
  1705. new Boolean(false), new Boolean(true));
  1706. }
  1707. }
  1708. /**
  1709. * Returns the model for selections. This should always return a
  1710. * non-<code>null</code> value. If you don't want to allow anything
  1711. * to be selected
  1712. * set the selection model to <code>null</code>, which forces an empty
  1713. * selection model to be used.
  1714. *
  1715. * @param the <code>TreeSelectionModel</code> in use
  1716. * @see #setSelectionModel
  1717. */
  1718. public TreeSelectionModel getSelectionModel() {
  1719. return selectionModel;
  1720. }
  1721. /**
  1722. * Returns <code>JTreePath</code> instances representing the path
  1723. * between index0 and index1 (including index1).
  1724. * Returns <code>null</code> if there is no tree.
  1725. *
  1726. * @param index0 an integer specifying a display row, where 0 is the
  1727. * first row in the display
  1728. * @param index1 an integer specifying a second display row
  1729. * @return an array of <code>TreePath</code> objects, one for each
  1730. * node between index0 and index1, inclusive; or <code>null</code>
  1731. * if there is no tree
  1732. */
  1733. protected TreePath[] getPathBetweenRows(int index0, int index1) {
  1734. int newMinIndex, newMaxIndex;
  1735. TreeUI tree = getUI();
  1736. newMinIndex = Math.min(index0, index1);
  1737. newMaxIndex = Math.max(index0, index1);
  1738. if(tree != null) {
  1739. TreePath[] selection = new TreePath[newMaxIndex -
  1740. newMinIndex + 1];
  1741. for(int counter = newMinIndex; counter <= newMaxIndex; counter++)
  1742. selection[counter - newMinIndex] = tree.getPathForRow(this,
  1743. counter);
  1744. return selection;
  1745. }
  1746. return null;
  1747. }
  1748. /**
  1749. * Selects the nodes between index0 and index1, inclusive.
  1750. *
  1751. * @param index0 an integer specifying a display row, where 0 is the
  1752. * first row in the display
  1753. * @param index1 an integer specifying a second display row
  1754. */
  1755. public void setSelectionInterval(int index0, int index1) {
  1756. TreePath[] paths = getPathBetweenRows(index0, index1);
  1757. this.getSelectionModel().setSelectionPaths(paths);
  1758. }
  1759. /**
  1760. * Adds the paths between index0 and index1, inclusive, to the
  1761. * selection.
  1762. *
  1763. * @param index0 an integer specifying a display row, where 0 is the
  1764. * first row in the display
  1765. * @param index1 an integer specifying a second display row
  1766. */
  1767. public void addSelectionInterval(int index0, int index1) {
  1768. TreePath[] paths = getPathBetweenRows(index0, index1);
  1769. this.getSelectionModel().addSelectionPaths(paths);
  1770. }
  1771. /**
  1772. * Removes the nodes between index0 and index1, inclusive, from the
  1773. * selection.
  1774. *
  1775. * @param index0 an integer specifying a display row, where 0 is the
  1776. * first row in the display
  1777. * @param index1 an integer specifying a second display row
  1778. */
  1779. public void removeSelectionInterval(int index0, int index1) {
  1780. TreePath[] paths = getPathBetweenRows(index0, index1);
  1781. this.getSelectionModel().removeSelectionPaths(paths);
  1782. }
  1783. /**
  1784. * Removes the node identified by the specified path from the current
  1785. * selection.
  1786. *
  1787. * @param path the <code>TreePath</code> identifying a node
  1788. */
  1789. public void removeSelectionPath(TreePath path) {
  1790. this.getSelectionModel().removeSelectionPath(path);
  1791. }
  1792. /**
  1793. * Removes the nodes identified by the specified paths from the
  1794. * current selection.
  1795. *
  1796. * @param paths an array of <code>TreePath</code> objects that
  1797. * specifies the nodes to remove
  1798. */
  1799. public void removeSelectionPaths(TreePath[] paths) {
  1800. this.getSelectionModel().removeSelectionPaths(paths);
  1801. }
  1802. /**
  1803. * Removes the path at the index <code>row</code> from the current
  1804. * selection.
  1805. *
  1806. * @param path the TreePath identifying the node to remove
  1807. */
  1808. public void removeSelectionRow(int row) {
  1809. int[] rows = { row };
  1810. removeSelectionRows(rows);
  1811. }
  1812. /**
  1813. * Removes the paths that are selected at each of the specified
  1814. * rows.
  1815. *
  1816. * @param row an array of ints specifying display rows, where 0 is
  1817. * the first row in the display
  1818. */
  1819. public void removeSelectionRows(int[] rows) {
  1820. TreeUI ui = getUI();
  1821. if(ui != null && rows != null) {
  1822. int numRows = rows.length;
  1823. TreePath[] paths = new TreePath[numRows];
  1824. for(int counter = 0; counter < numRows; counter++)
  1825. paths[counter] = ui.getPathForRow(this, rows[counter]);
  1826. removeSelectionPaths(paths);
  1827. }
  1828. }
  1829. /**
  1830. * Clears the selection.
  1831. */
  1832. public void clearSelection() {
  1833. getSelectionModel().clearSelection();
  1834. }
  1835. /**
  1836. * Returns true if the selection is currently empty.
  1837. *
  1838. * @return true if the selection is currently empty
  1839. */
  1840. public boolean isSelectionEmpty() {
  1841. return getSelectionModel().isSelectionEmpty();
  1842. }
  1843. /**
  1844. * Adds a listener for <code>TreeExpansion</code> events.
  1845. *
  1846. * @param tel a TreeExpansionListener that will be notified when
  1847. * a tree node is expanded or collapsed (a "negative
  1848. * expansion")
  1849. */
  1850. public void addTreeExpansionListener(TreeExpansionListener tel) {
  1851. if (settingUI) {
  1852. uiTreeExpansionListener = tel;
  1853. }
  1854. listenerList.add(TreeExpansionListener.class, tel);
  1855. }
  1856. /**
  1857. * Removes a listener for <code>TreeExpansion</code> events.
  1858. *
  1859. * @param tel the <code>TreeExpansionListener</code> to remove
  1860. */
  1861. public void removeTreeExpansionListener(TreeExpansionListener tel) {
  1862. listenerList.remove(TreeExpansionListener.class, tel);
  1863. if (uiTreeExpansionListener == tel) {
  1864. uiTreeExpansionListener = null;
  1865. }
  1866. }
  1867. /**
  1868. * Adds a listener for <code>TreeWillExpand</code> events.
  1869. *
  1870. * @param tel a <code>TreeWillExpandListener</code> that will be notified
  1871. * when a tree node will be expanded or collapsed (a "negative
  1872. * expansion")
  1873. */
  1874. public void addTreeWillExpandListener(TreeWillExpandListener tel) {
  1875. listenerList.add(TreeWillExpandListener.class, tel);
  1876. }
  1877. /**
  1878. * Removes a listener for <code>TreeWillExpand</code> events.
  1879. *
  1880. * @param tel the <code>TreeWillExpandListener</code> to remove
  1881. */
  1882. public void removeTreeWillExpandListener(TreeWillExpandListener tel) {
  1883. listenerList.remove(TreeWillExpandListener.class, tel);
  1884. }
  1885. /**
  1886. * Notify all listeners that have registered interest for
  1887. * notification on this event type. The event instance
  1888. * is lazily created using the parameters passed into
  1889. * the fire method.
  1890. *
  1891. * @param path the <code>TreePath</code> indicating the node that was
  1892. * expanded
  1893. * @see EventListenerList
  1894. */
  1895. public void fireTreeExpanded(TreePath path) {
  1896. // Guaranteed to return a non-null array
  1897. Object[] listeners = listenerList.getListenerList();
  1898. TreeExpansionEvent e = null;
  1899. if (uiTreeExpansionListener != null) {
  1900. e = new TreeExpansionEvent(this, path);
  1901. uiTreeExpansionListener.treeExpanded(e);
  1902. }
  1903. // Process the listeners last to first, notifying
  1904. // those that are interested in this event
  1905. for (int i = listeners.length-2; i>=0; i-=2) {
  1906. if (listeners[i]==TreeExpansionListener.class &&
  1907. listeners[i + 1] != uiTreeExpansionListener) {
  1908. // Lazily create the event:
  1909. if (e == null)
  1910. e = new TreeExpansionEvent(this, path);
  1911. ((TreeExpansionListener)listeners[i+1]).
  1912. treeExpanded(e);
  1913. }
  1914. }
  1915. }
  1916. /**
  1917. * Notify all listeners that have registered interest for
  1918. * notification on this event type. The event instance
  1919. * is lazily created using the parameters passed into
  1920. * the fire method.
  1921. *
  1922. * @param path the <code>TreePath</code> indicating the node that was
  1923. * collapsed
  1924. * @see EventListenerList
  1925. */
  1926. public void fireTreeCollapsed(TreePath path) {
  1927. // Guaranteed to return a non-null array
  1928. Object[] listeners = listenerList.getListenerList();
  1929. TreeExpansionEvent e = null;
  1930. if (uiTreeExpansionListener != null) {
  1931. e = new TreeExpansionEvent(this, path);
  1932. uiTreeExpansionListener.treeCollapsed(e);
  1933. }
  1934. // Process the listeners last to first, notifying
  1935. // those that are interested in this event
  1936. for (int i = listeners.length-2; i>=0; i-=2) {
  1937. if (listeners[i]==TreeExpansionListener.class &&
  1938. listeners[i + 1] != uiTreeExpansionListener) {
  1939. // Lazily create the event:
  1940. if (e == null)
  1941. e = new TreeExpansionEvent(this, path);
  1942. ((TreeExpansionListener)listeners[i+1]).
  1943. treeCollapsed(e);
  1944. }
  1945. }
  1946. }
  1947. /**
  1948. * Notify all listeners that have registered interest for
  1949. * notification on this event type. The event instance
  1950. * is lazily created using the parameters passed into
  1951. * the fire method.
  1952. *
  1953. * @param path the <code>TreePath</code> indicating the node that was
  1954. * expanded
  1955. * @see EventListenerList
  1956. */
  1957. public void fireTreeWillExpand(TreePath path) throws ExpandVetoException {
  1958. // Guaranteed to return a non-null array
  1959. Object[] listeners = listenerList.getListenerList();
  1960. TreeExpansionEvent e = null;
  1961. // Process the listeners last to first, notifying
  1962. // those that are interested in this event
  1963. for (int i = listeners.length-2; i>=0; i-=2) {
  1964. if (listeners[i]==TreeWillExpandListener.class) {
  1965. // Lazily create the event:
  1966. if (e == null)
  1967. e = new TreeExpansionEvent(this, path);
  1968. ((TreeWillExpandListener)listeners[i+1]).
  1969. treeWillExpand(e);
  1970. }
  1971. }
  1972. }
  1973. /**
  1974. * Notify all listeners that have registered interest for
  1975. * notification on this event type. The event instance
  1976. * is lazily created using the parameters passed into
  1977. * the fire method.
  1978. *
  1979. * @param path the <code>TreePath</code> indicating the node that was
  1980. * expanded
  1981. * @see EventListenerList
  1982. */
  1983. public void fireTreeWillCollapse(TreePath path) throws ExpandVetoException {
  1984. // Guaranteed to return a non-null array
  1985. Object[] listeners = listenerList.getListenerList();
  1986. TreeExpansionEvent e = null;
  1987. // Process the listeners last to first, notifying
  1988. // those that are interested in this event
  1989. for (int i = listeners.length-2; i>=0; i-=2) {
  1990. if (listeners[i]==TreeWillExpandListener.class) {
  1991. // Lazily create the event:
  1992. if (e == null)
  1993. e = new TreeExpansionEvent(this, path);
  1994. ((TreeWillExpandListener)listeners[i+1]).
  1995. treeWillCollapse(e);
  1996. }
  1997. }
  1998. }
  1999. /**
  2000. * Adds a listener for <code>TreeSelection</code> events.
  2001. *
  2002. * @param tsl the <code>TreeSelectionListener</code> that will be notified
  2003. * when a node is selected or deselected (a "negative
  2004. * selection")
  2005. */
  2006. public void addTreeSelectionListener(TreeSelectionListener tsl) {
  2007. listenerList.add(TreeSelectionListener.class,tsl);
  2008. if(listenerList.getListenerCount(TreeSelectionListener.class) != 0
  2009. && selectionRedirector == null) {
  2010. selectionRedirector = new TreeSelectionRedirector();
  2011. selectionModel.addTreeSelectionListener(selectionRedirector);
  2012. }
  2013. }
  2014. /**
  2015. * Removes a <code>TreeSelection</code> listener.
  2016. *
  2017. * @param tsl the <code>TreeSelectionListener</code> to remove
  2018. */
  2019. public void removeTreeSelectionListener(TreeSelectionListener tsl) {
  2020. listenerList.remove(TreeSelectionListener.class,tsl);
  2021. if(listenerList.getListenerCount(TreeSelectionListener.class) == 0
  2022. && selectionRedirector != null) {
  2023. selectionModel.removeTreeSelectionListener
  2024. (selectionRedirector);
  2025. selectionRedirector = null;
  2026. }
  2027. }
  2028. /**
  2029. * Notifies all listeners that have registered interest for
  2030. * notification on this event type. The event instance
  2031. * is lazily created using the parameters passed into
  2032. * the fire method.
  2033. *
  2034. * @param e the <code>TreeSelectionEvent</code> generated by the
  2035. * <code>TreeSelectionModel</code>
  2036. * when a node is selected or deselected
  2037. * @see EventListenerList
  2038. */
  2039. protected void fireValueChanged(TreeSelectionEvent e) {
  2040. // Guaranteed to return a non-null array
  2041. Object[] listeners = listenerList.getListenerList();
  2042. // Process the listeners last to first, notifying
  2043. // those that are interested in this event
  2044. for (int i = listeners.length-2; i>=0; i-=2) {
  2045. // TreeSelectionEvent e = null;
  2046. if (listeners[i]==TreeSelectionListener.class) {
  2047. // Lazily create the event:
  2048. // if (e == null)
  2049. // e = new ListSelectionEvent(this, firstIndex, lastIndex);
  2050. ((TreeSelectionListener)listeners[i+1]).valueChanged(e);
  2051. }
  2052. }
  2053. }
  2054. /**
  2055. * Sent when the tree has changed enough that we need to resize
  2056. * the bounds, but not enough that we need to remove the
  2057. * expanded node set (e.g nodes were expanded or collapsed, or
  2058. * nodes were inserted into the tree). You should never have to
  2059. * invoke this, the UI will invoke this as it needs to.
  2060. */
  2061. public void treeDidChange() {
  2062. revalidate();
  2063. repaint();
  2064. }
  2065. /**
  2066. * Sets the number of rows that are to be displayed.
  2067. * This will only work if the reciever is contained in a
  2068. * <code>JScrollPane</code>,
  2069. * and will adjust the preferred size and size of that scrollpane.
  2070. *
  2071. * @param newCount the number of rows to display
  2072. * @beaninfo
  2073. * bound: true
  2074. * description: The number of rows that are to be displayed.
  2075. */
  2076. public void setVisibleRowCount(int newCount) {
  2077. int oldCount = visibleRowCount;
  2078. visibleRowCount = newCount;
  2079. firePropertyChange(VISIBLE_ROW_COUNT_PROPERTY, oldCount,
  2080. visibleRowCount);
  2081. invalidate();
  2082. if (accessibleContext != null) {
  2083. ((AccessibleJTree)accessibleContext).fireVisibleDataPropertyChange();
  2084. }
  2085. }
  2086. /**
  2087. * Returns the number of rows that are displayed in the display area.
  2088. *
  2089. * @return the number of rows displayed
  2090. */
  2091. public int getVisibleRowCount() {
  2092. return visibleRowCount;
  2093. }
  2094. // Serialization support.
  2095. private void writeObject(ObjectOutputStream s) throws IOException {
  2096. Vector values = new Vector();
  2097. s.defaultWriteObject();
  2098. // Save the cellRenderer, if its Serializable.
  2099. if(cellRenderer != null && cellRenderer instanceof Serializable) {
  2100. values.addElement("cellRenderer");
  2101. values.addElement(cellRenderer);
  2102. }
  2103. // Save the cellEditor, if its Serializable.
  2104. if(cellEditor != null && cellEditor instanceof Serializable) {
  2105. values.addElement("cellEditor");
  2106. values.addElement(cellEditor);
  2107. }
  2108. // Save the treeModel, if its Serializable.
  2109. if(treeModel != null && treeModel instanceof Serializable) {
  2110. values.addElement("treeModel");
  2111. values.addElement(treeModel);
  2112. }
  2113. // Save the selectionModel, if its Serializable.
  2114. if(selectionModel != null && selectionModel instanceof Serializable) {
  2115. values.addElement("selectionModel");
  2116. values.addElement(selectionModel);
  2117. }
  2118. Object expandedData = getArchivableExpandedState();
  2119. if(expandedData != null) {
  2120. values.addElement("expandedState");
  2121. values.addElement(expandedData);
  2122. }
  2123. s.writeObject(values);
  2124. if ((ui != null) && (getUIClassID().equals(uiClassID))) {
  2125. ui.installUI(this);
  2126. }
  2127. }
  2128. private void readObject(ObjectInputStream s)
  2129. throws IOException, ClassNotFoundException {
  2130. s.defaultReadObject();
  2131. // Create an instance of expanded state.
  2132. expandedState = new Hashtable();
  2133. expandedStack = new Stack();
  2134. Vector values = (Vector)s.readObject();
  2135. int indexCounter = 0;
  2136. int maxCounter = values.size();
  2137. if(indexCounter < maxCounter && values.elementAt(indexCounter).
  2138. equals("cellRenderer")) {
  2139. cellRenderer = (TreeCellRenderer)values.elementAt(++indexCounter);
  2140. indexCounter++;
  2141. }
  2142. if(indexCounter < maxCounter && values.elementAt(indexCounter).
  2143. equals("cellEditor")) {
  2144. cellEditor = (TreeCellEditor)values.elementAt(++indexCounter);
  2145. indexCounter++;
  2146. }
  2147. if(indexCounter < maxCounter && values.elementAt(indexCounter).
  2148. equals("treeModel")) {
  2149. treeModel = (TreeModel)values.elementAt(++indexCounter);
  2150. indexCounter++;
  2151. }
  2152. if(indexCounter < maxCounter && values.elementAt(indexCounter).
  2153. equals("selectionModel")) {
  2154. selectionModel = (TreeSelectionModel)values.elementAt(++indexCounter);
  2155. indexCounter++;
  2156. }
  2157. if(indexCounter < maxCounter && values.elementAt(indexCounter).
  2158. equals("expandedState")) {
  2159. unarchiveExpandedState(values.elementAt(++indexCounter));
  2160. indexCounter++;
  2161. }
  2162. // Reinstall the redirector.
  2163. if(listenerList.getListenerCount(TreeSelectionListener.class) != 0) {
  2164. selectionRedirector = new TreeSelectionRedirector();
  2165. selectionModel.addTreeSelectionListener(selectionRedirector);
  2166. }
  2167. // Listener to TreeModel.
  2168. if(treeModel != null) {
  2169. treeModelListener = createTreeModelListener();
  2170. if(treeModelListener != null)
  2171. treeModel.addTreeModelListener(treeModelListener);
  2172. }
  2173. }
  2174. /**
  2175. * Returns an object that can be archived indicating what nodes are
  2176. * expanded and what aren't. The objects from the model are NOT
  2177. * written out.
  2178. */
  2179. private Object getArchivableExpandedState() {
  2180. TreeModel model = getModel();
  2181. if(model != null) {
  2182. Enumeration paths = expandedState.keys();
  2183. if(paths != null) {
  2184. Vector state = new Vector();
  2185. while(paths.hasMoreElements()) {
  2186. TreePath path = (TreePath)paths.nextElement();
  2187. Object archivePath;
  2188. try {
  2189. archivePath = getModelIndexsForPath(path);
  2190. } catch (Error error) {
  2191. archivePath = null;
  2192. }
  2193. if(archivePath != null) {
  2194. state.addElement(archivePath);
  2195. state.addElement(expandedState.get(path));
  2196. }
  2197. }
  2198. return state;
  2199. }
  2200. }
  2201. return null;
  2202. }
  2203. /**
  2204. * Updates the expanded state of nodes in the tree based on the
  2205. * previously archived state <code>state</code>.
  2206. */
  2207. private void unarchiveExpandedState(Object state) {
  2208. if(state instanceof Vector) {
  2209. Vector paths = (Vector)state;
  2210. for(int counter = paths.size() - 1; counter >= 0; counter--) {
  2211. Boolean eState = (Boolean)paths.elementAt(counter--);
  2212. TreePath path;
  2213. try {
  2214. path = getPathForIndexs((int[])paths.elementAt(counter));
  2215. if(path != null)
  2216. expandedState.put(path, eState);
  2217. } catch (Error error) {}
  2218. }
  2219. }
  2220. }
  2221. /**
  2222. * Returns an array of integers specifying the indexs of the
  2223. * components in the <code>path</code>. If <code>path</code> is
  2224. * the root, this will return an empty array. If <code>path</code>
  2225. * is <code>null</code>, <code>null</code> will be returned.
  2226. */
  2227. private int[] getModelIndexsForPath(TreePath path) {
  2228. if(path != null) {
  2229. TreeModel model = getModel();
  2230. int count = path.getPathCount();
  2231. int[] indexs = new int[count - 1];
  2232. Object parent = model.getRoot();
  2233. for(int counter = 1; counter < count; counter++) {
  2234. indexs[counter - 1] = model.getIndexOfChild
  2235. (parent, path.getPathComponent(counter));
  2236. parent = path.getPathComponent(counter);
  2237. if(indexs[counter - 1] < 0)
  2238. return null;
  2239. }
  2240. return indexs;
  2241. }
  2242. return null;
  2243. }
  2244. /**
  2245. * Returns a <code>TreePath</code> created by obtaining the children
  2246. * for each of the indices in <code>indexs</code>. If <code>indexs</code>
  2247. * or the <code>TreeModel</code> is <code>null</code>, it will return
  2248. * <code>null</code>.
  2249. */
  2250. private TreePath getPathForIndexs(int[] indexs) {
  2251. if(indexs == null)
  2252. return null;
  2253. TreeModel model = getModel();
  2254. if(model == null)
  2255. return null;
  2256. int count = indexs.length;
  2257. Object parent = model.getRoot();
  2258. TreePath parentPath = new TreePath(parent);
  2259. for(int counter = 0; counter < count; counter++) {
  2260. parent = model.getChild(parent, indexs[counter]);
  2261. if(parent == null)
  2262. return null;
  2263. parentPath = parentPath.pathByAddingChild(parent);
  2264. }
  2265. return parentPath;
  2266. }
  2267. /**
  2268. * <code>EmptySelectionModel</code> is a <code>TreeSelectionModel</code>
  2269. * that does not allow anything to be selected.
  2270. * <p>
  2271. * <strong>Warning:</strong>
  2272. * Serialized objects of this class will not be compatible with
  2273. * future Swing releases. The current serialization support is appropriate
  2274. * for short term storage or RMI between applications running the same
  2275. * version of Swing. A future release of Swing will provide support for
  2276. * long term persistence.
  2277. */
  2278. protected static class EmptySelectionModel extends
  2279. DefaultTreeSelectionModel
  2280. {
  2281. /** Unique shared instance. */
  2282. protected static final EmptySelectionModel sharedInstance =
  2283. new EmptySelectionModel();
  2284. /** Returns a shared instance of an empty selection model. */
  2285. static public EmptySelectionModel sharedInstance() {
  2286. return sharedInstance;
  2287. }
  2288. /** A <code>null</code> implementation that selects nothing. */
  2289. public void setSelectionPaths(TreePath[] pPaths) {}
  2290. /** A <code>null</code> implementation that adds nothing. */
  2291. public void addSelectionPaths(TreePath[] paths) {}
  2292. /** A <code>null</code> implementation that removes nothing. */
  2293. public void removeSelectionPaths(TreePath[] paths) {}
  2294. }
  2295. /**
  2296. * Handles creating a new <code>TreeSelectionEvent</code> with the
  2297. * <code>JTree</code> as the
  2298. * source and passing it off to all the listeners.
  2299. * <p>
  2300. * <strong>Warning:</strong>
  2301. * Serialized objects of this class will not be compatible with
  2302. * future Swing releases. The current serialization support is appropriate
  2303. * for short term storage or RMI between applications running the same
  2304. * version of Swing. A future release of Swing will provide support for
  2305. * long term persistence.
  2306. */
  2307. protected class TreeSelectionRedirector implements Serializable,
  2308. TreeSelectionListener
  2309. {
  2310. /**
  2311. * Invoked by the <code>TreeSelectionModel</code> when the
  2312. * selection changes.
  2313. *
  2314. * @param e the <code>TreeSelectionEvent</code> generated by the
  2315. * <code>TreeSelectionModel</code>
  2316. */
  2317. public void valueChanged(TreeSelectionEvent e) {
  2318. TreeSelectionEvent newE;
  2319. newE = (TreeSelectionEvent)e.cloneWithSource(JTree.this);
  2320. fireValueChanged(newE);
  2321. }
  2322. } // End of class JTree.TreeSelectionRedirector
  2323. //
  2324. // Scrollable interface
  2325. //
  2326. /**
  2327. * Returns the preferred display size of a <code>JTree</code>. The height is
  2328. * determined from <code>getVisibleRowCount</code> and the width
  2329. * is the current preferred width.
  2330. *
  2331. * @return a <code>Dimension</code> object containing the preferred size
  2332. */
  2333. public Dimension getPreferredScrollableViewportSize() {
  2334. int width = getPreferredSize().width;
  2335. int visRows = getVisibleRowCount();
  2336. int height;
  2337. if(isFixedRowHeight())
  2338. height = visRows * getRowHeight();
  2339. else {
  2340. TreeUI ui = getUI();
  2341. if(ui != null && ui.getRowCount(this) > 0)
  2342. height = getRowBounds(0).height * visRows;
  2343. else
  2344. height = 16 * visRows;
  2345. }
  2346. return new Dimension(width, height);
  2347. }
  2348. /**
  2349. * Returns the amount to increment when scrolling. The amount is
  2350. * the height of the first displayed row that isn't completely in view
  2351. * or, if it is totally displayed, the height of the next row in the
  2352. * scrolling direction.
  2353. *
  2354. * @param visibleRect the view area visible within the viewport
  2355. * @param orientation either <code>SwingConstants.VERTICAL</code>
  2356. * or <code>SwingConstants.HORIZONTAL</code>
  2357. * @param direction less than zero to scroll up/left,
  2358. * greater than zero for down/right
  2359. * @return the "unit" increment for scrolling in the specified direction
  2360. * @see JScrollBar#setUnitIncrement(int)
  2361. */
  2362. public int getScrollableUnitIncrement(Rectangle visibleRect,
  2363. int orientation, int direction) {
  2364. if(orientation == SwingConstants.VERTICAL) {
  2365. Rectangle rowBounds;
  2366. int firstIndex = getClosestRowForLocation
  2367. (0, visibleRect.y);
  2368. if(firstIndex != -1) {
  2369. rowBounds = getRowBounds(firstIndex);
  2370. if(rowBounds.y != visibleRect.y) {
  2371. if(direction < 0) // UP
  2372. return (visibleRect.y - rowBounds.y);
  2373. return (rowBounds.y + rowBounds.height - visibleRect.y);
  2374. }
  2375. if(direction < 0) { // UP
  2376. if(firstIndex != 0) {
  2377. rowBounds = getRowBounds(firstIndex - 1);
  2378. return rowBounds.height;
  2379. }
  2380. }
  2381. else {
  2382. return rowBounds.height;
  2383. }
  2384. }
  2385. return 0;
  2386. }
  2387. return 4;
  2388. }
  2389. /**
  2390. * Returns the amount for a block increment, which is the height or
  2391. * width of <code>visibleRect</code>, based on <code>orientation</code>.
  2392. *
  2393. * @param visibleRect the view area visible within the viewport
  2394. * @param orientation either <code>SwingConstants.VERTICAL</code>
  2395. * or <code>SwingConstants.HORIZONTAL</code>
  2396. * @param direction less than zero to scroll up/left,
  2397. * greater than zero for down/right.
  2398. * @return the "block" increment for scrolling in the specified direction
  2399. * @see JScrollBar#setBlockIncrement(int)
  2400. */
  2401. public int getScrollableBlockIncrement(Rectangle visibleRect,
  2402. int orientation, int direction) {
  2403. return (orientation == SwingConstants.VERTICAL) ? visibleRect.height :
  2404. visibleRect.width;
  2405. }
  2406. /**
  2407. * Returns false to indicate that the width of the viewport does not
  2408. * determine the width of the table, unless the preferred width of
  2409. * the tree is smaller than the viewports width. In other words:
  2410. * ensure that the tree is never smaller than its viewport.
  2411. *
  2412. * @return false
  2413. * @see Scrollable#getScrollableTracksViewportWidth
  2414. */
  2415. public boolean getScrollableTracksViewportWidth() {
  2416. if (getParent() instanceof JViewport) {
  2417. return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
  2418. }
  2419. return false;
  2420. }
  2421. /**
  2422. * Returns false to indicate that the height of the viewport does not
  2423. * determine the height of the table, unless the preferred height
  2424. * of the tree is smaller than the viewports height. In other words:
  2425. * ensure that the tree is never smaller than its viewport.
  2426. *
  2427. * @return false
  2428. * @see Scrollable#getScrollableTracksViewportHeight
  2429. */
  2430. public boolean getScrollableTracksViewportHeight() {
  2431. if (getParent() instanceof JViewport) {
  2432. return (((JViewport)getParent()).getHeight() > getPreferredSize().height);
  2433. }
  2434. return false;
  2435. }
  2436. /**
  2437. * Sets the expanded state of this <code>JTree</code>.
  2438. * If <code>state</code> is
  2439. * true, all parents of <code>path</code> and path are marked as
  2440. * expanded. If <code>state</code> is false, all parents of
  2441. * <code>path</code> are marked EXPANDED, but <code>path</code> itself
  2442. * is marked collapsed.<p>
  2443. * This will fail if a <code>TreeWillExpandListener</code> vetos it.
  2444. */
  2445. protected void setExpandedState(TreePath path, boolean state) {
  2446. if(path != null) {
  2447. // Make sure all parents of path are expanded.
  2448. Stack stack;
  2449. TreePath parentPath = path.getParentPath();
  2450. if (expandedStack.size() == 0) {
  2451. stack = new Stack();
  2452. }
  2453. else {
  2454. stack = (Stack)expandedStack.pop();
  2455. }
  2456. try {
  2457. while(parentPath != null) {
  2458. if(isExpanded(parentPath)) {
  2459. parentPath = null;
  2460. }
  2461. else {
  2462. stack.push(parentPath);
  2463. parentPath = parentPath.getParentPath();
  2464. }
  2465. }
  2466. for(int counter = stack.size() - 1; counter >= 0; counter--) {
  2467. parentPath = (TreePath)stack.pop();
  2468. if(!isExpanded(parentPath)) {
  2469. try {
  2470. fireTreeWillExpand(parentPath);
  2471. } catch (ExpandVetoException eve) {
  2472. // Expand vetoed!
  2473. return;
  2474. }
  2475. expandedState.put(parentPath, Boolean.TRUE);
  2476. fireTreeExpanded(parentPath);
  2477. if (accessibleContext != null) {
  2478. ((AccessibleJTree)accessibleContext).
  2479. fireVisibleDataPropertyChange();
  2480. }
  2481. }
  2482. }
  2483. }
  2484. finally {
  2485. if (expandedStack.size() < TEMP_STACK_SIZE) {
  2486. stack.removeAllElements();
  2487. expandedStack.push(stack);
  2488. }
  2489. }
  2490. if(!state) {
  2491. // collapse last path.
  2492. Object cValue = expandedState.get(path);
  2493. if(cValue != null && ((Boolean)cValue).booleanValue()) {
  2494. try {
  2495. fireTreeWillCollapse(path);
  2496. }
  2497. catch (ExpandVetoException eve) {
  2498. return;
  2499. }
  2500. expandedState.put(path, Boolean.FALSE);
  2501. fireTreeCollapsed(path);
  2502. if (removeDescendantSelectedPaths(path, false) &&
  2503. !isPathSelected(path)) {
  2504. // A descendant was selected, select the parent.
  2505. addSelectionPath(path);
  2506. }
  2507. if (accessibleContext != null) {
  2508. ((AccessibleJTree)accessibleContext).
  2509. fireVisibleDataPropertyChange();
  2510. }
  2511. }
  2512. }
  2513. else {
  2514. // Expand last path.
  2515. Object cValue = expandedState.get(path);
  2516. if(cValue == null || !((Boolean)cValue).booleanValue()) {
  2517. try {
  2518. fireTreeWillExpand(path);
  2519. }
  2520. catch (ExpandVetoException eve) {
  2521. return;
  2522. }
  2523. expandedState.put(path, Boolean.TRUE);
  2524. fireTreeExpanded(path);
  2525. if (accessibleContext != null) {
  2526. ((AccessibleJTree)accessibleContext).
  2527. fireVisibleDataPropertyChange();
  2528. }
  2529. }
  2530. }
  2531. }
  2532. }
  2533. /**
  2534. * Returns an <code>Enumeration</code> of <code>TreePaths</code>
  2535. * that have been expanded that
  2536. * are descendants of <code>parent</code>.
  2537. */
  2538. protected Enumeration getDescendantToggledPaths(TreePath parent) {
  2539. if(parent == null)
  2540. return null;
  2541. Vector descendants = new Vector();
  2542. Enumeration nodes = expandedState.keys();
  2543. TreePath path;
  2544. while(nodes.hasMoreElements()) {
  2545. path = (TreePath)nodes.nextElement();
  2546. if(parent.isDescendant(path))
  2547. descendants.addElement(path);
  2548. }
  2549. return descendants.elements();
  2550. }
  2551. /**
  2552. * Removes any descendants of the <code>TreePaths</code> in
  2553. * <code>toRemove</code>
  2554. * that have been expanded.
  2555. */
  2556. protected void removeDescendantToggledPaths(Enumeration toRemove) {
  2557. if(toRemove != null) {
  2558. while(toRemove.hasMoreElements()) {
  2559. Enumeration descendants = getDescendantToggledPaths
  2560. ((TreePath)toRemove.nextElement());
  2561. if(descendants != null) {
  2562. while(descendants.hasMoreElements()) {
  2563. expandedState.remove(descendants.nextElement());
  2564. }
  2565. }
  2566. }
  2567. }
  2568. }
  2569. /**
  2570. * Clears the cache of toggled tree paths. This does NOT send out
  2571. * any <code>TreeExpansionListener</code> events.
  2572. */
  2573. protected void clearToggledPaths() {
  2574. expandedState.clear();
  2575. }
  2576. /**
  2577. * Creates and returns an instance of <code>TreeModelHandler</code>.
  2578. * The returned
  2579. * object is responsible for updating the expanded state when the
  2580. * <code>TreeModel</code> changes.
  2581. * <p>
  2582. * For more information on what expanded state means, see the
  2583. * <a href=#jtree_description>JTree description</a> above.
  2584. */
  2585. protected TreeModelListener createTreeModelListener() {
  2586. return new TreeModelHandler();
  2587. }
  2588. /**
  2589. * Removes any paths in the selection that are descendants of
  2590. * <code>path</code>. If <code>includePath</code> is true and
  2591. * <code>path</code> is selected, it will be removed from the selection.
  2592. *
  2593. * @return true if a descendant was selected
  2594. * @since 1.3
  2595. */
  2596. protected boolean removeDescendantSelectedPaths(TreePath path,
  2597. boolean includePath) {
  2598. TreePath[] toRemove = getDescendantSelectedPaths(path, includePath);
  2599. if (toRemove != null) {
  2600. getSelectionModel().removeSelectionPaths(toRemove);
  2601. return true;
  2602. }
  2603. return false;
  2604. }
  2605. /**
  2606. * Returns an array of paths in the selection that are descendants of
  2607. * <code>path</code>. The returned array may contain <code>null</code>s.
  2608. */
  2609. private TreePath[] getDescendantSelectedPaths(TreePath path,
  2610. boolean includePath) {
  2611. TreeSelectionModel sm = getSelectionModel();
  2612. TreePath[] selPaths = (sm != null) ? sm.getSelectionPaths() :
  2613. null;
  2614. if(selPaths != null) {
  2615. boolean shouldRemove = false;
  2616. for(int counter = selPaths.length - 1; counter >= 0; counter--) {
  2617. if(selPaths[counter] != null &&
  2618. path.isDescendant(selPaths[counter]) &&
  2619. (!path.equals(selPaths[counter]) || includePath))
  2620. shouldRemove = true;
  2621. else
  2622. selPaths[counter] = null;
  2623. }
  2624. if(!shouldRemove) {
  2625. selPaths = null;
  2626. }
  2627. return selPaths;
  2628. }
  2629. return null;
  2630. }
  2631. /**
  2632. * Removes any paths from the selection model that are descendants of
  2633. * the nodes identified by in <code>e</code>.
  2634. */
  2635. void removeDescendantSelectedPaths(TreeModelEvent e) {
  2636. TreePath pPath = e.getTreePath();
  2637. Object[] oldChildren = e.getChildren();
  2638. TreeSelectionModel sm = getSelectionModel();
  2639. if (sm != null && pPath != null && oldChildren != null &&
  2640. oldChildren.length > 0) {
  2641. for (int counter = oldChildren.length - 1; counter >= 0;
  2642. counter--) {
  2643. // Might be better to call getDescendantSelectedPaths
  2644. // numerous times, then push to the model.
  2645. removeDescendantSelectedPaths(pPath.pathByAddingChild
  2646. (oldChildren[counter]), true);
  2647. }
  2648. }
  2649. }
  2650. /**
  2651. * Listens to the model and updates the <code>expandedState</code>
  2652. * accordingly when nodes are removed, or changed.
  2653. */
  2654. protected class TreeModelHandler implements TreeModelListener {
  2655. public void treeNodesChanged(TreeModelEvent e) { }
  2656. public void treeNodesInserted(TreeModelEvent e) { }
  2657. public void treeStructureChanged(TreeModelEvent e) {
  2658. if(e == null)
  2659. return;
  2660. // NOTE: If I change this to NOT remove the descendants
  2661. // and update BasicTreeUIs treeStructureChanged method
  2662. // to update descendants in response to a treeStructureChanged
  2663. // event, all the children of the event won't collapse!
  2664. TreePath parent = e.getTreePath();
  2665. if(parent == null)
  2666. return;
  2667. if (parent.getPathCount() == 1) {
  2668. // New root, remove everything!
  2669. clearToggledPaths();
  2670. if(!treeModel.isLeaf(treeModel.getRoot())) {
  2671. // Mark the root as expanded, if it isn't a leaf.
  2672. expandedState.put(parent, Boolean.TRUE);
  2673. }
  2674. }
  2675. else if(expandedState.get(parent) != null) {
  2676. Vector toRemove = new Vector(1);
  2677. boolean isExpanded = isExpanded(parent);
  2678. toRemove.addElement(parent);
  2679. removeDescendantToggledPaths(toRemove.elements());
  2680. if(isExpanded) {
  2681. TreeModel model = getModel();
  2682. if(model == null || model.isLeaf
  2683. (parent.getLastPathComponent()))
  2684. collapsePath(parent);
  2685. else
  2686. expandedState.put(parent, Boolean.TRUE);
  2687. }
  2688. }
  2689. removeDescendantSelectedPaths(parent, false);
  2690. }
  2691. public void treeNodesRemoved(TreeModelEvent e) {
  2692. if(e == null)
  2693. return;
  2694. TreePath parent = e.getTreePath();
  2695. Object[] children = e.getChildren();
  2696. if(children == null)
  2697. return;
  2698. TreePath rPath;
  2699. Vector toRemove = new Vector(Math.max
  2700. (1, children.length));
  2701. for(int counter = children.length - 1; counter >= 0; counter--) {
  2702. rPath = parent.pathByAddingChild(children[counter]);
  2703. if(expandedState.get(rPath) != null)
  2704. toRemove.addElement(rPath);
  2705. }
  2706. if(toRemove.size() > 0)
  2707. removeDescendantToggledPaths(toRemove.elements());
  2708. TreeModel model = getModel();
  2709. if(model == null || model.isLeaf(parent.getLastPathComponent()))
  2710. expandedState.remove(parent);
  2711. removeDescendantSelectedPaths(e);
  2712. }
  2713. }
  2714. /**
  2715. * <code>DynamicUtilTreeNode</code> can wrap
  2716. * vectors/hashtables/arrays/strings and
  2717. * create the appropriate children tree nodes as necessary. It is
  2718. * dynamic in that it will only create the children as necessary.
  2719. * <p>
  2720. * <strong>Warning:</strong>
  2721. * Serialized objects of this class will not be compatible with
  2722. * future Swing releases. The current serialization support is appropriate
  2723. * for short term storage or RMI between applications running the same
  2724. * version of Swing. A future release of Swing will provide support for
  2725. * long term persistence.
  2726. */
  2727. public static class DynamicUtilTreeNode extends DefaultMutableTreeNode {
  2728. /**
  2729. * Does the this <code>JTree</code> have children?
  2730. * This property is currently not implemented.
  2731. */
  2732. protected boolean hasChildren;
  2733. /** Value to create children with. */
  2734. protected Object childValue;
  2735. /** Have the children been loaded yet? */
  2736. protected boolean loadedChildren;
  2737. /**
  2738. * Adds to parent all the children in <code>children</code>.
  2739. * If <code>children</code> is an array or vector all of its
  2740. * elements are added is children, otherwise if <code>children</code>
  2741. * is a hashtable all the key/value pairs are added in the order
  2742. * <code>Enumeration</code> returns them.
  2743. */
  2744. public static void createChildren(DefaultMutableTreeNode parent,
  2745. Object children) {
  2746. if(children instanceof Vector) {
  2747. Vector childVector = (Vector)children;
  2748. for(int counter = 0, maxCounter = childVector.size();
  2749. counter < maxCounter; counter++)
  2750. parent.add(new DynamicUtilTreeNode
  2751. (childVector.elementAt(counter),
  2752. childVector.elementAt(counter)));
  2753. }
  2754. else if(children instanceof Hashtable) {
  2755. Hashtable childHT = (Hashtable)children;
  2756. Enumeration keys = childHT.keys();
  2757. Object aKey;
  2758. while(keys.hasMoreElements()) {
  2759. aKey = keys.nextElement();
  2760. parent.add(new DynamicUtilTreeNode(aKey,
  2761. childHT.get(aKey)));
  2762. }
  2763. }
  2764. else if(children instanceof Object[]) {
  2765. Object[] childArray = (Object[])children;
  2766. for(int counter = 0, maxCounter = childArray.length;
  2767. counter < maxCounter; counter++)
  2768. parent.add(new DynamicUtilTreeNode(childArray[counter],
  2769. childArray[counter]));
  2770. }
  2771. }
  2772. /**
  2773. * Creates a node with the specified object as its value and
  2774. * with the specified children. For the node to allow children,
  2775. * the children-object must be an array of objects, a
  2776. * <code>Vector</code>, or a <code>Hashtable</code> -- even
  2777. * if empty. Otherwise, the node is not
  2778. * allowed to have children.
  2779. *
  2780. * @param value the <code>Object</code> that is the value for the
  2781. * new node
  2782. * @param children an array of <code>Object</code>s, a
  2783. * <code>Vector</code>, or a <code>Hashtable</code>
  2784. * used to create the child nodes; if any other
  2785. * object is specified, or if the value is
  2786. * <code>null</code>,
  2787. * then the node is not allowed to have children
  2788. */
  2789. public DynamicUtilTreeNode(Object value, Object children) {
  2790. super(value);
  2791. loadedChildren = false;
  2792. childValue = children;
  2793. if(children != null) {
  2794. if(children instanceof Vector)
  2795. setAllowsChildren(true);
  2796. else if(children instanceof Hashtable)
  2797. setAllowsChildren(true);
  2798. else if(children instanceof Object[])
  2799. setAllowsChildren(true);
  2800. else
  2801. setAllowsChildren(false);
  2802. }
  2803. else
  2804. setAllowsChildren(false);
  2805. }
  2806. /**
  2807. * Returns true if this node allows children. Whether the node
  2808. * allows children depends on how it was created.
  2809. *
  2810. * @return true if this node allows children, false otherwise
  2811. * @see #JTree.DynamicUtilTreeNode
  2812. */
  2813. public boolean isLeaf() {
  2814. return !getAllowsChildren();
  2815. }
  2816. /**
  2817. * Returns the number of child nodes.
  2818. *
  2819. * @return the number of child nodes
  2820. */
  2821. public int getChildCount() {
  2822. if(!loadedChildren)
  2823. loadChildren();
  2824. return super.getChildCount();
  2825. }
  2826. /**
  2827. * Loads the children based on <code>childValue</code>.
  2828. * If <code>childValue</code> is a <code>Vector</code>
  2829. * or array each element is added as a child,
  2830. * if <code>childValue</code> is a <code>Hashtable</code>
  2831. * each key/value pair is added in the order that
  2832. * <code>Enumeration</code> returns the keys.
  2833. */
  2834. protected void loadChildren() {
  2835. loadedChildren = true;
  2836. createChildren(this, childValue);
  2837. }
  2838. /**
  2839. * Subclassed to load the children, if necessary.
  2840. */
  2841. public TreeNode getChildAt(int index) {
  2842. if(!loadedChildren)
  2843. loadChildren();
  2844. return super.getChildAt(index);
  2845. }
  2846. /**
  2847. * Subclassed to load the children, if necessary.
  2848. */
  2849. public Enumeration children() {
  2850. if(!loadedChildren)
  2851. loadChildren();
  2852. return super.children();
  2853. }
  2854. }
  2855. /**
  2856. * Returns a string representation of this <code>JTree</code>.
  2857. * This method
  2858. * is intended to be used only for debugging purposes, and the
  2859. * content and format of the returned string may vary between
  2860. * implementations. The returned string may be empty but may not
  2861. * be <code>null</code>.
  2862. *
  2863. * @return a string representation of this <code>JTree</code>.
  2864. */
  2865. protected String paramString() {
  2866. String rootVisibleString = (rootVisible ?
  2867. "true" : "false");
  2868. String showsRootHandlesString = (showsRootHandles ?
  2869. "true" : "false");
  2870. String editableString = (editable ?
  2871. "true" : "false");
  2872. String largeModelString = (largeModel ?
  2873. "true" : "false");
  2874. String invokesStopCellEditingString = (invokesStopCellEditing ?
  2875. "true" : "false");
  2876. String scrollsOnExpandString = (scrollsOnExpand ?
  2877. "true" : "false");
  2878. return super.paramString() +
  2879. ",editable=" + editableString +
  2880. ",invokesStopCellEditing=" + invokesStopCellEditingString +
  2881. ",largeModel=" + largeModelString +
  2882. ",rootVisible=" + rootVisibleString +
  2883. ",rowHeight=" + rowHeight +
  2884. ",scrollsOnExpand=" + scrollsOnExpandString +
  2885. ",showsRootHandles=" + showsRootHandlesString +
  2886. ",toggleClickCount=" + toggleClickCount +
  2887. ",visibleRowCount=" + visibleRowCount;
  2888. }
  2889. /////////////////
  2890. // Accessibility support
  2891. ////////////////
  2892. /**
  2893. * Gets the AccessibleContext associated with this JTree.
  2894. * For JTrees, the AccessibleContext takes the form of an
  2895. * AccessibleJTree.
  2896. * A new AccessibleJTree instance is created if necessary.
  2897. *
  2898. * @return an AccessibleJTree that serves as the
  2899. * AccessibleContext of this JTree
  2900. */
  2901. public AccessibleContext getAccessibleContext() {
  2902. if (accessibleContext == null) {
  2903. accessibleContext = new AccessibleJTree();
  2904. }
  2905. return accessibleContext;
  2906. }
  2907. /**
  2908. * This class implements accessibility support for the
  2909. * <code>JTree</code> class. It provides an implementation of the
  2910. * Java Accessibility API appropriate to tree user-interface elements.
  2911. * <p>
  2912. * <strong>Warning:</strong>
  2913. * Serialized objects of this class will not be compatible with
  2914. * future Swing releases. The current serialization support is appropriate
  2915. * for short term storage or RMI between applications running the same
  2916. * version of Swing. A future release of Swing will provide support for
  2917. * long term persistence.
  2918. */
  2919. protected class AccessibleJTree extends AccessibleJComponent
  2920. implements AccessibleSelection, TreeSelectionListener,
  2921. TreeModelListener, TreeExpansionListener {
  2922. TreePath leadSelectionPath;
  2923. Accessible leadSelectionAccessible;
  2924. public AccessibleJTree() {
  2925. // Add a tree model listener for JTree
  2926. JTree.this.getModel().addTreeModelListener(this);
  2927. JTree.this.addTreeExpansionListener(this);
  2928. JTree.this.addTreeSelectionListener(this);
  2929. leadSelectionPath = JTree.this.getLeadSelectionPath();
  2930. leadSelectionAccessible = (leadSelectionPath != null)
  2931. ? new AccessibleJTreeNode(JTree.this,
  2932. leadSelectionPath,
  2933. JTree.this)
  2934. : null;
  2935. }
  2936. /**
  2937. * Tree Selection Listener value change method. Used to fire the
  2938. * property change
  2939. *
  2940. * @param e ListSelectionEvent
  2941. *
  2942. */
  2943. public void valueChanged(TreeSelectionEvent e) {
  2944. TreePath oldLeadSelectionPath = leadSelectionPath;
  2945. leadSelectionPath = JTree.this.getLeadSelectionPath();
  2946. if (oldLeadSelectionPath != leadSelectionPath) {
  2947. Accessible oldLSA = leadSelectionAccessible;
  2948. leadSelectionAccessible = (leadSelectionPath != null)
  2949. ? new AccessibleJTreeNode(JTree.this,
  2950. leadSelectionPath,
  2951. JTree.this)
  2952. : null;
  2953. firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
  2954. oldLSA, leadSelectionAccessible);
  2955. }
  2956. firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
  2957. new Boolean(false), new Boolean(true));
  2958. }
  2959. /**
  2960. * Fire a visible data property change notification.
  2961. * A 'visible' data property is one that represents
  2962. * something about the way the component appears on the
  2963. * display, where that appearance isn't bound to any other
  2964. * property. It notifies screen readers that the visual
  2965. * appearance of the component has changed, so they can
  2966. * notify the user.
  2967. */
  2968. public void fireVisibleDataPropertyChange() {
  2969. firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
  2970. new Boolean(false), new Boolean(true));
  2971. }
  2972. // Fire the visible data changes for the model changes.
  2973. /**
  2974. * Tree Model Node change notification.
  2975. *
  2976. * @param e a Tree Model event
  2977. */
  2978. public void treeNodesChanged(TreeModelEvent e) {
  2979. fireVisibleDataPropertyChange();
  2980. }
  2981. /**
  2982. * Tree Model Node change notification.
  2983. *
  2984. * @param e a Tree node insertion event
  2985. */
  2986. public void treeNodesInserted(TreeModelEvent e) {
  2987. fireVisibleDataPropertyChange();
  2988. }
  2989. /**
  2990. * Tree Model Node change notification.
  2991. *
  2992. * @param e a Tree node(s) removal event
  2993. */
  2994. public void treeNodesRemoved(TreeModelEvent e) {
  2995. fireVisibleDataPropertyChange();
  2996. }
  2997. /**
  2998. * Tree Model structure change change notification.
  2999. *
  3000. * @param e a Tree Model event
  3001. */
  3002. public void treeStructureChanged(TreeModelEvent e) {
  3003. fireVisibleDataPropertyChange();
  3004. }
  3005. /**
  3006. * Tree Collapsed notification.
  3007. *
  3008. * @param e a TreeExpansionEvent
  3009. */
  3010. public void treeCollapsed(TreeExpansionEvent e) {
  3011. fireVisibleDataPropertyChange();
  3012. firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  3013. AccessibleState.EXPANDED,
  3014. AccessibleState.COLLAPSED);
  3015. }
  3016. /**
  3017. * Tree Model Expansion notification.
  3018. *
  3019. * @param e a Tree node insertion event
  3020. */
  3021. public void treeExpanded(TreeExpansionEvent e) {
  3022. fireVisibleDataPropertyChange();
  3023. firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
  3024. AccessibleState.COLLAPSED,
  3025. AccessibleState.EXPANDED);
  3026. }
  3027. private AccessibleContext getCurrentAccessibleContext() {
  3028. Component c = getCurrentComponent();
  3029. if (c instanceof Accessible) {
  3030. return (((Accessible) c).getAccessibleContext());
  3031. } else {
  3032. return null;
  3033. }
  3034. }
  3035. private Component getCurrentComponent() {
  3036. // is the object visible?
  3037. // if so, get row, selected, focus & leaf state,
  3038. // and then get the renderer component and return it
  3039. TreeModel model = JTree.this.getModel();
  3040. TreePath path = new TreePath(model.getRoot());
  3041. if (JTree.this.isVisible(path)) {
  3042. TreeCellRenderer r = JTree.this.getCellRenderer();
  3043. TreeUI ui = JTree.this.getUI();
  3044. if (ui != null) {
  3045. int row = ui.getRowForPath(JTree.this, path);
  3046. int lsr = JTree.this.getLeadSelectionRow();
  3047. boolean hasFocus = JTree.this.hasFocus()
  3048. && (lsr == row);
  3049. boolean selected = JTree.this.isPathSelected(path);
  3050. boolean expanded = JTree.this.isExpanded(path);
  3051. return r.getTreeCellRendererComponent(JTree.this,
  3052. model.getRoot(), selected, expanded,
  3053. model.isLeaf(model.getRoot()), row, hasFocus);
  3054. }
  3055. }
  3056. return null;
  3057. }
  3058. // Overridden methods from AccessibleJComponent
  3059. /**
  3060. * Get the role of this object.
  3061. *
  3062. * @return an instance of AccessibleRole describing the role of the
  3063. * object
  3064. * @see AccessibleRole
  3065. */
  3066. public AccessibleRole getAccessibleRole() {
  3067. return AccessibleRole.TREE;
  3068. }
  3069. /**
  3070. * Returns the Accessible child, if one exists, contained at the local
  3071. * coordinate Point.
  3072. *
  3073. * @param p point in local coordinates of this Accessible
  3074. * @return the Accessible, if it exists, at the specified location;
  3075. * else null
  3076. */
  3077. public Accessible getAccessibleAt(Point p) {
  3078. TreePath path = getClosestPathForLocation(p.x, p.y);
  3079. if (path != null) {
  3080. // JTree.this is NOT the parent; parent will get computed later
  3081. return new AccessibleJTreeNode(JTree.this, path, null);
  3082. } else {
  3083. return null;
  3084. }
  3085. }
  3086. /**
  3087. * Returns the number of top-level children nodes of this
  3088. * JTree. Each of these nodes may in turn have children nodes.
  3089. *
  3090. * @return the number of accessible children nodes in the tree.
  3091. */
  3092. public int getAccessibleChildrenCount() {
  3093. TreeModel model = JTree.this.getModel();
  3094. if (model != null) {
  3095. return 1;
  3096. } else {
  3097. return 0;
  3098. }
  3099. }
  3100. /**
  3101. * Return the nth Accessible child of the object.
  3102. *
  3103. * @param i zero-based index of child
  3104. * @return the nth Accessible child of the object
  3105. */
  3106. public Accessible getAccessibleChild(int i) {
  3107. TreeModel model = JTree.this.getModel();
  3108. if (model != null) {
  3109. if (i != 0) {
  3110. return null;
  3111. } else {
  3112. Object[] objPath = {model.getRoot()};
  3113. TreePath path = new TreePath(objPath);
  3114. return new AccessibleJTreeNode(JTree.this, path,
  3115. JTree.this);
  3116. }
  3117. }
  3118. return null;
  3119. }
  3120. /**
  3121. * Get the index of this object in its accessible parent.
  3122. *
  3123. * @return the index of this object in its parent. Since a JTree
  3124. * top-level object does not have an accessible parent.
  3125. * @see #getAccessibleParent
  3126. */
  3127. public int getAccessibleIndexInParent() {
  3128. // didn't ever need to override this...
  3129. return super.getAccessibleIndexInParent();
  3130. }
  3131. // AccessibleSelection methods
  3132. /**
  3133. * Get the AccessibleSelection associated with this object. In the
  3134. * implementation of the Java Accessibility API for this class,
  3135. * return this object, which is responsible for implementing the
  3136. * AccessibleSelection interface on behalf of itself.
  3137. *
  3138. * @return this object
  3139. */
  3140. public AccessibleSelection getAccessibleSelection() {
  3141. return this;
  3142. }
  3143. /**
  3144. * Returns the number of items currently selected.
  3145. * If no items are selected, the return value will be 0.
  3146. *
  3147. * @return the number of items currently selected.
  3148. */
  3149. public int getAccessibleSelectionCount() {
  3150. Object[] rootPath = new Object[1];
  3151. rootPath[0] = treeModel.getRoot();
  3152. TreePath childPath = new TreePath(rootPath);
  3153. if (JTree.this.isPathSelected(childPath)) {
  3154. return 1;
  3155. } else {
  3156. return 0;
  3157. }
  3158. }
  3159. /**
  3160. * Returns an Accessible representing the specified selected item
  3161. * in the object. If there isn't a selection, or there are
  3162. * fewer items selected than the integer passed in, the return
  3163. * value will be null.
  3164. *
  3165. * @param i the zero-based index of selected items
  3166. * @return an Accessible containing the selected item
  3167. */
  3168. public Accessible getAccessibleSelection(int i) {
  3169. if (i == 0) {
  3170. Object[] rootPath = new Object[1];
  3171. rootPath[0] = treeModel.getRoot();
  3172. TreePath childPath = new TreePath(rootPath);
  3173. if (JTree.this.isPathSelected(childPath)) {
  3174. return new AccessibleJTreeNode(JTree.this, childPath, JTree.this);
  3175. }
  3176. }
  3177. return null;
  3178. }
  3179. /**
  3180. * Returns true if the current child of this object is selected.
  3181. *
  3182. * @param i the zero-based index of the child in this Accessible object.
  3183. * @see AccessibleContext#getAccessibleChild
  3184. */
  3185. public boolean isAccessibleChildSelected(int i) {
  3186. TreePath[] paths = JTree.this.getSelectionPaths();
  3187. TreeModel treeModel = JTree.this.getModel();
  3188. Object o;
  3189. for (int j = 0; j < paths.length; j++) {
  3190. o = paths[j].getLastPathComponent();
  3191. if (i == treeModel.getIndexOfChild(treeModel.getRoot(), o)) {
  3192. return true;
  3193. }
  3194. }
  3195. return false;
  3196. }
  3197. /**
  3198. * Adds the specified selected item in the object to the object's
  3199. * selection. If the object supports multiple selections,
  3200. * the specified item is added to any existing selection, otherwise
  3201. * it replaces any existing selection in the object. If the
  3202. * specified item is already selected, this method has no effect.
  3203. *
  3204. * @param i the zero-based index of selectable items
  3205. */
  3206. public void addAccessibleSelection(int i) {
  3207. TreeModel model = JTree.this.getModel();
  3208. if (model != null) {
  3209. if (i == 0) {
  3210. Object[] objPath = {model.getRoot()};
  3211. TreePath path = new TreePath(objPath);
  3212. JTree.this.addSelectionPath(path);
  3213. }
  3214. }
  3215. }
  3216. /**
  3217. * Removes the specified selected item in the object from the object's
  3218. * selection. If the specified item isn't currently selected, this
  3219. * method has no effect.
  3220. *
  3221. * @param i the zero-based index of selectable items
  3222. */
  3223. public void removeAccessibleSelection(int i) {
  3224. TreeModel model = JTree.this.getModel();
  3225. if (model != null) {
  3226. if (i == 0) {
  3227. Object[] objPath = {model.getRoot()};
  3228. TreePath path = new TreePath(objPath);
  3229. JTree.this.removeSelectionPath(path);
  3230. }
  3231. }
  3232. }
  3233. /**
  3234. * Clears the selection in the object, so that nothing in the
  3235. * object is selected.
  3236. */
  3237. public void clearAccessibleSelection() {
  3238. int childCount = getAccessibleChildrenCount();
  3239. for (int i = 0; i < childCount; i++) {
  3240. removeAccessibleSelection(i);
  3241. }
  3242. }
  3243. /**
  3244. * Causes every selected item in the object to be selected
  3245. * if the object supports multiple selections.
  3246. */
  3247. public void selectAllAccessibleSelection() {
  3248. TreeModel model = JTree.this.getModel();
  3249. if (model != null) {
  3250. Object[] objPath = {model.getRoot()};
  3251. TreePath path = new TreePath(objPath);
  3252. JTree.this.addSelectionPath(path);
  3253. }
  3254. }
  3255. /**
  3256. * This class implements accessibility support for the
  3257. * <code>JTree</code> child. It provides an implementation of the
  3258. * Java Accessibility API appropriate to tree nodes.
  3259. */
  3260. protected class AccessibleJTreeNode extends AccessibleContext
  3261. implements Accessible, AccessibleComponent, AccessibleSelection,
  3262. AccessibleAction {
  3263. private JTree tree = null;
  3264. private TreeModel treeModel = null;
  3265. private Object obj = null;
  3266. private TreePath path = null;
  3267. private Accessible accessibleParent = null;
  3268. private int index = 0;
  3269. private boolean isLeaf = false;
  3270. /**
  3271. * Constructs an AccessibleJTreeNode
  3272. */
  3273. public AccessibleJTreeNode(JTree t, TreePath p, Accessible ap) {
  3274. tree = t;
  3275. path = p;
  3276. accessibleParent = ap;
  3277. treeModel = t.getModel();
  3278. obj = p.getLastPathComponent();
  3279. if (treeModel != null) {
  3280. isLeaf = treeModel.isLeaf(obj);
  3281. }
  3282. }
  3283. private TreePath getChildTreePath(int i) {
  3284. // Tree nodes can't be so complex that they have
  3285. // two sets of children -> we're ignoring that case
  3286. if (i < 0 || i >= getAccessibleChildrenCount()) {
  3287. return null;
  3288. } else {
  3289. Object childObj = treeModel.getChild(obj, i);
  3290. Object[] objPath = path.getPath();
  3291. Object[] objChildPath = new Object[objPath.length+1];
  3292. java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
  3293. objChildPath[objChildPath.length-1] = childObj;
  3294. return new TreePath(objChildPath);
  3295. }
  3296. }
  3297. /**
  3298. * Get the AccessibleContext associated with this tree node.
  3299. * In the implementation of the Java Accessibility API for
  3300. * this class, return this object, which is its own
  3301. * AccessibleContext.
  3302. *
  3303. * @return this object
  3304. */
  3305. public AccessibleContext getAccessibleContext() {
  3306. return this;
  3307. }
  3308. private AccessibleContext getCurrentAccessibleContext() {
  3309. Component c = getCurrentComponent();
  3310. if (c instanceof Accessible) {
  3311. return (((Accessible) c).getAccessibleContext());
  3312. } else {
  3313. return null;
  3314. }
  3315. }
  3316. private Component getCurrentComponent() {
  3317. // is the object visible?
  3318. // if so, get row, selected, focus & leaf state,
  3319. // and then get the renderer component and return it
  3320. if (tree.isVisible(path)) {
  3321. TreeCellRenderer r = tree.getCellRenderer();
  3322. if (r == null) {
  3323. return null;
  3324. }
  3325. TreeUI ui = tree.getUI();
  3326. if (ui != null) {
  3327. int row = ui.getRowForPath(JTree.this, path);
  3328. boolean selected = tree.isPathSelected(path);
  3329. boolean expanded = tree.isExpanded(path);
  3330. boolean hasFocus = false; // how to tell?? -PK
  3331. return r.getTreeCellRendererComponent(tree, obj,
  3332. selected, expanded, isLeaf, row, hasFocus);
  3333. }
  3334. }
  3335. return null;
  3336. }
  3337. // AccessibleContext methods
  3338. /**
  3339. * Get the accessible name of this object.
  3340. *
  3341. * @return the localized name of the object; null if this
  3342. * object does not have a name
  3343. */
  3344. public String getAccessibleName() {
  3345. AccessibleContext ac = getCurrentAccessibleContext();
  3346. if (ac != null) {
  3347. String name = ac.getAccessibleName();
  3348. if ((name != null) && (name != "")) {
  3349. return ac.getAccessibleName();
  3350. } else {
  3351. return null;
  3352. }
  3353. }
  3354. if ((accessibleName != null) && (accessibleName != "")) {
  3355. return accessibleName;
  3356. } else {
  3357. return null;
  3358. }
  3359. }
  3360. /**
  3361. * Set the localized accessible name of this object.
  3362. *
  3363. * @param s the new localized name of the object.
  3364. */
  3365. public void setAccessibleName(String s) {
  3366. AccessibleContext ac = getCurrentAccessibleContext();
  3367. if (ac != null) {
  3368. ac.setAccessibleName(s);
  3369. } else {
  3370. super.setAccessibleName(s);
  3371. }
  3372. }
  3373. //
  3374. // *** should check tooltip text for desc. (needs MouseEvent)
  3375. //
  3376. /**
  3377. * Get the accessible description of this object.
  3378. *
  3379. * @return the localized description of the object; null if
  3380. * this object does not have a description
  3381. */
  3382. public String getAccessibleDescription() {
  3383. AccessibleContext ac = getCurrentAccessibleContext();
  3384. if (ac != null) {
  3385. return ac.getAccessibleDescription();
  3386. } else {
  3387. return super.getAccessibleDescription();
  3388. }
  3389. }
  3390. /**
  3391. * Set the accessible description of this object.
  3392. *
  3393. * @param s the new localized description of the object
  3394. */
  3395. public void setAccessibleDescription(String s) {
  3396. AccessibleContext ac = getCurrentAccessibleContext();
  3397. if (ac != null) {
  3398. ac.setAccessibleDescription(s);
  3399. } else {
  3400. super.setAccessibleDescription(s);
  3401. }
  3402. }
  3403. /**
  3404. * Get the role of this object.
  3405. *
  3406. * @return an instance of AccessibleRole describing the role of the object
  3407. * @see AccessibleRole
  3408. */
  3409. public AccessibleRole getAccessibleRole() {
  3410. AccessibleContext ac = getCurrentAccessibleContext();
  3411. if (ac != null) {
  3412. return ac.getAccessibleRole();
  3413. } else {
  3414. return AccessibleRole.UNKNOWN;
  3415. }
  3416. }
  3417. /**
  3418. * Get the state set of this object.
  3419. *
  3420. * @return an instance of AccessibleStateSet containing the
  3421. * current state set of the object
  3422. * @see AccessibleState
  3423. */
  3424. public AccessibleStateSet getAccessibleStateSet() {
  3425. AccessibleContext ac = getCurrentAccessibleContext();
  3426. AccessibleStateSet states;
  3427. int row = tree.getUI().getRowForPath(tree,path);
  3428. int lsr = tree.getLeadSelectionRow();
  3429. if (ac != null) {
  3430. states = ac.getAccessibleStateSet();
  3431. } else {
  3432. states = new AccessibleStateSet();
  3433. }
  3434. // need to test here, 'cause the underlying component
  3435. // is a cellRenderer, which is never showing...
  3436. if (isShowing()) {
  3437. states.add(AccessibleState.SHOWING);
  3438. } else if (states.contains(AccessibleState.SHOWING)) {
  3439. states.remove(AccessibleState.SHOWING);
  3440. }
  3441. if (isVisible()) {
  3442. states.add(AccessibleState.VISIBLE);
  3443. } else if (states.contains(AccessibleState.VISIBLE)) {
  3444. states.remove(AccessibleState.VISIBLE);
  3445. }
  3446. if (tree.isPathSelected(path)){
  3447. states.add(AccessibleState.SELECTED);
  3448. }
  3449. if (lsr == row) {
  3450. states.add(AccessibleState.ACTIVE);
  3451. }
  3452. if (!isLeaf) {
  3453. states.add(AccessibleState.EXPANDABLE);
  3454. }
  3455. if (tree.isExpanded(path)) {
  3456. states.add(AccessibleState.EXPANDED);
  3457. } else {
  3458. states.add(AccessibleState.COLLAPSED);
  3459. }
  3460. if (tree.isEditable()) {
  3461. states.add(AccessibleState.EDITABLE);
  3462. }
  3463. return states;
  3464. }
  3465. /**
  3466. * Get the Accessible parent of this object.
  3467. *
  3468. * @return the Accessible parent of this object; null if this
  3469. * object does not have an Accessible parent
  3470. */
  3471. public Accessible getAccessibleParent() {
  3472. // someone wants to know, so we need to create our parent
  3473. // if we don't have one (hey, we're a talented kid!)
  3474. if (accessibleParent == null) {
  3475. Object[] objPath = path.getPath();
  3476. if (objPath.length > 1) {
  3477. Object objParent = objPath[objPath.length-2];
  3478. if (treeModel != null) {
  3479. index = treeModel.getIndexOfChild(objParent, obj);
  3480. }
  3481. Object[] objParentPath = new Object[objPath.length-1];
  3482. java.lang.System.arraycopy(objPath, 0, objParentPath,
  3483. 0, objPath.length-1);
  3484. TreePath parentPath = new TreePath(objParentPath);
  3485. accessibleParent = new AccessibleJTreeNode(tree,
  3486. parentPath,
  3487. null);
  3488. this.setAccessibleParent(accessibleParent);
  3489. } else if (treeModel != null) {
  3490. accessibleParent = tree; // we're the top!
  3491. index = 0; // we're an only child!
  3492. this.setAccessibleParent(accessibleParent);
  3493. }
  3494. }
  3495. return accessibleParent;
  3496. }
  3497. /**
  3498. * Get the index of this object in its accessible parent.
  3499. *
  3500. * @return the index of this object in its parent; -1 if this
  3501. * object does not have an accessible parent.
  3502. * @see #getAccessibleParent
  3503. */
  3504. public int getAccessibleIndexInParent() {
  3505. // index is invalid 'till we have an accessibleParent...
  3506. if (accessibleParent == null) {
  3507. getAccessibleParent();
  3508. }
  3509. Object[] objPath = path.getPath();
  3510. if (objPath.length > 1) {
  3511. Object objParent = objPath[objPath.length-2];
  3512. if (treeModel != null) {
  3513. index = treeModel.getIndexOfChild(objParent, obj);
  3514. }
  3515. }
  3516. return index;
  3517. }
  3518. /**
  3519. * Returns the number of accessible children in the object.
  3520. *
  3521. * @return the number of accessible children in the object.
  3522. */
  3523. public int getAccessibleChildrenCount() {
  3524. // Tree nodes can't be so complex that they have
  3525. // two sets of children -> we're ignoring that case
  3526. return treeModel.getChildCount(obj);
  3527. }
  3528. /**
  3529. * Return the specified Accessible child of the object.
  3530. *
  3531. * @param i zero-based index of child
  3532. * @return the Accessible child of the object
  3533. */
  3534. public Accessible getAccessibleChild(int i) {
  3535. // Tree nodes can't be so complex that they have
  3536. // two sets of children -> we're ignoring that case
  3537. if (i < 0 || i >= getAccessibleChildrenCount()) {
  3538. return null;
  3539. } else {
  3540. Object childObj = treeModel.getChild(obj, i);
  3541. Object[] objPath = path.getPath();
  3542. Object[] objChildPath = new Object[objPath.length+1];
  3543. java.lang.System.arraycopy(objPath, 0, objChildPath, 0, objPath.length);
  3544. objChildPath[objChildPath.length-1] = childObj;
  3545. TreePath childPath = new TreePath(objChildPath);
  3546. return new AccessibleJTreeNode(JTree.this, childPath, this);
  3547. }
  3548. }
  3549. /**
  3550. * Gets the locale of the component. If the component does not have
  3551. * a locale, then the locale of its parent is returned.
  3552. *
  3553. * @return This component's locale. If this component does not have
  3554. * a locale, the locale of its parent is returned.
  3555. * @exception IllegalComponentStateException
  3556. * If the Component does not have its own locale and has not yet
  3557. * been added to a containment hierarchy such that the locale can be
  3558. * determined from the containing parent.
  3559. * @see #setLocale
  3560. */
  3561. public Locale getLocale() {
  3562. AccessibleContext ac = getCurrentAccessibleContext();
  3563. if (ac != null) {
  3564. return ac.getLocale();
  3565. } else {
  3566. return tree.getLocale();
  3567. }
  3568. }
  3569. /**
  3570. * Add a PropertyChangeListener to the listener list.
  3571. * The listener is registered for all properties.
  3572. *
  3573. * @param listener The PropertyChangeListener to be added
  3574. */
  3575. public void addPropertyChangeListener(PropertyChangeListener l) {
  3576. AccessibleContext ac = getCurrentAccessibleContext();
  3577. if (ac != null) {
  3578. ac.addPropertyChangeListener(l);
  3579. } else {
  3580. super.addPropertyChangeListener(l);
  3581. }
  3582. }
  3583. /**
  3584. * Remove a PropertyChangeListener from the listener list.
  3585. * This removes a PropertyChangeListener that was registered
  3586. * for all properties.
  3587. *
  3588. * @param listener The PropertyChangeListener to be removed
  3589. */
  3590. public void removePropertyChangeListener(PropertyChangeListener l) {
  3591. AccessibleContext ac = getCurrentAccessibleContext();
  3592. if (ac != null) {
  3593. ac.removePropertyChangeListener(l);
  3594. } else {
  3595. super.removePropertyChangeListener(l);
  3596. }
  3597. }
  3598. /**
  3599. * Get the AccessibleAction associated with this object. In the
  3600. * implementation of the Java Accessibility API for this class,
  3601. * return this object, which is responsible for implementing the
  3602. * AccessibleAction interface on behalf of itself.
  3603. *
  3604. * @return this object
  3605. */
  3606. public AccessibleAction getAccessibleAction() {
  3607. return this;
  3608. }
  3609. /**
  3610. * Get the AccessibleComponent associated with this object. In the
  3611. * implementation of the Java Accessibility API for this class,
  3612. * return this object, which is responsible for implementing the
  3613. * AccessibleComponent interface on behalf of itself.
  3614. *
  3615. * @return this object
  3616. */
  3617. public AccessibleComponent getAccessibleComponent() {
  3618. return this; // to override getBounds()
  3619. }
  3620. /**
  3621. * Get the AccessibleSelection associated with this object if one
  3622. * exists. Otherwise return null.
  3623. *
  3624. * @return the AccessibleSelection, or null
  3625. */
  3626. public AccessibleSelection getAccessibleSelection() {
  3627. AccessibleContext ac = getCurrentAccessibleContext();
  3628. if (ac != null && isLeaf) {
  3629. return getCurrentAccessibleContext().getAccessibleSelection();
  3630. } else {
  3631. return this;
  3632. }
  3633. }
  3634. /**
  3635. * Get the AccessibleText associated with this object if one
  3636. * exists. Otherwise return null.
  3637. *
  3638. * @return the AccessibleText, or null
  3639. */
  3640. public AccessibleText getAccessibleText() {
  3641. AccessibleContext ac = getCurrentAccessibleContext();
  3642. if (ac != null) {
  3643. return getCurrentAccessibleContext().getAccessibleText();
  3644. } else {
  3645. return null;
  3646. }
  3647. }
  3648. /**
  3649. * Get the AccessibleValue associated with this object if one
  3650. * exists. Otherwise return null.
  3651. *
  3652. * @return the AccessibleValue, or null
  3653. */
  3654. public AccessibleValue getAccessibleValue() {
  3655. AccessibleContext ac = getCurrentAccessibleContext();
  3656. if (ac != null) {
  3657. return getCurrentAccessibleContext().getAccessibleValue();
  3658. } else {
  3659. return null;
  3660. }
  3661. }
  3662. // AccessibleComponent methods
  3663. /**
  3664. * Get the background color of this object.
  3665. *
  3666. * @return the background color, if supported, of the object;
  3667. * otherwise, null
  3668. */
  3669. public Color getBackground() {
  3670. AccessibleContext ac = getCurrentAccessibleContext();
  3671. if (ac instanceof AccessibleComponent) {
  3672. return ((AccessibleComponent) ac).getBackground();
  3673. } else {
  3674. Component c = getCurrentComponent();
  3675. if (c != null) {
  3676. return c.getBackground();
  3677. } else {
  3678. return null;
  3679. }
  3680. }
  3681. }
  3682. /**
  3683. * Set the background color of this object.
  3684. *
  3685. * @param c the new Color for the background
  3686. */
  3687. public void setBackground(Color c) {
  3688. AccessibleContext ac = getCurrentAccessibleContext();
  3689. if (ac instanceof AccessibleComponent) {
  3690. ((AccessibleComponent) ac).setBackground(c);
  3691. } else {
  3692. Component cp = getCurrentComponent();
  3693. if (cp != null) {
  3694. cp.setBackground(c);
  3695. }
  3696. }
  3697. }
  3698. /**
  3699. * Get the foreground color of this object.
  3700. *
  3701. * @return the foreground color, if supported, of the object;
  3702. * otherwise, null
  3703. */
  3704. public Color getForeground() {
  3705. AccessibleContext ac = getCurrentAccessibleContext();
  3706. if (ac instanceof AccessibleComponent) {
  3707. return ((AccessibleComponent) ac).getForeground();
  3708. } else {
  3709. Component c = getCurrentComponent();
  3710. if (c != null) {
  3711. return c.getForeground();
  3712. } else {
  3713. return null;
  3714. }
  3715. }
  3716. }
  3717. public void setForeground(Color c) {
  3718. AccessibleContext ac = getCurrentAccessibleContext();
  3719. if (ac instanceof AccessibleComponent) {
  3720. ((AccessibleComponent) ac).setForeground(c);
  3721. } else {
  3722. Component cp = getCurrentComponent();
  3723. if (cp != null) {
  3724. cp.setForeground(c);
  3725. }
  3726. }
  3727. }
  3728. public Cursor getCursor() {
  3729. AccessibleContext ac = getCurrentAccessibleContext();
  3730. if (ac instanceof AccessibleComponent) {
  3731. return ((AccessibleComponent) ac).getCursor();
  3732. } else {
  3733. Component c = getCurrentComponent();
  3734. if (c != null) {
  3735. return c.getCursor();
  3736. } else {
  3737. Accessible ap = getAccessibleParent();
  3738. if (ap instanceof AccessibleComponent) {
  3739. return ((AccessibleComponent) ap).getCursor();
  3740. } else {
  3741. return null;
  3742. }
  3743. }
  3744. }
  3745. }
  3746. public void setCursor(Cursor c) {
  3747. AccessibleContext ac = getCurrentAccessibleContext();
  3748. if (ac instanceof AccessibleComponent) {
  3749. ((AccessibleComponent) ac).setCursor(c);
  3750. } else {
  3751. Component cp = getCurrentComponent();
  3752. if (cp != null) {
  3753. cp.setCursor(c);
  3754. }
  3755. }
  3756. }
  3757. public Font getFont() {
  3758. AccessibleContext ac = getCurrentAccessibleContext();
  3759. if (ac instanceof AccessibleComponent) {
  3760. return ((AccessibleComponent) ac).getFont();
  3761. } else {
  3762. Component c = getCurrentComponent();
  3763. if (c != null) {
  3764. return c.getFont();
  3765. } else {
  3766. return null;
  3767. }
  3768. }
  3769. }
  3770. public void setFont(Font f) {
  3771. AccessibleContext ac = getCurrentAccessibleContext();
  3772. if (ac instanceof AccessibleComponent) {
  3773. ((AccessibleComponent) ac).setFont(f);
  3774. } else {
  3775. Component c = getCurrentComponent();
  3776. if (c != null) {
  3777. c.setFont(f);
  3778. }
  3779. }
  3780. }
  3781. public FontMetrics getFontMetrics(Font f) {
  3782. AccessibleContext ac = getCurrentAccessibleContext();
  3783. if (ac instanceof AccessibleComponent) {
  3784. return ((AccessibleComponent) ac).getFontMetrics(f);
  3785. } else {
  3786. Component c = getCurrentComponent();
  3787. if (c != null) {
  3788. return c.getFontMetrics(f);
  3789. } else {
  3790. return null;
  3791. }
  3792. }
  3793. }
  3794. public boolean isEnabled() {
  3795. AccessibleContext ac = getCurrentAccessibleContext();
  3796. if (ac instanceof AccessibleComponent) {
  3797. return ((AccessibleComponent) ac).isEnabled();
  3798. } else {
  3799. Component c = getCurrentComponent();
  3800. if (c != null) {
  3801. return c.isEnabled();
  3802. } else {
  3803. return false;
  3804. }
  3805. }
  3806. }
  3807. public void setEnabled(boolean b) {
  3808. AccessibleContext ac = getCurrentAccessibleContext();
  3809. if (ac instanceof AccessibleComponent) {
  3810. ((AccessibleComponent) ac).setEnabled(b);
  3811. } else {
  3812. Component c = getCurrentComponent();
  3813. if (c != null) {
  3814. c.setEnabled(b);
  3815. }
  3816. }
  3817. }
  3818. public boolean isVisible() {
  3819. Rectangle pathBounds = tree.getPathBounds(path);
  3820. Rectangle parentBounds = tree.getVisibleRect();
  3821. if (pathBounds != null && parentBounds != null &&
  3822. parentBounds.intersects(pathBounds)) {
  3823. return true;
  3824. } else {
  3825. return false;
  3826. }
  3827. }
  3828. public void setVisible(boolean b) {
  3829. }
  3830. public boolean isShowing() {
  3831. return (tree.isShowing() && isVisible());
  3832. }
  3833. public boolean contains(Point p) {
  3834. AccessibleContext ac = getCurrentAccessibleContext();
  3835. if (ac instanceof AccessibleComponent) {
  3836. Rectangle r = ((AccessibleComponent) ac).getBounds();
  3837. return r.contains(p);
  3838. } else {
  3839. Component c = getCurrentComponent();
  3840. if (c != null) {
  3841. Rectangle r = c.getBounds();
  3842. return r.contains(p);
  3843. } else {
  3844. return getBounds().contains(p);
  3845. }
  3846. }
  3847. }
  3848. public Point getLocationOnScreen() {
  3849. if (tree != null) {
  3850. Point parentLocation = tree.getLocationOnScreen();
  3851. Point componentLocation = getLocation();
  3852. componentLocation.translate(parentLocation.x, parentLocation.y);
  3853. return componentLocation;
  3854. } else {
  3855. return null;
  3856. }
  3857. }
  3858. protected Point getLocationInJTree() {
  3859. Rectangle r = tree.getPathBounds(path);
  3860. if (r != null) {
  3861. return r.getLocation();
  3862. } else {
  3863. return null;
  3864. }
  3865. }
  3866. public Point getLocation() {
  3867. Rectangle r = getBounds();
  3868. if (r != null) {
  3869. return r.getLocation();
  3870. } else {
  3871. return null;
  3872. }
  3873. }
  3874. public void setLocation(Point p) {
  3875. }
  3876. public Rectangle getBounds() {
  3877. Rectangle r = tree.getPathBounds(path);
  3878. Accessible parent = getAccessibleParent();
  3879. if (parent != null) {
  3880. if (parent instanceof AccessibleJTreeNode) {
  3881. Point parentLoc = ((AccessibleJTreeNode) parent).getLocationInJTree();
  3882. if (parentLoc != null && r != null) {
  3883. r.translate(-parentLoc.x, -parentLoc.y);
  3884. } else {
  3885. return null; // not visible!
  3886. }
  3887. }
  3888. }
  3889. return r;
  3890. }
  3891. public void setBounds(Rectangle r) {
  3892. AccessibleContext ac = getCurrentAccessibleContext();
  3893. if (ac instanceof AccessibleComponent) {
  3894. ((AccessibleComponent) ac).setBounds(r);
  3895. } else {
  3896. Component c = getCurrentComponent();
  3897. if (c != null) {
  3898. c.setBounds(r);
  3899. }
  3900. }
  3901. }
  3902. public Dimension getSize() {
  3903. return getBounds().getSize();
  3904. }
  3905. public void setSize (Dimension d) {
  3906. AccessibleContext ac = getCurrentAccessibleContext();
  3907. if (ac instanceof AccessibleComponent) {
  3908. ((AccessibleComponent) ac).setSize(d);
  3909. } else {
  3910. Component c = getCurrentComponent();
  3911. if (c != null) {
  3912. c.setSize(d);
  3913. }
  3914. }
  3915. }
  3916. public Accessible getAccessibleAt(Point p) {
  3917. AccessibleContext ac = getCurrentAccessibleContext();
  3918. if (ac instanceof AccessibleComponent) {
  3919. return ((AccessibleComponent) ac).getAccessibleAt(p);
  3920. } else {
  3921. return null;
  3922. }
  3923. }
  3924. public boolean isFocusTraversable() {
  3925. AccessibleContext ac = getCurrentAccessibleContext();
  3926. if (ac instanceof AccessibleComponent) {
  3927. return ((AccessibleComponent) ac).isFocusTraversable();
  3928. } else {
  3929. Component c = getCurrentComponent();
  3930. if (c != null) {
  3931. return c.isFocusTraversable();
  3932. } else {
  3933. return false;
  3934. }
  3935. }
  3936. }
  3937. public void requestFocus() {
  3938. AccessibleContext ac = getCurrentAccessibleContext();
  3939. if (ac instanceof AccessibleComponent) {
  3940. ((AccessibleComponent) ac).requestFocus();
  3941. } else {
  3942. Component c = getCurrentComponent();
  3943. if (c != null) {
  3944. c.requestFocus();
  3945. }
  3946. }
  3947. }
  3948. public void addFocusListener(FocusListener l) {
  3949. AccessibleContext ac = getCurrentAccessibleContext();
  3950. if (ac instanceof AccessibleComponent) {
  3951. ((AccessibleComponent) ac).addFocusListener(l);
  3952. } else {
  3953. Component c = getCurrentComponent();
  3954. if (c != null) {
  3955. c.addFocusListener(l);
  3956. }
  3957. }
  3958. }
  3959. public void removeFocusListener(FocusListener l) {
  3960. AccessibleContext ac = getCurrentAccessibleContext();
  3961. if (ac instanceof AccessibleComponent) {
  3962. ((AccessibleComponent) ac).removeFocusListener(l);
  3963. } else {
  3964. Component c = getCurrentComponent();
  3965. if (c != null) {
  3966. c.removeFocusListener(l);
  3967. }
  3968. }
  3969. }
  3970. // AccessibleSelection methods
  3971. /**
  3972. * Returns the number of items currently selected.
  3973. * If no items are selected, the return value will be 0.
  3974. *
  3975. * @return the number of items currently selected.
  3976. */
  3977. public int getAccessibleSelectionCount() {
  3978. int count = 0;
  3979. int childCount = getAccessibleChildrenCount();
  3980. for (int i = 0; i < childCount; i++) {
  3981. TreePath childPath = getChildTreePath(i);
  3982. if (tree.isPathSelected(childPath)) {
  3983. count++;
  3984. }
  3985. }
  3986. return count;
  3987. }
  3988. /**
  3989. * Returns an Accessible representing the specified selected item
  3990. * in the object. If there isn't a selection, or there are
  3991. * fewer items selected than the integer passed in, the return
  3992. * value will be null.
  3993. *
  3994. * @param i the zero-based index of selected items
  3995. * @return an Accessible containing the selected item
  3996. */
  3997. public Accessible getAccessibleSelection(int i) {
  3998. int childCount = getAccessibleChildrenCount();
  3999. if (i < 0 || i >= childCount) {
  4000. return null; // out of range
  4001. }
  4002. int count = 0;
  4003. for (int j = 0; j < childCount && i >= count; j++) {
  4004. TreePath childPath = getChildTreePath(j);
  4005. if (tree.isPathSelected(childPath)) {
  4006. if (count == i) {
  4007. return new AccessibleJTreeNode(tree, childPath, this);
  4008. } else {
  4009. count++;
  4010. }
  4011. }
  4012. }
  4013. return null;
  4014. }
  4015. /**
  4016. * Returns true if the current child of this object is selected.
  4017. *
  4018. * @param i the zero-based index of the child in this Accessible
  4019. * object.
  4020. * @see AccessibleContext#getAccessibleChild
  4021. */
  4022. public boolean isAccessibleChildSelected(int i) {
  4023. int childCount = getAccessibleChildrenCount();
  4024. if (i < 0 || i >= childCount) {
  4025. return false; // out of range
  4026. } else {
  4027. TreePath childPath = getChildTreePath(i);
  4028. return tree.isPathSelected(childPath);
  4029. }
  4030. }
  4031. /**
  4032. * Adds the specified selected item in the object to the object's
  4033. * selection. If the object supports multiple selections,
  4034. * the specified item is added to any existing selection, otherwise
  4035. * it replaces any existing selection in the object. If the
  4036. * specified item is already selected, this method has no effect.
  4037. *
  4038. * @param i the zero-based index of selectable items
  4039. */
  4040. public void addAccessibleSelection(int i) {
  4041. TreeModel model = JTree.this.getModel();
  4042. if (model != null) {
  4043. if (i >= 0 && i < getAccessibleChildrenCount()) {
  4044. TreePath path = getChildTreePath(i);
  4045. JTree.this.addSelectionPath(path);
  4046. }
  4047. }
  4048. }
  4049. /**
  4050. * Removes the specified selected item in the object from the
  4051. * object's
  4052. * selection. If the specified item isn't currently selected, this
  4053. * method has no effect.
  4054. *
  4055. * @param i the zero-based index of selectable items
  4056. */
  4057. public void removeAccessibleSelection(int i) {
  4058. TreeModel model = JTree.this.getModel();
  4059. if (model != null) {
  4060. if (i >= 0 && i < getAccessibleChildrenCount()) {
  4061. TreePath path = getChildTreePath(i);
  4062. JTree.this.removeSelectionPath(path);
  4063. }
  4064. }
  4065. }
  4066. /**
  4067. * Clears the selection in the object, so that nothing in the
  4068. * object is selected.
  4069. */
  4070. public void clearAccessibleSelection() {
  4071. int childCount = getAccessibleChildrenCount();
  4072. for (int i = 0; i < childCount; i++) {
  4073. removeAccessibleSelection(i);
  4074. }
  4075. }
  4076. /**
  4077. * Causes every selected item in the object to be selected
  4078. * if the object supports multiple selections.
  4079. */
  4080. public void selectAllAccessibleSelection() {
  4081. TreeModel model = JTree.this.getModel();
  4082. if (model != null) {
  4083. int childCount = getAccessibleChildrenCount();
  4084. TreePath path;
  4085. for (int i = 0; i < childCount; i++) {
  4086. path = getChildTreePath(i);
  4087. JTree.this.addSelectionPath(path);
  4088. }
  4089. }
  4090. }
  4091. // AccessibleAction methods
  4092. /**
  4093. * Returns the number of accessible actions available in this
  4094. * tree node. If this node is not a leaf, there is at least
  4095. * one action (toggle expand), in addition to any available
  4096. * on the object behind the TreeCellRenderer.
  4097. *
  4098. * @return the number of Actions in this object
  4099. */
  4100. public int getAccessibleActionCount() {
  4101. AccessibleContext ac = getCurrentAccessibleContext();
  4102. if (ac != null) {
  4103. AccessibleAction aa = ac.getAccessibleAction();
  4104. if (aa != null) {
  4105. return (aa.getAccessibleActionCount() + (isLeaf ? 0 : 1));
  4106. }
  4107. }
  4108. return isLeaf ? 0 : 1;
  4109. }
  4110. /**
  4111. * Return a description of the specified action of the tree node.
  4112. * If this node is not a leaf, there is at least one action
  4113. * description (toggle expand), in addition to any available
  4114. * on the object behind the TreeCellRenderer.
  4115. *
  4116. * @param i zero-based index of the actions
  4117. * @return a description of the action
  4118. */
  4119. public String getAccessibleActionDescription(int i) {
  4120. if (i < 0 || i >= getAccessibleActionCount()) {
  4121. return null;
  4122. }
  4123. AccessibleContext ac = getCurrentAccessibleContext();
  4124. if (i == 0) {
  4125. return "toggle expand";
  4126. } else if (ac != null) {
  4127. AccessibleAction aa = ac.getAccessibleAction();
  4128. if (aa != null) {
  4129. return aa.getAccessibleActionDescription(i - 1);
  4130. }
  4131. }
  4132. return null;
  4133. }
  4134. /**
  4135. * Perform the specified Action on the tree node. If this node
  4136. * is not a leaf, there is at least one action which can be
  4137. * done (toggle expand), in addition to any available on the
  4138. * object behind the TreeCellRenderer.
  4139. *
  4140. * @param i zero-based index of actions
  4141. * @return true if the the action was performed; else false.
  4142. */
  4143. public boolean doAccessibleAction(int i) {
  4144. if (i < 0 || i >= getAccessibleActionCount()) {
  4145. return false;
  4146. }
  4147. AccessibleContext ac = getCurrentAccessibleContext();
  4148. if (i == 0) {
  4149. if (JTree.this.isExpanded(path)) {
  4150. JTree.this.collapsePath(path);
  4151. } else {
  4152. JTree.this.expandPath(path);
  4153. }
  4154. return true;
  4155. } else if (ac != null) {
  4156. AccessibleAction aa = ac.getAccessibleAction();
  4157. if (aa != null) {
  4158. return aa.doAccessibleAction(i - 1);
  4159. }
  4160. }
  4161. return false;
  4162. }
  4163. } // inner class AccessibleJTreeNode
  4164. } // inner class AccessibleJTree
  4165. } // End of class JTree