效果如上图
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.plaf.ColorUIResource;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
/**
* 树的渲染工具类,实现了将组件挂到树上
* @author 崔耀强 20150507
* @version 1.1
* */
public class TreeComponentRenderer extends JPanel implements TreeCellRenderer {
private static final long serialVersionUID = 1L;
private TreeComponent button;
private DefaultMutableTreeNode root;
/**
* @param button 需要挂到树上的组件
* @param root 树的根节点
*/
public TreeComponentRenderer(TreeComponent button,DefaultMutableTreeNode root) {
setLayout(null);
//button = new MyComponentUI2();
this.button=button;
this.root=root;
add(button);
}
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
DefaultMutableTreeNode root2=(DefaultMutableTreeNode) value;
if(leaf&&!root2.getParent().equals(root)){
Equipment o= (Equipment) root2.getUserObject();
if(o.getEquipmentType().getImgUrl()!=null){
//UNDO 分组
if(o.getEquipmentType().getIsGroup()==0){
button.setPreferredSize(new Dimension(TreeComponent.compUI2Width,TreeComponent.compUI2Hight));
//CD4组
button.setLableText(o.getEquipmentType().getName()+"组");
button.setLableImage(o.getEquipmentType().getImgUrl());
button.setTextFiledText(o.getEquipmentType().getNum()+"");
button.setTextFiledBackGround(Color.lightGray);
button.setJlBackGround(Color.gray);
}else{
button.setPreferredSize(new Dimension(TreeComponent.compUI2Width,TreeComponent.compUI2Hight));
button.setLableText(o.getId()+"");
button.setLableImage(o.getEquipmentType().getImgUrl());
button.setTextFiledText(o.getLocation());
button.setTextFiledBackGround(Color.lightGray);
button.setJlBackGround(Color.gray);
}
}
return this;
} else{
EquipmentType o= (EquipmentType) root2.getUserObject();
if(o.getImgUrl()!=null){
button.setPreferredSize(new Dimension( TreeComponent.compUI2Width,TreeComponent.compUI2Hight));
button.setLableText(o.getName());
button.setLableImage(o.getImgUrl());
button.setTextFiledText(o.getNum()+"");
button.setTextFiledBackGround(Color.lightGray);
button.setJlBackGround(Color.gray);
}
return this;
}
}
@Override
public Dimension getPreferredSize() {
Dimension d_button = button.getPreferredSize();
return new Dimension(d_button.width ,
( d_button.height));
}
@Override
public void doLayout() {
Dimension d_button = button.getPreferredSize();
button.setBounds(4, 0,d_button.width, d_button.height );
}
//设置叶子的背景颜色
public void setBackground(Color color) {
if (color instanceof ColorUIResource)
color = null;
super.setBackground(color);
}
}