1 36 37 40 41 import javax.swing.Icon ; 42 import javax.swing.ImageIcon ; 43 import javax.swing.JLabel ; 44 import javax.swing.JTree ; 45 import javax.swing.tree.TreeCellRenderer ; 46 import javax.swing.tree.DefaultMutableTreeNode ; 47 import java.awt.Component ; 48 import java.awt.Color ; 49 import java.awt.Font ; 50 import java.awt.Graphics ; 51 52 public class SampleTreeCellRenderer extends JLabel implements TreeCellRenderer  53 { 54 55 static protected Font defaultFont; 56 57 static protected ImageIcon collapsedIcon; 58 59 static protected ImageIcon expandedIcon; 60 61 62 static protected final Color SelectedBackgroundColor = Color.yellow; 64 static 65 { 66 try { 67 defaultFont = new Font ("SansSerif", 0, 12); 68 } catch (Exception e) {} 69 try { 70 collapsedIcon = new ImageIcon (SampleTreeCellRenderer.class.getResource("/resources/images/collapsed.gif")); 71 expandedIcon = new ImageIcon (SampleTreeCellRenderer.class.getResource("/resources/images/expanded.gif")); 72 } catch (Exception e) { 73 System.out.println("Couldn't load images: " + e); 74 } 75 } 76 77 78 protected boolean selected; 79 80 86 public Component getTreeCellRendererComponent(JTree tree, Object value, 87 boolean selected, boolean expanded, 88 boolean leaf, int row, 89 boolean hasFocus) { 90 Font font; 91 String stringValue = tree.convertValueToText(value, selected, 92 expanded, leaf, row, hasFocus); 93 94 95 setText(stringValue); 96 97 setToolTipText(stringValue); 98 99 100 if(expanded) 101 setIcon(expandedIcon); 102 else if(!leaf) 103 setIcon(collapsedIcon); 104 else 105 setIcon(null); 106 107 108 SampleData userObject = (SampleData)((DefaultMutableTreeNode )value) 109 .getUserObject(); 110 if(hasFocus) 111 setForeground(Color.cyan); 112 else 113 setForeground(userObject.getColor()); 114 if(userObject.getFont() == null) 115 setFont(defaultFont); 116 else 117 setFont(userObject.getFont()); 118 119 120 this.selected = selected; 121 122 return this; 123 } 124 125 130 public void paint(Graphics g) { 131 Color bColor; 132 Icon currentI = getIcon(); 133 134 if(selected) 135 bColor = SelectedBackgroundColor; 136 else if(getParent() != null) 137 139 bColor = getParent().getBackground(); 140 else 141 bColor = getBackground(); 142 g.setColor(bColor); 143 if(currentI != null && getText() != null) { 144 int offset = (currentI.getIconWidth() + getIconTextGap()); 145 146 if (getComponentOrientation().isLeftToRight()) { 147 g.fillRect(offset, 0, getWidth() - 1 - offset, 148 getHeight() - 1); 149 } 150 else { 151 g.fillRect(0, 0, getWidth() - 1 - offset, getHeight() - 1); 152 } 153 } 154 else 155 g.fillRect(0, 0, getWidth()-1, getHeight()-1); 156 super.paint(g); 157 } 158 } 159
| Popular Tags
|