如果文本框中的文字达到限制,我希望增加文本框的高度。实际上,如果文本框的宽度最多可以容纳15个字符,那么在15个字符之后我的文本框大小应该增加,这样我就可以看到文本框的两行。我正在使用多行文本框。
答案 0 :(得分:2)
这是可能的。如果您使用SWT.WRAP,当您超出文本小部件的线宽时,您的文本将自动在新行中继续。然而,高度将保持不变。因此,您必须在文本修改事件中计算它。为文本小部件设置新高度后,必须布局父级,以便计算文本小部件兄弟的新位置。
final Text text = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP);
text.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
Point textSize = text.computeSize(SWT.DEFAULT, SWT.DEFAULT);
Rectangle textTrim = text.computeTrim(0, 0, textSize.x,
text.getLineHeight());
final int textPadding = textTrim.height - text.getLineHeight();
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
int height = text.getLineCount() * text.getLineHeight()
+ textPadding;
text.setSize(text.getSize().x, height);
// need to layout parent, in order to change position of
// siblings
parent.layout();
}
});