我确认问题可以通过我在问题中建议的第二种方法解决。 如果有人有更好的答案,请发表。
这种方法有这些对象:
AbstractLabelWithHeightOfAnotherControl / custom StackLayout
<>-- Other control
Composite / GridLayout
<>-- Label / GridData( SWT.BEGINNING, SWT.CENTER, false, true )
自定义 StackLayout 具有标签的宽度,但具有其他控件的高度。
此代码提供了一个抽象类,它支持各种其他控件的行为。
public abstract class AbstractLabelWithHeightOfAnotherControl extends Composite {
private Label m_label;
private Control m_otherControl;
/** Constructor.
* @param parent
* @param style
*/
public AbstractLabelWithHeightOfAnotherControl(Composite parent, int style) {
super( parent, style );
StackLayout stackLayout = new MyStackLayout();
this.setLayout( stackLayout );
Composite layerLabel = new Composite( this, SWT.NONE );
GridLayout layerLabelLayout = new GridLayout( 1, false );
layerLabelLayout.marginWidth = 0;
layerLabelLayout.marginHeight = 0;
layerLabel.setLayout( layerLabelLayout );
m_label = new Label( layerLabel, SWT.NONE);
m_label.setLayoutData( new GridData( SWT.BEGINNING, SWT.CENTER, false, true ) );
m_otherControl = makeOtherControl( this );
stackLayout.topControl = layerLabel;
}
protected abstract Control makeOtherControl( @Nonnull Composite parent );
public Label getLabel() {
return m_label;
}
private final class MyStackLayout extends StackLayout {
MyStackLayout() {
this.marginHeight = 0;
this.marginWidth = 0;
}
@Override
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
int width = m_label.computeSize( wHint, hHint, flushCache ).x;
int height = m_otherControl.computeSize( wHint, hHint, flushCache ).y;
if (wHint != SWT.DEFAULT) width = wHint;
if (hHint != SWT.DEFAULT) height = hHint;
return new Point(width, height);
}
}
}
实现类可以只提供这样的方法:
@Override
protected Control makeOtherControl( @Nonnull Composite parent ) {
return new Combo( parent, SWT.NONE );
}