使用jdom操作xml數據,生成含Jtree的applet(轉載 Jagie 原創 )

使用jdom操作xml數據,生成含Jtree的applet
Jagie 原創  (參與分:291,專家分:1430)   發表:2003-11-5 下午4:06   更新:2003-11-5 下午4:22   版本:1.0   閱讀:3608
http://www.javaresearch.org/article/showarticle.jsp?column=287&thread=10150

關鍵詞:xml,jdom,applet,jtree


在我們工作中,常常會碰到樹形組件的生成問題,如果你在開發web application,純粹使用
javascript來生成樹形組件是非常繁瑣的,而且交互性也不不太好。所以許多產品使applet來實現樹形組件的功能。比如說,weblogic,jboss等產品的console.所以,把樹形數據組織成xml文件,用jdom剖析它,最後生成applet就非常有通用的意義。下面,我就給出一個例子,拋磚引玉。

1.準備一個存有屬性數據的xml文件,把它放在classpath中,我這裏是org.xml。

[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/org
E:/myDemo/org.xsd" name="組織機構" id="-1" desc="" link="#">
    <node name="總經理" id="1" desc="" link="#">
        <node name="管理副總經理" id="2" desc="" link="#"/>
        <node name="生產副總經理" id="3" desc="" link="#">
            <node name="項目部" id="7" desc="" link="#"/>
            <node name="機械公司" id="8" desc="" link="#"/>
            <node name="貝盟公司" id="9" desc="" link="#"/>
            <node name="洛斯韋公司" id="9" desc="" link="#"/>
        </node>
        <node name="總工程師" id="4" desc="" link="#"/>
        <node name="總會計師" id="5" desc="" link="#"/>
        <node name="總經濟師" id="6" desc="" link="#"/>
    </node>
</node>[/pre]

2.確保你可以使用jdom解析器,你如果沒有可以去這裏下載。

3.用於代表樹結點節點的javabean,TreeNode.java

package 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.自己寫的TreeCellRenderer,IconRender.java

package com.javabox.jtree;

import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;

import javax.swing.tree.DefaultTreeCellRenderer;

class IconRender
    extends DefaultTreeCellRenderer {
  
//你需要替換成你的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) {
    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,該文件解析xml文件,生成含Jtree的applet,你可以把它嵌入到jsp,html文件中使用,也可以直接運行該文件。

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.*;


public 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();
    }
    //你可以在這裏改變jtree中連線的顏色,我請教國外的高手才找到的,很酷的哦:)
    UIManager.put( "Tree.hash"new ColorUIResource(Color.red) );
    return new JTree(top);

  }

  /**
   *
   * @param e 待加入樹種的jdom元素
   * @param rootNode 樹根節點
   */


  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);
    //如有父節點
    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));
      }
    }
    //如有子節點
    Iterator it=e.getChildren().iterator();
    while(it.hasNext()){
      Element child=(Element)it.next();
      addNode(child,rootNode);
    }

  }

  /**
   * 根據id,查找樹節點,//廣度優先
   * @param id 節點id
   * @param rootNode 樹根節點
   * @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();
      }
      //調用一個javascript函數; 
//      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);
    frame.setSize(600,600);

    frame.show();
  }

}


6.運行一個這個類,是不是很cool哦,你還可以把它嵌在網頁中,調用javasript函數,達到刷新頁面的目的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章