1

我创建了一个显示文件列表的 JTree。这些文件的长度不同。我想在 JTree 中以相同的长度显示它们,例如 20 个字符。如果名称大于 20 个字符,它应该出现在工具提示中。

我怎么能意识到它? 下面是我的 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;
    }
}
4

1 回答 1

3

您可以调整标签上的文本以限制大小,例如

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

笔记:

getPreferredSize您无缘无故地覆盖了,因为渲染器是一个组件这一事实并未在您的代码中使用。getTreeCellRendererComponent您在方法中返回一个标签

于 2012-05-03T12:37:25.153 回答