JTree叶子节点添加图标

package com.wsy.JComPz;
import java.awt.Component;
import java.util.Calendar;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JTree;

import javax.swing.tree.DefaultTreeCellRenderer;



public class LeafIconTest {

private JFrame jf = null;
/**

* @param args

*/

public static void main(String[] args) {

LeafIconTest lit = new LeafIconTest();

lit.test();

}
private void test() {

jf.show();

}
public LeafIconTest() {
super();
jf = new JFrame("Leaf Icon Test");
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setSize(200, 300);
jf.getContentPane().add(getJTree());
}
private Component getJTree() {

JTree jt = new JTree();

jt.setCellRenderer(new DefaultTreeCellRenderer() {

public Component getTreeCellRendererComponent(JTree tree,

Object value, boolean sel, boolean expanded, boolean leaf,

int row, boolean hasFocus) {

System.out.println("[DEBUG] "

+ Calendar.getInstance().getTime().toGMTString()

+ "  getLeafIcon invoked");

super.getTreeCellRendererComponent(tree, value, sel, expanded,

leaf, row, hasFocus);

if (leaf) {

setIcon(getLengthIcon(value));

}

return this;

}

});

return jt;

}
protected Icon getLengthIcon(Object value) {

ImageIcon ii;

// We use the length of the string representation of the node to

// determine the icon.

// In real world, we need to determine this by the

// 'male | female' attribute of the tree node, which can be extracted

// from the parameter 'value'

int length = value.toString().length();

if (length == 5 || length == 3) {

ii = new ImageIcon("e:/model.png");

} else {
ii = new ImageIcon("e:/model.png");

}

System.out.println(value.toString());

return ii;

}

}

你可能感兴趣的:(swing)