Reputation: 605
We have a Text
widget whose input is changed dynamically. The size is computed after setting a new input. The size should always be as small as possible
This works all fine. I was just wondering if it is in any way possible to restrict the size of this Text
. If a lot of lines are added to the text, it takes up all of the composite. Is there any way to update the size of the Text
widget after changing the text, but only up to a certain maximum value?
So far, I tried to add a resize listener on the Text
. The problem is though, that the widget is resized, but the space is taken from the buttom. So the other content above is covered anyways.
Upvotes: 0
Views: 102
Reputation: 36884
You can use GridData#heightHint
to restrict the size of the Text
. Here is an example that restricts the height to three (3) lines:
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell();
shell.setText("StackOverflow");
shell.setLayout(new GridLayout(1, false));
final Text text = new Text(shell, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
text.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true));
text.addListener(SWT.Modify, new Listener()
{
private int height = 0;
@Override
public void handleEvent(Event arg0)
{
int newHeight = computeHeight(text, 3);
if (newHeight != height)
{
height = newHeight;
GridData gridData = (GridData) text.getLayoutData();
gridData.heightHint = height;
text.setLayoutData(gridData);
text.getParent().layout(true, true);
}
}
});
shell.pack();
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
private static int computeHeight(Text text, int maxHeight)
{
int height = text.getText().split("\n", -1).length;
return Math.min(height, maxHeight) * text.getLineHeight();
}
Upvotes: 3