SWT 动态添加ScrolledComposite子组件实现垂直滚动
时间: 2023-12-10 21:40:38 浏览: 142
在 SWT 中,可以使用 ScrolledComposite 控件来实现垂直滚动。但是,如果需要动态添加子组件,需要注意以下几点:
1. 在创建 ScrolledComposite 时,需要指定垂直滚动条的显示方式:
```
ScrolledComposite scrolledComposite = new ScrolledComposite(parent, SWT.V_SCROLL);
```
2. 在添加子组件时,需要设置子组件的布局数据,并将子组件添加到 ScrolledComposite 中:
```
Composite contentComposite = new Composite(scrolledComposite, SWT.NONE);
contentComposite.setLayout(new GridLayout(1, false));
for (int i = 0; i < 10; i++) {
Label label = new Label(contentComposite, SWT.NONE);
label.setText("Label " + i);
label.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
}
scrolledComposite.setContent(contentComposite);
```
3. 在添加完子组件后,需要调用 ScrolledComposite 的 setMinSize() 方法来设置内容区域的最小尺寸:
```
Point contentSize = contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
scrolledComposite.setMinSize(contentSize);
```
完整代码示例:
```
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class ScrolledCompositeDemo {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new GridLayout(1, false));
ScrolledComposite scrolledComposite = new ScrolledComposite(shell, SWT.V_SCROLL);
scrolledComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite contentComposite = new Composite(scrolledComposite, SWT.NONE);
contentComposite.setLayout(new GridLayout(1, false));
for (int i = 0; i < 10; i++) {
Label label = new Label(contentComposite, SWT.NONE);
label.setText("Label " + i);
label.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
}
scrolledComposite.setContent(contentComposite);
Point contentSize = contentComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
scrolledComposite.setMinSize(contentSize);
shell.setSize(200, 300);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
```
阅读全文
相关推荐
















