Using Jdom to manipulate XML data to generate an applet containing JTree

Source: Internet
Author: User
Tags final return xmlns
dom|xml| data
Turn from: http://www.softhouse.com.cn/html/200410/2004102517145700001335.html

Using Jdom to manipulate XML data to generate an applet containing JTree
    in our work, we often encounter the generation of tree components, if you are developing web application, purely JavaScript to generate tree components is very tedious, and the interaction is not very good. So many products enable applets to implement the functionality of the tree component. For example, Weblogic,jboss and other products, such as console. So, to organize the tree data into an XML file, analyze it with jdom, and finally generate the applet is very universal meaning. Next, I will give an example, a point. 1. Prepare an XML file with attribute data, put it in the classpath, I'm org.xml here. [pre]<?xml version= "1.0"  encoding= "UTF-8"?><!--sample xml file generated  by XMLSPY v5 rel. 3 U  (http://www.xmlspy.com)--><node xmlns= " Http://www.javabox.com/schemas/org " xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance " xsi: schemalocation= "Http://www.javabox.com/schemas/orge:\mydemo\org.xsd"  name= "organization"  id= "-1"  desc= " " link=" # ">    <node name=" General manager " id=" 1 " desc=" " link=" # ">         <node name= "Management deputy general Manager"  id= "2"  desc= ""  link = "#"/>        <node name= "vice president of productionDaniel " id=" 3 " desc=" " link=" "#" >             <node name= "Project Department"  id= "7"  desc= ""  link= "#"/>             <node name= "Machinery Company"  id= "8"  desc= ""  link= "#" >            <node name= "The  id= of the Union Company" "9"  desc= ""  link= "#"/>             <node name= "Loswe Company"  id= "9"  desc= ""  link= "#"/>         </node>        <node name= "chief Engineer"  id= "4"  desc= ""  link= "#"/>        <node name= "chief accountant"  id= "5"  desc= ""  link= "#"/>        <node name = "chief economist"  id= "6"  desc=""  link= "#"/>    </node></node>[/pre]2. Make sure you can use the Jdom parser if you don't have to go here to download. 3. Used to represent nodes of a tree node javabean,treenode.javapackage com.javabox.jtree;public class treenode{   private string id;  private string name;  private string  Link;  public treenode (String id,string name,string link) {     this.id=id;    this.name=name;    this.link=link;  }   public string getid () {    return id;  }   Public void setid (string id) {    this.id=id;  }  public  void  setname (String name) {    this.name=name;  }   public string getname () {    return name;  }   Public string tostring () {    return  name;  }  public string getlink () {     return link;  }  public void setlink (String  Link) {    this.link=link;  }}4. Written by himself treecellrenderer,iconrender.javapackage  com.javabox.jtree;import javax.swing.*;import java.awt.*;import javax.swing.tree.*;import  javax.swing.tree.defaulttreecellrenderer;class iconrender    extends  defaulttreecellrenderer {  //, you need to replace your icon  public static final icon.  leafselectedicon = new imageicon ("Greeball.") JPG ");  public static final icon leafunselectedicon = new  ImageIcon ("Greyball.") JPG ");   public static final icon folderopen = new imageicon (" Folderopen. JPG ");   public static final iCon folderclose = new imageicon ("Folderclose.") JPG ");   public component gettreecellrenderercomponent (jtree tree,                                                   Object value,                                                   boolean selected,                                                  boolean expanded,                                                   boolean leaf,                                                   int row,                                                   boolean hasfocus) &NBsp {    super.gettreecellrenderercomponent (tree, value, selected, expanded,                                          leaf, row, hasfocus);    if  (leaf &&  Selected)  {      seticon (Iconrender.leafselectedicon);     }    else if  (leaf)  {      seticon ( Iconrender.leafunselectedicon);     }    return this;  }   public iconrender ()  {    super ();     This.setleaficon (Leafunselectedicon);     this.setopenicon (Folderopen);     this.setclosedicon (Folderclose);   }}5.applettree.java, the file parses an XML file, generates an applet with JTree, you can embed it in a jsp,html file, or you can run the file directly. Package com.javabox.jtree;import javax.swing.event.*;import java.awt.*;import java.applet. *;import javax.swing.*;import javax.swing.tree.*;import java.awt.event.*;import org.jdom.* ; import org.jdom.input.*;import java.io.*;import java.util.*;import java.awt.*;import  javax.swing.*;import javax.swing.border.*;import javax.swing.plaf.*;import  javax.swing.plaf.basic.*;import javax.swing.plaf.metal.*;import java.io.*;import  netscape.javascript.*;p ublic class applettree extends applet implements  treeselectionlistener{  private jtree tree;  private treepath path;   private Panel topPanel;  private DefaultMutableTreeNode top;   private defaultmutabletreenode clicknode;  prIvate string link;  public applettree () {  }  public void  init () {    try{    super.init ();     This.setlayout (New gridlayout (1,1));     tree=createtree (New FileInputStream (" Org.xml "));     tree.getselectionmodel (). Setselectionmode (Treeselectionmodel.single_tree_ SELECTION);     tree.putclientproperty ("Jtree.linestyle", "angled");     Tree.setshowsroothandles (True);     tree.seteditable (false);     Tree.addtreeselectionlistener ( this );    iconrender render=new  Iconrender ();     tree.setcellrenderer (render);    toppanel=new  Panel (New borderlayout ());     toppanel.add (tree);     this.add ( Toppanel);     }catch (excePtion e) {      e.printstacktrace ();     }  }   public jtree createtree (Inputstream is) {    saxbuilder  Builder = new saxbuilder ();    try {       document doc = builder.build (is);       element root= Doc.getrootelement ();       treenode rootnode=new treenode ( Root.getattributevalue ("id"), root.getattributevalue ("name"), Root.getattributevalue ("link");       top=new defaultmutabletreenode (RootNode);       addnode ( Root,top);    }  catch  (Exception ex)  {       ex.printstacktrace ()     }    //You can change the color of the lines in JTree here, I ask foreign experts to find, very cool oh:)     Uimanager.put (  "Tree.hash",  new coloruiresource (color.red)  );     Return new jtree (top);  }  /**   *   *  @param  e  jdom elements to be added    *  @param  rootNode  root node    */   private void addnode (Element e,defaultmutabletreenode rootnode) {     string id=e.getattributevalue ("id");     string name=e.getattributevalue (" Name ");     string link=e.getattributevalue (" link ");     treenode  node=new treenode (id,name,link);     //If there is a parent node     element  father=e.getparent ();     if (father!=null) {      string  fid=father.getattributevalue ("id");      defaultmutabletreenode  Fathernode=gettreenode (Fid,rootnode);       if (Fathernode!=null) {         Fathernode.add (New defaultmutabletreenode (node));      }     }    //If there is a child node     iterator it=e.getchildren (). Iterator ();     while (It.hasnext ()) {      element child= (Element) It.next ();       addnode (child,rootnode);     }  }   /**   *  Find tree nodes by ID,//Breadth First    *  @param  id  Node ID    *  @param  rootNode  root node    *  @return   Defaultmutabletreenode   */  private defaultmutabletreenode gettreenode ( String id,defaultmutabletreenode rootnode) {    defaultmutabletreenode  Returnnode=null;    if (RootnodE!=null) {      enumeration enum=rootnode.breadthfirstenumeration ();       while (Enum.hasmoreelements ()) {         defaultmutabletreenode temp= (Defaultmutabletreenode) enum.nextelement ();         treenode node= (TreeNode) temp.getuserobject ();         if (Node.getid (). Equals (ID)) {          returnnode=temp;           break;         }      }    }    return  Returnnode;  }  public void valuechanged ( treeselectionevent event  ) {    if ( event.getsource ()  == tree ) {       path = evEnt.getpath ();       clicknode= (Defaultmutabletreenode) path.getLastPathComponent ( );       object uo=clicknode.getuserobject ();       if (Uo instanceof treenode) {        treenode nd= ( TreeNode) Clicknode.getuserobject ();         link=nd.getlink ();       }      //calls a JavaScript function;//       JSObject.getWindow  (This) .eval  ("Javascript:window.open (' +link+") ")  ;     }  }  public static  void main (String[] args  ) {    jframe frame=new jframe ("test");     applettree  tree=new applettree ();     tree.init ();     Frame.getcontentpane (). Add (tree);  &Nbsp;  frame.setsize (600,600),     frame.show (),   }}6. Running one of these, isn't it cool? , you can also embed it in the Web page, call the Javasript function, to refresh the page.

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.