Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove folder symbol which comes in front of each node from JTree in java

Tags:

java

swing

jtree

I am trying to remove the folder symbol from node of JTree which comes by default. How can I accomplish this?

like image 690
Vishwnath Tamrakar Avatar asked Dec 07 '22 22:12

Vishwnath Tamrakar


2 Answers

Just for reference, here's a complete example:

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.UIManager;

/** @see http://stackoverflow.com/questions/5260223 */
public class JTreeLite {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            //@Override
            public void run() {
                createGUI();
            }
        });
    }

    private static void createGUI() {
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Icon empty = new TreeIcon();
        UIManager.put("Tree.closedIcon", empty);
        UIManager.put("Tree.openIcon", empty);
        UIManager.put("Tree.collapsedIcon", empty);
        UIManager.put("Tree.expandedIcon", empty);
        UIManager.put("Tree.leafIcon", empty);

        JTree jt = new JTree();
        frame.add(jt);
        frame.pack();
        frame.setSize(300, 400);
        frame.setVisible(true);
    }
}

class TreeIcon implements Icon {

    private static int SIZE = 0;

    public TreeIcon() {
    }

    public int getIconWidth() {
        return SIZE;
    }

    public int getIconHeight() {
        return SIZE;
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        System.out.println(c.getWidth() + " " + c.getHeight() + " " + x + " " + y);
    }
}
like image 146
trashgod Avatar answered Dec 10 '22 13:12

trashgod


DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) jTree.getCellRenderer();
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);

The jtree uses CellRender, for example DefaultTreeCellRenderer, and you can dasable or change default nodes icon. Also, you can create custom cellRender and defined more dificult logic for you icon scheme.

tree.setCellRenderer(new DefaultTreeCellRenderer() {
                @Override
                public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                    JLabel component = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
                    ImageIcon iconPath = ((WizardNode) value).getIcon();
                    component.setIcon(iconPath);
                    return this;
                }
            });
like image 35
Vadim Komyshenets Avatar answered Dec 10 '22 13:12

Vadim Komyshenets