我创建了一个显示文件列表的 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;
}
}