JTree Common methods

Source: Internet
Author: User
Tags gety

 PackageCom.swing.demo;Importjava.awt.Component;ImportJava.awt.event.MouseAdapter;Importjava.awt.event.MouseEvent;Importjava.util.ArrayList;Importjava.util.Enumeration;Importjava.util.List;ImportJavax.swing.JFrame;ImportJavax.swing.JScrollPane;ImportJavax.swing.JTree;Importjavax.swing.SwingUtilities;Importjavax.swing.event.TreeExpansionEvent;ImportJavax.swing.event.TreeExpansionListener;Importjavax.swing.event.TreeSelectionEvent;ImportJavax.swing.event.TreeSelectionListener;ImportJavax.swing.tree.DefaultMutableTreeNode;ImportJavax.swing.tree.DefaultTreeCellRenderer;ImportJavax.swing.tree.DefaultTreeModel;ImportJavax.swing.tree.TreeNode;ImportJavax.swing.tree.TreePath;ImportJavax.swing.tree.TreeSelectionModel;ImportCom.swing.model.User;/*** JTree Common methods. *@authorAdministrator **/ Public classTreedemo { Public Static voidMain (string[] args) {FinalJTree tree =Createtree (); //form SettingsJFrame frame =NewJFrame ("Jtreedemo"); //after the construction of the tree will also put the tree on the Jscollpanel, or the tree will show a problemJScrollPane TreeView =NewJScrollPane (tree);        Frame.add (TreeView); Frame.setsize (300, 300); Frame.setvisible (true);        Frame.setdefaultcloseoperation (Jframe.exit_on_close); //Add tree node Select eventTree.addtreeselectionlistener (NewTreeselectionlistener () {@Override Public voidvaluechanged (treeselectionevent e) {//Get TreePath//TreePath NewPath = Event.getnewleadselectionpath (); //TreePath OldPath = Event.getoldleadselectionpath (); //get node through JTree//JTree tree = (jtree) event.getsource (); //tree.getlastselectedpathcomponent ();Defaultmutabletreenode node =(Defaultmutabletreenode) tree. getlastselectedpathcomponent (); if(node = =NULL) {                    return; } Object Object=Node.getuserobject (); if(Node.isleaf ()) {User User=(User) object; System.out.println ("You have chosen:" +user.tostring ()); }                //Get root node:TreeNode RootNode =(TreeNode) Tree.getmodel (). Getroot (); //get the data model of the tree:Defaulttreemodel TreeModel =(Defaulttreemodel) Tree.getmodel (); //get the location of a node of a tree:TreePath Nodepath =NewTreePath (Treemodel.getpathtoroot (node)); //to set the expansion selection and visibility of a node:Tree.setselectionpath (Nodepath);                Tree.makevisible (Nodepath); //expand and scroll to the node visible:tree.scrollpathtovisible (Nodepath); //Another is to set the mouse click to expand the tree node (the default is double-clicked, changed to 0 is not clickable):Tree.settoggleclickcount (1); //The other is a set cell height, but this method we generally do not, most of the time is set in the renderer, because this setting may have UI problems://Tree.setrowheight (a);            }        }); //tree node expand (collapse) eventTree.addtreeexpansionlistener (NewTreeexpansionlistener () {@Override Public voidtreeexpanded (Treeexpansionevent event) {} @Override Public voidtreecollapsed (Treeexpansionevent event) {}}); Tree.addmouselistener (NewMouseadapter () {@Override Public voidmouseclicked (MouseEvent e) {if(Swingutilities.isleftmousebutton (e)&& E.getclickcount () = = 1) {                    //Returns The last path componentDefaultmutabletreenode node =(Defaultmutabletreenode) tree. getlastselectedpathcomponent (); } Else if(Swingutilities.isrightmousebutton (e)) {//Returns The row for the specified location. //int selectrow = tree.getrowforlocation (E.getx (),//e.gety ()); //Returns The path for the node at the specified location.TreePath Selectpath =tree.getpathforlocation (E.getx (), e.gety ()); if(Selectpath! =NULL) {                        //Set SelectTree.setselectionpath (Selectpath); //get tree node.Defaultmutabletreenode TreeNode =(Defaultmutabletreenode) Selectpath. Getlastpathcomponent ();        }                }            }        }); //rendererTree.setcellrenderer (NewDefaulttreecellrenderer () {/*** Serialversionuid*/            Private Static Final LongSerialversionuid = 1L; @Override PublicComponent gettreecellrenderercomponent (jtree tree, Object value,BooleanSelBooleanExpandedBooleanLeaf,intRowBooleanHasfocus) {                return Super. Gettreecellrenderercomponent (tree, value, sel, expanded, leaf, row, hasfocus);    }        }); }    /*** Createtree * *@return     */    Private StaticJTree Createtree () {//creates a tree node that has no parent and child nodes, but allows child nodes, and initializes it with the specified user object. //Public Defaultmutabletreenode (Object UserObject)Defaultmutabletreenode Node1 =NewDefaultmutabletreenode ("software Department"); Node1.add (NewDefaultmutabletreenode (NewUser ("Floret"))); Node1.add (NewDefaultmutabletreenode (NewUser ("Xiao Hu"))); Node1.add (NewDefaultmutabletreenode (NewUser ("Drake"))); Defaultmutabletreenode Node2=NewDefaultmutabletreenode ("Sales Department"); Node2.add (NewDefaultmutabletreenode (NewUser ("Leaflet"))); Node2.add (NewDefaultmutabletreenode (NewUser ("Xiao Wen"))); Node2.add (NewDefaultmutabletreenode (NewUser ("Little Summer"))); Defaultmutabletreenode Top=NewDefaultmutabletreenode ("Staff Management"); Top.add (NewDefaultmutabletreenode (NewUser ("General manager"))));        Top.add (Node1);        Top.add (Node2); //jtree (TreeNode root)//Returns a jtree that specifies the TreeNode as its root, which displays the root node. JTree tree =NewJTree (top); //The final JTree also sets the data through Setmodel://tree = new JTree (); //Tree.setmodel (TreeModel);Tree.getselectionmodel (). Setselectionmode (treeselectionmodel.single_tree_selection); returnTree; }    PrivateList<treenode> treenodelist =NewArraylist<treenode>(); /*** Recursively from any node with all the examples below. *      * @paramTreeNode*/     Public voidgetchildnodelist (TreeNode TreeNode) {if(TreeNode = =NULL) {            Throw NewRuntimeException ("Error TreeNode.")); }        if(Treenodelist = =NULL) {treenodelist=NewArraylist<treenode>(); }        if(Treenode.getchildcount () >= 0) {             for(Enumeration<treenode> e =Treenode.children (); E. hasmoreelements ();) {TreeNode Childnode=(TreeNode) e.nextelement ();                Treenodelist.add (Childnode);            Getchildnodelist (Childnode); }        }    }}

JTree Common methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.