开发者

Expanded JTree Rendering

When the tree is expanded and I开发者_开发技巧 tried to rename the tree node not all the name displayed only about 4 5 letters and the others as (...) but if the tree is collapsed, every thing is OK. The following is my custom tree cell render:

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


label.setSize(label.getHeight(),value.toString().length());
  1. This method takes width and height, you switched both parameters.
  2. String.length() returns only the letter count, not the display size of the string. If you want to get the width of the string rendered with the font of the DefaultRenderer, use getFont().getStringBounds("yourString", getFontMetrics(getFont()).getFontRenderContext()).getWidth();

You can try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜