📄 tree.html
字号:
> <a href=../index.html target=_top>Creating a GUI with JFC/Swing</a> > <a href=index.html target=_top>Using Swing Components</a> </span> <div class=NavBit> <a target=_top href=tooltip.html>« Previous</a> • <a target=_top href=../TOC.html>Trail</a> • <a target=_top href=icon.html>Next »</a> </div> <div id=PageTitle>How to Use Trees</div> <blockquote>With the<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JTree.html"><code>JTree</code></a> class,you can display hierarchical data.A <code>JTree</code> object doesn't actually contain your data;it simply provides a view of the data.Like any non-trivial Swing component,the tree gets data by querying its data model.Here's a picture of a tree:<p><center><IMG SRC="../../figures/uiswing/components/tree.gif" WIDTH="128" HEIGHT="113" ALIGN="BOTTOM" ALT="A tree"></center></p>[PENDING: This picture will be updatedto show the Java look and feel.Labels will be added: "root node", "expanded branch node","collapsed branch node", "leaf node".]<p>As the preceding figure shows, <code>JTree</code> displays its data vertically. Each row displayed by the tree contains exactly one item of data,which is called a <em>node</em>.Every tree has a <em>root</em> nodefrom which all nodes descend.By default, the tree displays the root node,but you can decree otherwise.A node can either have children or not.We refer to nodes that can have children —whether or not they currently <em>have</em> children —as <em>branch</em> nodes.Nodes that can't have childrenare <em>leaf</em> nodes.<p>Branch nodes can have any number of children.Typically,the user can expand and collapse branch nodes —making their children visible or invisible —by clicking them.By default, all branch nodes except the root node start out collapsed.A program can detect changes in branch nodes' expansion stateby listening for tree expansion or tree-will-expand events,as described in<a class="TutorialLink" target="_top" href="../events/treeexpansionlistener.html">How to Write a Tree Expansion Listener</a> and<a class="TutorialLink" target="_top" href="../events/treewillexpandlistener.html">How to Write a Tree-Will-Expand Listener</a>.<p>The rest of this section discusses the following topics:<ul><li> <a href="#create">Creating a Tree</a><li> <a href="#select">Responding to Node Selection</a><li> <a href="#display">Customizing a Tree's Display</a><li> <a href="#dynamic">Dynamically Changing a Tree</a><li> <a href="#data">Creating a Data Model</a><li> <a href="#api">The Tree API</a><li> <a href="#eg">Examples that Use Trees</a></ul></blockquote><h3><a name="create">Creating a Tree</a></h3><blockquote>Here is a picture of an application, the top half of which displays a treein a scroll pane.<p><center><IMG SRC="../../figures/uiswing/components/TreeDemo.png" WIDTH="508" HEIGHT="280" ALIGN="BOTTOM" ALT="TreeDemo"></center></p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TreeDemo.jnlp">Run TreeDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java<sup><font size=-2>TM</font></sup> Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#TreeDemo">example index</a>.<li> Expand one or more nodes. <br> You can do this by clicking the circle to the left of the item.<li> Collapse a node. <br> You do this by clicking the circle to the left of an expanded node.</ol><hr></blockquote><p>The following code,taken from <a class="SourceLink" target="_blank" href="examples/TreeDemo.java"><code>TreeDemo.java</code></a>,creates the <code>JTree</code> objectand puts it in a scroll pane:<blockquote><pre><em>//Where instance variables are declared:</em>private JTree tree;...public TreeDemo() { ... DefaultMutableTreeNode top = new DefaultMutableTreeNode("The Java Series"); createNodes(top); tree = new JTree(top); ... JScrollPane treeView = new JScrollPane(tree); ...}</pre></blockquote>The code creates an instance of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultMutableTreeNode.html"><code>DefaultMutableTreeNode</code></a> to serve as the root node for the tree.It then creates the rest of the nodes in the tree.After that, it creates the tree, specifying the root node as an argumentto the <code>JTree</code> constructor.Finally, it puts the tree in a scroll pane,a common tactic because showing the full, expanded treewould otherwise require too much space.<p>Here is the code that creates the nodes under the root node:<blockquote><pre>private void createNodes(DefaultMutableTreeNode top) { DefaultMutableTreeNode category = null; DefaultMutableTreeNode book = null; category = new DefaultMutableTreeNode("Books for Java Programmers"); top.add(category); //original Tutorial book = new DefaultMutableTreeNode(new BookInfo ("The Java Tutorial: A Short Course on the Basics", "tutorial.html")); category.add(book); //Tutorial Continued book = new DefaultMutableTreeNode(new BookInfo ("The Java Tutorial Continued: The Rest of the JDK", "tutorialcont.html")); category.add(book); //JFC Swing Tutorial book = new DefaultMutableTreeNode(new BookInfo ("The JFC Swing Tutorial: A Guide to Constructing GUIs", "swingtutorial.html")); category.add(book); <em>//...add more books for programmers...</em> category = new DefaultMutableTreeNode("Books for Java Implementers"); top.add(category); //VM book = new DefaultMutableTreeNode(new BookInfo ("The Java Virtual Machine Specification", "vm.html")); category.add(book); //Language Spec book = new DefaultMutableTreeNode(new BookInfo ("The Java Language Specification", "jls.html")); category.add(book);}</pre></blockquote><p>The argument to the <code>DefaultMutableTreeNode</code>constructor is the <em>user object</em> —an object that contains or points to the dataassociated with the tree node.The user object can be a string, or it can be a custom object.If you implement a custom object,you should implement its <code>toString</code> methodso that it returns the string to be displayed for that node.<p>For example, the <code>BookInfo</code> classused in the previous code snippet is a custom class that holds two pieces of data: the name of a book,and the URL for an HTML file describing the book.The <code>toString</code> method is implementedto return the book name.Thus, each node associated with a <code>BookInfo</code> objectdisplays a book name.<blockquote><hr><strong>Note:</strong> You can specify text formatting in a tree nodeby putting HTML tags in the string for the node.See <a href="html.html">Using HTML in Swing Components</a>for details.<hr></blockquote><p>To summarize,you can create a treeby invoking the <code>JTree</code> constructor,specifying the root node as an argument.You should probably put the tree inside a scroll pane,so that the tree won't take up too much space.You don't have to do anythingto make the tree nodes expand and collapsein response to user clicks.However, you do have to add some codeto make the tree respond whenthe user selects a node —by clicking the node, for example.</blockquote><h3><a name="select">Responding to Node Selection</a></h3><blockquote>Responding to tree node selections is simple.You implement a tree selection listenerand register it on the tree,The following code showsthe selection-related code from the <code>TreeDemo</code> program:<blockquote><pre><em>//Where the tree is initialized:</em> tree.getSelectionModel().setSelectionMode (TreeSelectionModel.SINGLE_TREE_SELECTION); //Listen for when the selection changes. tree.addTreeSelectionListener(this);...public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (node.isLeaf()) { BookInfo book = (BookInfo)nodeInfo; displayURL(book.bookURL); } else { displayURL(helpURL); }}</pre></blockquote>The preceding code performs these tasks:<ul><li> Gets the default <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/tree/TreeSelectionModel.html"><code>TreeSelectionModel</code></a> for the tree, and then sets it up so that at most one tree node at a time can be selected.<li> Registers an event handler on the tree. The event handler is an object that implements the <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/event/TreeSelectionListener.html"><code>TreeSelectionListener</code></a> interface.<li> In the event handler, determines which node is selected by invoking the tree's <code>getLastSelectedPathComponent</code> method.<li> Uses the <code>getUserObject</code> method to get the data associated with the node.</ul>For more details about handling tree selection events, see<a class="TutorialLink" target="_top" href="../events/treeselectionlistener.html">How to Write a Tree Selection Listener</a>.</blockquote><h3><a name="display">Customizing a Tree's Display</a></h3><blockquote>Here is a picture of some tree nodes,as drawn by the Java, Windows, and Mac OS look and feel implementations.<p align=center><table summary="layout" cellspacing=10 align=center><tr align=center><td><IMG SRC="../../figures/uiswing/components/TreeDemo-lsAngled.gif" WIDTH="125" HEIGHT="96" ALT="TreeDemo with angled lines"></td><td><IMG SRC="../../figures/uiswing/components/TreeDemo-windows.gif" WIDTH="124" HEIGHT="82" ALT="A tree in the Windows look and feel"></td><td>[PENDING: Mac pic goes here]</td></tr><tr align=center><td>Java look and feel</td><td>Windows look and feel</td><td>Mac OS look and feel</td></tr></table></p><p>As the preceding figures show,a tree conventionally displays an icon and some text for each node.You can customize these, as we'll show shortly.<p>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -