当树被展开并且我试图重命名树节点时,并不是所有的名称只显示大约4个5个字母而其他名称显示为(...)但是如果树被折叠,则每个都可以。以下是我的自定义树单元格渲染:
public class customTreeCellRenderer extends DefaultTreeCellRenderer {
public Component getTreeCellRendererComponent(JTree tree,
Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus){
super.getTreeCellRendererComponent(tree, value,
selected, expanded, leaf, row, hasFocus);
JLabel label = (JLabel) this ;
label.setSize(label.getHeight(),value.toString().length());
label.setText(value.toString());
label.repaint();
tree.revalidate();
this.repaint();
System.out.println("expanded "+expanded);
System.out.println("Custom "+ value.toString());
return label;
}
}
答案 0 :(得分:0)
label.setSize(label.getHeight(),value.toString().length());
getFont().getStringBounds("yourString", getFontMetrics(getFont()).getFontRenderContext()).getWidth();
你可以试试这个:
if (label.getGraphics() != null) {
final Rectangle2D r = getGraphics().getFontMetrics(getFont())
.getStringBounds(value.toString(), getGraphics());
final Dimension d = new Dimension((int) r.getWidth()
+ getIcon().getIconWidth() + getIconTextGap(), (int) r.getHeight());
label.setMaximumSize(d);
label.setPreferredSize(d);
label.setMinimumSize(d);
}