扩展了JTree渲染

时间:2011-08-21 13:19:41

标签: java swing jtree cellrenderer

当树被展开并且我试图重命名树节点时,并不是所有的名称只显示大约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;
    }
} 

1 个答案:

答案 0 :(得分:0)

label.setSize(label.getHeight(),value.toString().length());
  1. 此方法采用宽度和高度,您切换了两个参数。
  2. String.length()仅返回字母数,而不返回字符串的显示大小。如果要获取使用DefaultRenderer字体呈现的字符串的宽度,请使用getFont().getStringBounds("yourString", getFontMetrics(getFont()).getFontRenderContext()).getWidth();
  3. 你可以试试这个:

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