Java JTree的用法

這是好幾天前找的代碼了,一直沒有看,今天翻出來,覺得寫得很不錯,就自己摘抄在這裏了。

原諒我已經不知道原文出處了,抱歉!各位有知道的,望轉告,謝謝~

package lj.hp.test4;

import javax.swing.*;

import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import javax.swing.tree.TreePath;
import java.sql.ResultSet;

public class GB extends JFrame{
	  private TreeMenu tree;
	  public GB() {
	    tree = new TreeMenu();
	    this.setSize(500,550);
	    this.Init();
	    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    this.show();
	  }
	  private void Init()
	  {
	    Container cp = this.getContentPane();
	    cp.setLayout(null);
	    JScrollPane jsp = new JScrollPane(tree);
	    jsp.setBounds(100,20,300,500);
	    cp.add(jsp);
	  }
	  public static void main(String[] args) {
	    GB gb = new GB();
	  }
	}
	class TreeMenu extends JTree
	{
	  private DefaultMutableTreeNode root;
	  private DefaultTreeModel model;
	  public TreeMenu()
	  {
	    super();
	    this.setRootVisible(true);
	    NodeData rootData = new NodeData("Root");
	    root = new DefaultMutableTreeNode(rootData);
	    model = new DefaultTreeModel(root);
	    model.setRoot(root);
	    this.setModel(model);
	    this.addMouseListener(new LinktoEvent());
	    this.setCellRenderer(new CellRender());
	    this.testLoaddata();
	  }
	 
	  private void testLoaddata()
	  {
	    Hashtable table = new Hashtable();
	    long seeds = java.util.Calendar.getInstance().getTimeInMillis();
	    for(int i = 0 ; i < 10 ; i ++)
	    {
	      Random r = new Random(seeds);
	      NodeData nd = new NodeData(String.valueOf(r.nextInt(1000)));
	      seeds += r.nextInt(1000);
	      Vector vec = new Vector();
	      for(int j = 0 ; j < 3 ; j++)
	      {
	        double min = r.nextDouble();
	        seeds += min;
	        double max = r.nextDouble();
	        seeds += max;
	        double value = r.nextDouble();
	        seeds += value;
	        vec.addElement(new NodeData(min,max,value,"www.csdn.NET"));
	      }
	      table.put(nd,vec);
	    }
	    this.LoadData(table);
	  }
	 
	 
	 
	  public void LoadData(Hashtable nodes)
	  {
	    Vector child;
	    Vector parent = new Vector();
	    java.util.Enumeration enum2 = nodes.keys();
	    while(enum2.hasMoreElements())
	    {
	      parent.addElement(enum2.nextElement());
	    }
	    for(int i = parent.size() - 1 ; i > 0 ; i--)
	    {
	      child = (Vector) nodes.get(parent.elementAt(i));
	      DefaultMutableTreeNode temp = this.addParentNode(
	                                        (NodeData)parent.elementAt(i));
	      DefaultMutableTreeNode parentNode =
	          this.addParentNode(temp,new NodeData("Three"));
	      for(int j = 0 ; j < child.size() ; j++)
	      {
	        this.addChildNode(parentNode,(NodeData) child.elementAt(j));
	      }
	    }
	  }
	 
	 
	 
	  public DefaultMutableTreeNode addParentNode(NodeData nodeData)
	  {
	    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeData);
	    ((DefaultMutableTreeNode) model.getRoot()).add(newNode);
	    return newNode;
	  }
	 
	 
	  public DefaultMutableTreeNode addParentNode(DefaultMutableTreeNode parentNode,
	                                              NodeData nodeData)
	  {
	    DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeData);
	    parentNode.add(newNode);
	    return newNode;
	  }
	 
	 
	 
	  public void addChildNode(DefaultMutableTreeNode node,NodeData nodeData)
	  {
	    DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(nodeData);
	    node.add(childNode);
	  }
	 
	 
	  public void reBuild()
	  {
	    root.removeAllChildren();
	    this.testLoaddata();
	  }
	 
	 
	  class LinktoEvent extends MouseAdapter
	  {
	    public void mouseClicked(MouseEvent me)
	    {
	      DefaultMutableTreeNode node;
	      TreePath selectedPath = TreeMenu.this.getPathForLocation(me.getX(),me.getY());
	      if(selectedPath !=null )
	      {
	        node = (DefaultMutableTreeNode)
	            selectedPath.getLastPathComponent();
	        if (node != null && node.isLeaf()) {
	          NodeData nd = (NodeData) node.getUserObject();
	          //The leaf that has url will be display a dialog.
	          if(nd.isLeaf())
	          {
	            JOptionPane.showConfirmDialog(TreeMenu.this, nd.getUrl());
	            //You can implment your function.
	          }
	        }
	      }
	    }
	  }
	}
	 
	 
	class NodeData
	{
	  private String name;
	  private double min;
	  private double max;
	  private double value;
	  private boolean isLeaf = false;
	  private String url = null;
	 
	 
	  public NodeData(String name)
	  {
	    this.name = name ;
	    this.isLeaf = false;
	  }
	 
	 
	  public NodeData(double min,double max,double value,String url)
	  {
	    this.min = min ;
	    this.max = max ;
	    this.value = value;
	    this.isLeaf = true;
	    this.url = url;
	  }
	 
	 
	  public boolean isLeaf()
	  {
	    return this.isLeaf ;
	  }
	 
	 
	  public boolean isOverflow()
	  {
	    if(this.isLeaf == true)
	    {
	      if(value <= max && value >= min)
	      {
	        return true ;
	      }
	      else
	      {
	          return false;
	      }
	    }
	    else
	    {
	        return false;
	    }
	  }
	 
	 
	 
	  public String toString()
	  {
	    if(this.isLeaf())
	    {
	      return String.valueOf(value);
	    }
	    else
	    {
	      return this.name;
	    }
	  }
	 
	 
	  public void setUrl(String newUrl)
	  {
	    this.url = newUrl;
	  }
	  public String getUrl()
	  {
	    return this.url;
	  }
	}
	 
	 
	class CellRender extends JLabel
	    implements TreeCellRenderer {
	  protected Color selectedBackground;
	  protected Color selectedForeground;
	  protected Color noselectedBackground;
	  protected Color noselectedForeground;
	  protected Color overflowBackground = Color.yellow;
	  protected Color overflowForeground = Color.red;
	  protected Color overflowSelectedBG = Color.green;
	  protected Color overflowSelectedFG = Color.black;
	  public CellRender()
	  {
	    super();
	    this.selectedBackground = Color.blue;
	    this.selectedForeground = Color.green;
	    this.noselectedBackground = Color.white;
	    this.noselectedForeground = Color.blue;
	    this.setForeground(this.noselectedForeground);
	    this.setBackground(this.noselectedBackground);
	  }
	 
	  public Component getTreeCellRendererComponent(JTree tree, Object value,
	                                                boolean selected,
	                                                boolean expanded, boolean leaf,
	                                                int row, boolean hasFocus) {
	    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
	    NodeData nd ;
	 
	      if(leaf)
	      {
	          nd = (NodeData) node.getUserObject();
	      }
	      else
	      {
	          nd = checkChild(node);
	      }
	      if (!nd.isOverflow()) {
	          if (selected)
	          {
	            this.setForeground(this.selectedForeground);
	            this.setBackground(this.selectedBackground);
	          }
	          else
	          {
	            this.setBackground(this.noselectedBackground);
	            this.setForeground(this.noselectedForeground);
	          }
	        }
	        else {
	          if(selected)
	          {
	            this.setBackground(this.overflowSelectedBG);
	            this.setForeground(this.overflowSelectedFG);
	          }
	          else
	          {
	            this.setBackground(this.overflowBackground);
	            this.setForeground(this.overflowForeground);
	          }
	        }
	 
	      this.setText(value.toString());
	    return this;
	  }
	  private NodeData checkChild(DefaultMutableTreeNode childNode)
	  {
	    NodeData child = null;
	    int count = childNode.getChildCount();
	    for(int i = 0 ; i < count ; i++)
	    {
	      DefaultMutableTreeNode childNodes =
	          (DefaultMutableTreeNode) childNode.getChildAt(i);
	      if(childNodes.isLeaf())
	      {
	        child = (NodeData) childNodes.getUserObject();
	        if(child.isOverflow())
	        {
	          break;
	        }
	      }
	      else
	      {
	          child = checkChild(childNodes);
	      }
	    }
	    return child;
	  }
	 
	}



運行結果如下圖所示:


再次感謝原文作者~

2017.04.22

大週六的還在實驗室學習~今天北京藍天,微風,天氣晴朗~適宜出門~


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