⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tree.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 5 页
字号:
A tree typically also performs some look-and-feel-specificpainting to indicate relationships between nodes.You can customize this painting in a limited way.First, you can use <code>tree.setRootVisible(true)</code>to show the root node or<code>tree.setRootVisible(false)</code>to hide it.Second, you can use <code>tree.setShowsRootHandles(true)</code>to request that a tree's top-level nodes &#151;the root node (if it's visible) or its children (if not) &#151;have handles that let them be expanded or collapsed.Third, if you're using the Java look and feel,you can customize whether lines are drawnto show relationships between tree nodes.<p>By default, the Java look and feel draws angled lines between nodes.By setting the <code>JTree.lineStyle</code>client property of a tree,you can specifya different convention.For example, to request that the Java look and feel use only horizontal lines to group nodes,use the following code:<blockquote><pre>tree.putClientProperty("JTree.lineStyle", "Horizontal");</pre></blockquote><p>To specify that the Java look and feel should draw no lines,use this code:<blockquote><pre>tree.putClientProperty("JTree.lineStyle", "None");</pre></blockquote>The following snapshots show the resultsof setting the <code>JTree.lineStyle</code> property,when using the Java look and feel.<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><p><center><IMG SRC="../../figures/uiswing/components/TreeDemo-lsHoriz.gif" WIDTH="125" HEIGHT="96" ALIGN="BOTTOM" ALT="TreeDemo with horizontal lines"></center></p></td><td><p><center><IMG SRC="../../figures/uiswing/components/TreeDemo-lsNone.gif" WIDTH="125" HEIGHT="96" ALIGN="BOTTOM" ALT="TreeDemo with no lines"></center></p></td></tr><tr align=center valign=bottom><td><code>"Angled"</code> (default)</td><td><code>"Horizontal"</code></td><td><code>"None"</code></td></tr></table></p><p>No matter what the look and feel,the default icon displayed by a nodeis determined by whether the node is a leafand, if not, whether it's expanded.For example, in the Windows and Motif look and feel implementations,the default icon for each leaf node is a dot;in the Java look and feel,the default leaf icon is a paper-like symbol.In all the look-and-feel implementations we've shown,branch nodes are marked with folder-like symbols.Some look and feels might have different iconsfor expanded branches versus collapsed branches.<p>You can easily change the default icon used for leaf,expanded branch, or collapsed branch nodes.To do so, you first create an instance of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html"><code>DefaultTreeCellRenderer</code></a>.Next, specify the icons to use by invoking one or more of thefollowing methods on the renderer:<code>setLeafIcon</code> (for leaf nodes),<code>setOpenIcon</code> (for expanded branch nodes),<code>setClosedIcon</code> (for collapsed branch nodes).If you want the tree to display no iconfor a type of node,then specify <code>null</code> for the icon.Once you've set up the icons,use the tree's <code>setCellRenderer</code> methodto specify that the <code>DefaultTreeCellRenderer</code>paint its nodes.Here is an example,taken from <a class="SourceLink" target="_blank" href="examples/TreeIconDemo.java"><code>TreeIconDemo.java</code></a>:<blockquote><pre>ImageIcon leafIcon = createImageIcon("images/middle.gif");if (leafIcon != null) {    DefaultTreeCellRenderer renderer = 	new DefaultTreeCellRenderer();    renderer.setLeafIcon(leafIcon);    tree.setCellRenderer(renderer);}</pre></blockquote>You can <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TreeIconDemo.jnlp">run TreeIconDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#TreeIconDemo">example index</a>.Here is what the resulting UI looks like:<p><center><IMG SRC="../../figures/uiswing/components/TreeIconDemo.png" WIDTH="508" HEIGHT="243" ALIGN="BOTTOM" ALT="TreeIconDemo"></center></p><p>If you want finer control over the node iconsor you want to provide tool tips,you can do so by creating asubclass of <code>DefaultTreeCellRenderer</code>and overriding the <code>getTreeCellRendererComponent</code> method.Because <code>DefaultTreeCellRenderer</code>is a subclass of <code>JLabel</code>,you can use any <code>JLabel</code> method &#151;such as <code>setIcon</code> &#151;to customize the <code>DefaultTreeCellRenderer</code>.<p>The following code, from <a class="SourceLink" target="_blank" href="examples/TreeIconDemo2.java"><code>TreeIconDemo2.java</code></a>, creates a cell rendererthat varies the leaf icondepending on whether the word "Tutorial"is in the node's text data.The renderer also specifies tool-tip text,as the bold lines show.You can <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/TreeIconDemo2.jnlp">run TreeIconDemo2</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#TreeIconDemo2">example index</a>.<blockquote><pre><em>//...where the tree is initialized:</em>    <b>//Enable tool tips.    ToolTipManager.sharedInstance().registerComponent(tree);</b>        ImageIcon tutorialIcon = createImageIcon("images/middle.gif");    if (tutorialIcon != null) {        tree.setCellRenderer(new MyRenderer(tutorialIcon));    }...class MyRenderer extends DefaultTreeCellRenderer {    Icon tutorialIcon;    public MyRenderer(Icon icon) {        tutorialIcon = icon;    }    public Component getTreeCellRendererComponent(                        JTree tree,                        Object value,                        boolean sel,                        boolean expanded,                        boolean leaf,                        int row,                        boolean hasFocus) {        super.getTreeCellRendererComponent(                        tree, value, sel,                        expanded, leaf, row,                        hasFocus);        if (leaf && isTutorialBook(value)) {            setIcon(tutorialIcon);            <b>setToolTipText("This book is in the Tutorial series.");</b>        <b>} else {            setToolTipText(null); //no tool tip</b>        }         return this;    }    protected boolean isTutorialBook(Object value) {        DefaultMutableTreeNode node =                (DefaultMutableTreeNode)value;        BookInfo nodeInfo =                (BookInfo)(node.getUserObject());        String title = nodeInfo.bookName;        if (title.indexOf("Tutorial") >= 0) {            return true;        }        return false;    }}</pre></blockquote>Here is the result:<p><center><IMG SRC="../../figures/uiswing/components/TreeIconDemo2.png" WIDTH="508" HEIGHT="241" ALIGN="BOTTOM" ALT="TreeIconDemo2"></center></p><p>You might be wondering how a cell renderer works.When a tree paints each node,neither the <code>JTree</code>nor its look-and-feel-specific implementation actually contains the code that paints the node.Instead, the tree uses the cell renderer's painting codeto paint the node.For example, to paint a leaf node that has the string "The Java Programming Language",the tree asks its cell rendererto return a componentthat can paint a leaf node with that string.If the cell renderer is a <code>DefaultTreeCellRenderer</code>,then it returns a label that paints the default leaf iconfollowed by the string.<p>A cell renderer only paints; it cannot handle events.If you want to add event handling to a tree,you need to register your handler on either the tree or, if the handling occurs only when a node is selected,the tree's <em>cell editor</em>.For information about cell editors,see<a href="table.html#editrender">Concepts: Editors and Renderers</a>.That section discusses table cell editors and renderers,which are similar to tree cell editors and renderers.</blockquote><h3><a name="dynamic">Dynamically Changing a Tree</a></h3><blockquote>The following figure shows an application called DynamicTreeDemo that lets you add nodes to and remove nodes from a visible tree.You can also edit the text in each node.<p><center><IMG SRC="../../figures/uiswing/components/DynamicTreeDemo.png" WIDTH="388" HEIGHT="184" ALIGN="BOTTOM" ALT="DynamicTreeDemo"></center></p><p>The application is based on an example provided bytutorial reader Richard Stanford.You can <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/components/examples/DynamicTreeDemo.jnlp">run DynamicTreeDemo</a> (it requires release 6) using<a class="TutorialLink" target="_top" href="../../information/javawebstart.html">Java Web Start</a>.    Or, to compile and run the example yourself,     consult the     <a href="examples/index.html#DynamicTreeDemo">example index</a>.Here is the code that initializes the tree:<blockquote><pre>rootNode = new DefaultMutableTreeNode("Root Node");treeModel = new DefaultTreeModel(rootNode);treeModel.addTreeModelListener(new MyTreeModelListener());tree = new JTree(treeModel);tree.setEditable(true);tree.getSelectionModel().setSelectionMode        (TreeSelectionModel.SINGLE_TREE_SELECTION);tree.setShowsRootHandles(true);</pre></blockquote>By explicitly creating the tree's model,the code guarantees that the tree's modelis an instance of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/tree/DefaultTreeModel.html"><code>DefaultTreeModel</code></a>.That way, we know all the methods that the tree modelsupports.For example, we know that we can invoke the model's<code>insertNodeInto</code> method,even though that method is not required by the <code>TreeModel</code>interface.<p>To make the text in the tree's nodes editable,we invoke <code>setEditable(true)</code> on the tree.When the user has finished editing a node,the model generates a tree model eventthat tells any listeners &#151;including the <code>JTree</code> &#151;that tree nodes have changed.Note that although <code>DefaultMutableTreeNode</code>has methods for changing a node's content,changes should go through the <code>DefaultTreeModel</code> cover methods.Otherwise, the tree model events won't be generated,and listeners such as the tree won't know about the updates.<p>To be notified of node changes,we can implement a <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/event/TreeModelListener.html"><code>TreeModelListener</code></a>.  Here is an example of a tree model listenerthat detects when the user has typed in a new namefor a tree node:<blockquote><pre>class MyTreeModelListener implements TreeModelListener {    public void treeNodesChanged(TreeModelEvent e) {        DefaultMutableTreeNode node;        node = (DefaultMutableTreeNode)                 (e.getTreePath().getLastPathComponent());        /*         * If the event lists children, then the changed         * node is the child of the node we've already         * gotten.  Otherwise, the changed node and the         * specified node are the same.         */        try {            int index = e.getChildIndices()[0];            node = (DefaultMutableTreeNode)                   (node.getChildAt(index));        } catch (NullPointerException exc) {}        System.out.println("The user has finished editing the node.");        System.out.println("New value: " + node.getUserObject());    }    public void treeNodesInserted(TreeModelEvent e) {    }    public void treeNodesRemoved(TreeModelEvent e) {    }    public void treeStructureChanged(TreeModelEvent e) {    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -