我有一个 SWT 文本字段,其内容长度会动态变化。我需要使完整的文本可见。我正在使用下面的代码来做到这一点。
public class MyDynamicDialog extends TrayDialog {
Text errorMessageText;
ScrolledComposite scrolledComposite;
Shell shell;
DynamicData dynamicData;
public MyDynamicDialog (final Shell shell) {
super(shell);
this.shell = shell;
}
public MyDynamicDialog (final Shell shell, final DynamicData dynamicData) {
super(shell);
this.shell = shell;
this.dynamicData = dynamicData;
}
@Override
protected Control createDialogArea(final Composite parent) {
final GridLayout layout = new GridLayout();
parent.setLayout(layout);
this.scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL | SWT.BORDER);
this.scrolledComposite.setExpandHorizontal(true);
this.scrolledComposite.setExpandVertical(false);
final Composite composite = new Composite(this.scrolledComposite, SWT.NONE);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
composite.setSize(400, 400);
this.scrolledComposite.setContent(composite);
this.scrolledComposite.addControlListener(new ControlAdapter() {
@Override
public void controlResized(final ControlEvent e) {
final Rectangle clientArea =
MyDynamicDialog.this.scrolledComposite.getClientArea();
final Point minSize = MyDynamicDialog.this.scrolledComposite.getContent().computeSize(clientArea.width, SWT.DEFAULT);
MyDynamicDialog.this.scrolledComposite.getContent().setSize(minSize);
}
});
createErrorMessageText(composite);
return parent;
}
private void createErrorMessageText(final Composite parent) {
final GridData errText = new GridData(/*200, SWT.DEFAULT*/);
errText.grabExcessHorizontalSpace = true;
errText.horizontalSpan = 3;
errText.horizontalAlignment = GridData.FILL;
this.errorMessageText = new Text(parent, SWT.READ_ONLY /*| SWT.WRAP | SWT.MULTI*/);
this.errorMessageText.setLayoutData(errText);
this.errorMessageText.addModifyListener(new ModifyListener() {
public void modifyText(final ModifyEvent e) {
final int columns = MyDynamicDialog.this.errorMessageText.getText().length() + 3;
final GC gc = new GC (MyDynamicDialog.this.errorMessageText);
final FontMetrics fm = gc.getFontMetrics ();
final int width = columns * fm.getAverageCharWidth ();
final int height = fm.getHeight ();
gc.dispose ();
MyDynamicDialog.this.errorMessageText.setSize (MyDynamicDialog.this.errorMessageText.computeSize (width, height));
MyDynamicDialog.this.errorMessageText.redraw();
MyDynamicDialog.this.errorMessageText.getParent().layout();
}
});
}
}
使用这段代码,当文本很大时,它会从屏幕上消失。我无法在运行时调整文本字段的大小。在调整文本框的大小后,我还尝试再次调用滚动复合上的监听器。但它们都不起作用。请指出错误之处。
最佳答案
当您使用将覆盖您可能在控件上执行的任何 setSize
的布局时。
而是将控件的 GridData
上的 widthHint
设置为您想要的宽度(还有 heightHint
)。
您还必须布局整个对话框区域,然后调整 shell 的大小。
Composite dialogAreaComp = ... get the dialog area composite
dialogAreaComp.layout(true, true);
Shell shell = getShell();
shell.pack(true);
关于java - 动态调整 SWT 文本字段的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685635/