我正在研究这个Composite
画布上还有其他Composite
可以添加和删除。
我对整个布局概念的理解仍然很模糊。
当孩子被添加到容器中时,考虑到容器有一个GridData
它填充了父级,父级不应该也知道子级调整了大小吗?由于外壳(顶部父级)的原因,子级在放置其容器后仍保持隐藏状态。
如果问题太模糊,请随时询问更多细节。另外,请尽量不要指给我了解 SWT 中的布局文章。
/**
*
* @author ggrec
*
*/
public class SSCCE
{
// ==================== 2. Instance Fields ============================
private Composite componentContainer;
private int componentCount = 0;
// ==================== 3. Static Methods =============================
public static void main(final String[] args)
{
new SSCCE();
}
// ==================== 4. Constructors ===============================
private SSCCE()
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
createContents(shell);
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
// ==================== 5. Creators ===================================
private void createContents(final Composite parent)
{
parent.setLayout(new GridLayout());
parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
final Button button = new Button(parent, SWT.PUSH);
button.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
button.setText("Add New Component");
button.addSelectionListener(new SelectionAdapter()
{
@Override public void widgetSelected(final SelectionEvent e)
{
addNewComponent();
componentContainer.layout();
}
});
componentContainer = new Composite(parent, SWT.BORDER);
componentContainer.setLayout(new GridLayout());
componentContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
}
// ==================== 6. Action Methods =============================
private void addNewComponent()
{
final Composite component = new Composite(componentContainer, SWT.BORDER);
component.setLayout(new FillLayout());
component.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
final Label label = new Label(component, SWT.NONE);
label.setText( String.valueOf(componentCount++) );
}
}
Fun fact:
这个问题是 veeery 相关的9 分钟前发布的另一篇文章 https://stackoverflow.com/questions/20204367/how-to-dynamically-add-swt-widgets-to-a-composite。有人要么是通灵的,要么是在跟踪我。