CustomTreeCellRenderer.java Source code

Java tutorial

Introduction

Here is the source code for CustomTreeCellRenderer.java

Source

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeCellRenderer;

class CustomTreeCellRenderer extends DefaultTreeCellRenderer {
    ImageIcon rendererIcon;

    public void setRendererIcon(ImageIcon myIcon) {
        this.rendererIcon = myIcon;
    };

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

        super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

        JLabel label = (JLabel) this;

        label.setIcon(rendererIcon);

        return this;
    }
}

public class Main {
    public static void main(String[] args) {
        ImageIcon iconWhite = new ImageIcon("white.jpg");
        ImageIcon iconBlack = new ImageIcon("black.jpg");
        ;
        JFrame frame = new JFrame();
        frame.setContentPane(new JPanel(new BorderLayout()));

        JTree tree = new JTree();
        frame.getContentPane().add(tree);

        CustomTreeCellRenderer renderer = new CustomTreeCellRenderer();
        renderer.setRendererIcon(iconWhite);
        tree.setCellRenderer(renderer);

        JPanel panelButtons = new JPanel();

        JButton buttonWhite = new JButton("");
        buttonWhite.setIcon(iconWhite);
        JButton buttonBlack = new JButton("");
        buttonBlack.setIcon(iconBlack);

        buttonBlack.addActionListener(e -> {
            renderer.setRendererIcon(iconBlack);
            tree.repaint();
        });

        panelButtons.add(buttonBlack);
        panelButtons.add(buttonWhite);
        frame.getContentPane().add(panelButtons, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

    private static class CustomTreeCellRenderer extends DefaultTreeCellRenderer {
        ImageIcon rendererIcon;

        public void setRendererIcon(ImageIcon myIcon) {
            this.rendererIcon = myIcon;
        }

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

            Component ret = super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row,
                    hasFocus);

            JLabel label = (JLabel) ret;
            label.setIcon(rendererIcon);
            return ret;
        }
    }
}