JTree节点 JTree设置不同节点不同图标的最小化代码实例 JTree图标

为JTree的不同节点设置不同的图标。

我的例子中控制了只是设置节点的图标,

当然也可以设置文件夹的图标,不必赘言。

 

最小化代码如下:(我写了两个类,方便查看)

第一个类(共两个类):

import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

/**
 *欢迎和我联系:772333621
 * @author FL
 */
public class MyTreeCellRenderer extends DefaultTreeCellRenderer{

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
        if (leaf) {
            setLeafIconByValue(value);
        }
        return this;
    }
    public void setLeafIconByValue(Object value) {
        ImageIcon ii;
        int length = value.toString().length();
        if (length > 4) {
            ii = new ImageIcon("e:/0.jpg");
        } else {
            ii = new ImageIcon("e:/1.jpg");
        }
        System.out.println(value.toString());
        this.setIcon(ii);
    }
}

第二个类(共两个类):

import javax.swing.JFrame;
import javax.swing.JTree;

/**
 *
 * @author FL
 */
public class MainFrame extends JFrame{

    public static void main(String[] args) {
        MainFrame mainFrame = new MainFrame();
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.setSize(200, 300);
        JTree jTree = new JTree();
        jTree.setCellRenderer(new MyTreeCellRenderer());
        mainFrame.getContentPane().add(jTree);
        mainFrame.setVisible(true);
    }

}

 

你可能感兴趣的:(import,object,tree,class,string)