[英]Restrict size of Text widget
We have a Text
widget whose input is changed dynamically. 我们有一个
Text
小部件,其输入是动态更改的。 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
. 我只是想知道是否可以通过任何方式限制此
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? 更改文本后,是否可以通过任何方式来更新“
Text
小部件的大小,但只能达到某个最大值?
So far, I tried to add a resize listener on the Text
. 到目前为止,我尝试在
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.
因此,上面的其他内容仍然会涉及。
You can use GridData#heightHint
to restrict the size of the Text
. 您可以使用
GridData#heightHint
来限制Text
的大小。 Here is an example that restricts the height to three (3) lines: 这是一个将高度限制为三(3)行的示例:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.