TreeCellRenderer使用方法简介

类别:Java 点击:0 评论:0 推荐:

在Jtree中如果要改变Jtree的显示方式要使用到TreeCellRender,通过对他的实现才能够得到不同显示方式的Jtree也使得Jtree的显示更加丰富多彩,如何使用这个接口哪。我借助下面的例子简单介绍一下,希望能够抛砖引玉。

其实实现这个类主要是对这个方法的实现:

public Component getTreeCellRendererComponent(JTree tree, Object value,

                                                boolean selected,

                                                boolean expanded, boolean leaf,

                                                int row, boolean hasFocus)

这个方法返回一个Component这个控件,也就是你要设置的树中节点的显示风格,当然在实现的时候你可以继承一个Jcomponent类的子类,也可以在类中设置一个私有变量然后返回。在这个方法中有很多参数,首先是Jtree 这个就是你要设置的树,对应的对象,然后是value

这个其实是节点,通过他你可以获得节点的数据,以及对应的子节点父节点等。接着是selected表示如果被选中时该如何显示。Expanded则表示如果出于扩展状态如何显示节点,然后是leaf,叶子节点的显示方式可以通过这个条件设置。还有row这个参数,对于那些没有伸缩的可以,如果有伸缩的话,row是随时改变的所以用的时候要小心,最后一个是是否拥有焦点,设置拥有焦点时的显示方式。实现了这个方法后,用setCellRende()方法设置一下这个类的实例就行了。下面通过一个例子来介绍TreeCellRenderer的使用方法,这个例子是一个朋友让我帮忙写的,拿到这里来希望他不要介意。数是由随机的Double构成的,不过如果是在某个范围则她和他的父节点直至根节点都会以不同的颜色显示。下面是代码,字节写的可能有点乱。

 

 

import javax.swing.*;

import java.awt.*;

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();

    Enumeration enum = nodes.keys();

    while(enum.hasMoreElements())

    {

      parent.addElement(enum.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;

  }

 

}

本文地址:http://com.8s8s.com/it/it15409.htm