如何从java中的JTree中删除每个节点前面的文件夹符号

时间:2011-03-10 13:25:57

标签: java swing jtree

我正在尝试从JTree的节点中删除默认情况下的文件夹符号。 我怎么能做到这一点?

3 个答案:

答案 0 :(得分:9)

仅供参考,这是一个完整的例子:

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);
    }
}

答案 1 :(得分:2)

Swing教程专门讨论了这样做:

http://download.oracle.com/javase/tutorial/uiswing/components/tree.html#display

  

您可以轻松更改默认图标   用于叶子,膨胀的分支,或   折叠的分支节点。为此,你   首先创建一个实例   DefaultTreeCellRenderer。

答案 2 :(得分:2)

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

jtree使用CellRender,例如DefaultTreeCellRenderer,您可以使用dasable或更改默认节点图标。此外,您可以创建自定义cellRender并为您的图标方案定义更多难以理解的逻辑。

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;
                }
            });