Question

I have a Tree node. I want an image to be displayed beside the node name when the tree is viewed. How do I go about?

Was it helpful?

Solution

  1. create an ImageIcon from your image

    ImageIcon icon = ....; (there are a number of ways to do this)

  2. create an instance of DefaultTreeCellRenderer

    DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();

  3. set the leaf icon field of the renderer

    renderer.setLeafIcon(icon);

  4. set the tree's renderer

    tree.setCellRenderer(renderer);

if you can't figure it out try the demo

OTHER TIPS

You can use a custom leaf renderer . Override the getTreeCEllRendererComponent () method.

When you render a component .

Use a panel and put the text first and the icon folliwng the text .

And then return the component.

public Component getTreeCellRendererComponent(JTree tree, Object value,
        boolean selected, boolean expanded, boolean leaf, int row,
        boolean hasFocus) {


    JLabel l = (JLabel)renderer.getTreeCellRendererComponent(
            tree, "", true, expanded, leaf, row, true);
    Component com = renderer.getTreeCellRendererComponent(
            tree, "", true, expanded, leaf, row, true);
    l.setIcon(YOUR_IMAGE);
    l.setText(value.toString());



        panel.removeAll();
        panel.add(this, BorderLayout.EAST);
        panel.add(j);
        return panel;



}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top