I need to determine the width of the text in a TextBox in Google Web Toolkit.
I have a proportional font, so I can’t just use something like getText().length() * characterWidth.
What I’m trying to do is resize the text so it always fits into the TextBox. That’s why I need width of the text to calculate needed font size.
Only solution I can think of is to make a map of widths of characters of the font I use and calculate the width of the text as a sum of widths of its individual characters.
I solved the problem as Corvus did, by introducing an additional
Labelelement and hiding it with CSS. I copy the text from theTextBoxto theLabeland retrieve the width byLabel.getOffsetWidth().However, I needed additional code to
I found that I could match styles by calling
The prewrap style referenced in the above statement must be defined somewhere as
This extra style is required because the built-in style for the textbox contains a
pre-wrapdirective which does not appear in the style list returned bytextbox.getStyleName().I also added an extra two spaces at the end of the label’s text string when calculating the width so that the text won’t jump back and forth so much when the user is typing.