Question

I have created a JTree which shows a list of files. these files have not the same length. I want to show all of them with the same length in the JTree for example 20 character. If the name is bigger than 20 character, it should appears in tool tip.

How can i realize it? below is my cellRenderer.

 private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
    private Map<String, Icon> iconCache = new HashMap<String, Icon>();
    private Map<File, String> rootNameCache = new HashMap<File, String>();

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

        FileTreeNode ftn = (FileTreeNode) value;
        File file = ftn.file;
        String filename = "";
        if (file != null) {
            if (ftn.isFileSystemRoot) {
                filename = this.rootNameCache.get(file);
                if (filename == null) {
                    filename = fsv.getSystemDisplayName(file);
                    this.rootNameCache.put(file, filename);
                }
            } else {
                filename = file.getName();
            }
        }
        JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
                filename, sel, expanded, leaf, row, hasFocus);
        if (sel)
            this.setFont(getFont().deriveFont(Font.BOLD));
        else
            this.setFont(getFont().deriveFont(Font.PLAIN));
        if (file != null) {
            Icon icon = this.iconCache.get(filename);
            if (icon == null) {
                icon = fsv.getSystemIcon(file);
                this.iconCache.put(filename, icon);
            }
            result.setIcon(icon);
        }
        return result;
    }

    @Override
    public Dimension getPreferredSize() {
        Dimension dim = super.getPreferredSize();
        FontMetrics fm = getFontMetrics(getFont());
        char[] chars = getText().toCharArray();

        int w = getIconTextGap() + 40;
        for (char ch : chars)  {
            w += fm.charWidth(ch);
        }
        w += getText().length();
        dim.width = w;
        return dim;
    }
}
Was it helpful?

Solution

You could adjust the text on your label to limit the size, e.g.

JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,
                filename, sel, expanded, leaf, row, hasFocus);
result.setText( fileName.subString( 0, Math.min( 20, fileName.length() ) );
result.setTooltip( fileName );

Note:

You override the getPreferredSize for no reason, since the fact that the renderer is a component is not used in your code. You return a label in the getTreeCellRendererComponent method

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