How to measure displayed string size?

Is there any way to measure displayed size of a string similar to Graphics.MeasureString in .NET?

It would be nice to write something like…


textField.setWidth(Reindeer.measureString(“A longest string user can enter.”, CssSizeUnit.EM));

Thanks.

Not a nice way no.

However, if you really really want to have that, you can do a trick with VerticalLayout and undefined and relative widths:

// A vertical layout with undefined width
VerticalLayout box = new VerticalLayout();
box.setSizeUndefined();

// This text field takes all the width given
// in the layout, which is the same as the
// width of the label.
TextField tf = new TextField("Give Date and Time");
tf.setWidth("100%");
tf.setMaxLength(10);
tf.setValue("01/01/2011 01:01");
box.addComponent(tf);

// The layout shrinks to fit this label
Label label = new Label("01/01/2011 01:01");
label.addStyleName("monospace");
label.setWidth(Sizeable.SIZE_UNDEFINED, 0);
label.setHeight("1em"); // Hide: Could be 0px
box.addComponent(label);

And in theme say:

.textfieldexample .v-label-monospace,
.textfieldexample .v-textfield {
    font-family: monospace;
}
.textfieldexample .v-label-monospace {
    padding: 0px 5px;
    color: #a0a0a0;
}

In real use, you’d need to make the width-template zero-height.

See the
on-line example
.

Yeah, it’s a bit ugly… Coincidentally, I just discussed this topic today. It would be handy if the TextField and TextArea had a setColumns() that would set the width. The method was deprecated just recently, because it actually just set the width with em-widths and was therefore equivalent to using setWidth(). The problem is that em-widths are a bit wider than (courier) letter columns. I don’t know why the method didn’t use the cols attribute in HTML, which does the thing. It could be that that would have compatibility issues in IE, for example.

Many thanks for your reply, Marko.

I probably should have described the original issue to be clear.

You see I have a heterogeneous table: some columns can be text or time or date fields, some - combo boxes, etc. I have not tried the custom TableFieldFactory approach yet, I took the container properties route and it worked just fine until I had to make it editable. If I do that the components in the “custom” columns get bigger and partly disappear as the column width remains the same. Besides there seems to be a a problem with combo box width (I made
a ticket
for it). So, I simply wanted to set width of everything myself every time i change the read/write mode. And, of course, 1 char = 1 em makes long strings too long.

Anyway, I’d like to try using a custom TableFieldFactory to see it it works out better. Overall it seems a better and cleaner approach for a heterogeneous table.

Cheers.