Reputation: 4216
I have a Text which will display different data of different length. Initially I was using a Textbox of fixed length. But, obviously It was not working. Then, I tried to get the length of the text, using that length as a width of the Text , like this -
textName = new Text(composite, SWT.BORDER);
String myText = tree.getSelection()[0].getText();
int length = myText.length();
textName.setBounds(76, 28, length, 21);
textName.setText(myText);
But, I found that the length of a string and the width of the Text field in SWT, are quite different. So, is there any solution for this purpose? Obviously, I can set a higher value to the width.. But, I think, that will not be a good solution.
Upvotes: 0
Views: 2512
Reputation: 516
You can compute string size with current font size and type by:
GC gc = new GC(textName);
Point textSize = gc.textExtent(myText);
gc.dispose();
textSize gives you size of Your text in pixels. Then you could determine size of Text control to set.
Upvotes: 3
Reputation: 33010
You can let the Text
object calculate its default size.
First set the text, then call computeSize
which computes the screen pixel size of the text string:
Text textName = new Text(composite, SWT.BORDER);
String myText = tree.getSelection()[0].getText();
textName.setText(myText);
Point size = textName.computeSize(SWT.DEFAULT, SWT.DEFAULT);
textName.setBounds(76, 28, size.x, 21);
Upvotes: 1