如何正确使用ScrolledComposite?
以下略有修改Snipped166:
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class Snippet166 {
public static void main(String[] args) {
Display display = new Display();
Image image1 = display.getSystemImage(SWT.ICON_WORKING);
Image image2 = display.getSystemImage(SWT.ICON_QUESTION);
Image image3 = display.getSystemImage(SWT.ICON_ERROR);
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final ScrolledComposite scrollComposite = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.BORDER);
final Composite parent = new Composite(scrollComposite, SWT.NONE);
for(int i = 0; i <= 50; i++) {
Label label = new Label(parent, SWT.NONE);
if (i % 3 == 0) label.setImage(image1);
if (i % 3 == 1) label.setImage(image2);
if (i % 3 == 2) label.setImage(image3);
}
RowLayout layout = new RowLayout(SWT.HORIZONTAL);
layout.wrap = false;
parent.setLayout(layout);
scrollComposite.setContent(parent);
scrollComposite.setExpandVertical(true);
scrollComposite.setExpandHorizontal(true);
scrollComposite.addControlListener(new ControlAdapter() {
@Override
public void controlResized(ControlEvent e) {
Rectangle r = scrollComposite.getClientArea();
scrollComposite.setMinSize(parent.computeSize(r.width, SWT.DEFAULT));
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
我希望它能显示带水平滚动条的长水平行标记。
不幸的是它不会绘制滚动条。
另外我不明白,为什么这个例子应该如此复杂?为什么我不能把一些大的东西放在ScrolledComposite上滚动?
此外,我不理解setContent()
方法的必要性,因为内容总是在SWT中的构造函数中设置。
更新
我发现,我可以手动设置大小,然后会出现滚动。
public class Snippet166_mod01 {
public static void main(String[] args) {
Display display = new Display();
Image image1 = display.getSystemImage(SWT.ICON_WORKING);
Image image2 = display.getSystemImage(SWT.ICON_QUESTION);
Image image3 = display.getSystemImage(SWT.ICON_ERROR);
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final ScrolledComposite scrollComposite = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.BORDER);
final Composite parent = new Composite(scrollComposite, SWT.NONE);
for(int i = 0; i <= 50; i++) {
Label label = new Label(parent, SWT.NONE);
if (i % 3 == 0) label.setImage(image1);
if (i % 3 == 1) label.setImage(image2);
if (i % 3 == 2) label.setImage(image3);
}
RowLayout layout = new RowLayout(SWT.HORIZONTAL);
layout.wrap = false;
parent.setLayout(layout);
// how to calculate actual size?
parent.setSize(1000, 100);
// what this is for?
scrollComposite.setContent(parent);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
所以,我想知道,如何自动设置尺寸?是否可以将parent
控件的大小精确设置为内部51个图像的宽度?
答案 0 :(得分:1)
你还必须告诉ScrolledComposite
它的最小尺寸:
scrolled.setMinSize(group.computeSize(SWT.DEFAULT, SWT.DEFAULT));
scrolled.setExpandHorizontal(true);
scrolled.setExpandVertical(true);
将所有孩子添加到群组后执行此操作。