如何强制Listviewer更新大小?当我向列表中添加一个比现有大小更长的元素时,列表查看器应该展开:
我以这种方式更新Listviewer:
lvConstraints.refresh();
答案 0 :(得分:1)
你确定在添加内容后调整大小是否是个好主意? IMO在运行时扩展和折叠会导致非常糟糕的用户体验。你不能想到包含在观众内部的元素的平均宽度吗?对于更长的元素,我建议你使用滚动功能。
如果您仍想在添加元素后更改viwer的大小,可以这样做:
viewer.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT);
viewer.getControl().pack();
示例:
public class Test {
private class MyContentProvider implements IStructuredContentProvider {
@Override
public Object[] getElements(Object inputElement) {
return ((List) inputElement).toArray(new MyModel[0]);
}
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
public class MyModel {
public String counter;
public MyModel(String counter) {
this.counter = counter;
}
@Override
public String toString() {
return "Item " + counter;
}
}
public Test(Shell shell) {
// final TableViewer v = new TableViewer(shell);
Composite c = new Composite(shell, SWT.NONE);
GridLayoutFactory.swtDefaults().applyTo(c);
GridDataFactory.defaultsFor(c).hint(100, 100).applyTo(c);
final ListViewer v = new ListViewer(c);
// v.setSize(200, 300);
v.setLabelProvider(new LabelProvider());
// for demonstration purposes use custom content provider
// alternatively you could use ArrayContentProvider.getInstance()
v.setContentProvider(new MyContentProvider());
v.setComparator(new ViewerComparator());
v.setInput(createModel());
GridDataFactory.defaultsFor(v.getControl()).align(SWT.BEGINNING, SWT.TOP).hint(100, 100).grab(true, true)
.applyTo(v.getControl());
// v.getTable().setLinesVisible(true);
Button b = new Button(c, SWT.NONE);
b.setText("button");
b.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
int nextInt = RandomUtils.nextInt(100);
String s = "";
for (int i = 0; i < nextInt; i++) {
s += "" + i;
}
// v.add(new MyModel(s));
((List) v.getInput()).add(new MyModel(s));
v.refresh();
v.getControl().computeSize(SWT.DEFAULT, SWT.DEFAULT);
v.getControl().pack();
}
});
}
private List<MyModel> createModel() {
List<MyModel> elements = new ArrayList<Test.MyModel>();
for (int i = 0; i < 10; i++) {
elements.add(new MyModel("" + i));
}
return elements;
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
new Test(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
要显示垂直滚动条,请使用SWT.V_SCROLL
样式创建查看器:如下所示:
final ListViewer v = new ListViewer(c, SWT.V_SCROLL);
为了防止调整更多,然后使用高度提示,在计算尺寸时使用高度提示,并执行以下操作(注意,您也可以提供宽度提示,以防止调整更多,然后是特定宽度)(注意::已删除pack()方法):
v.refresh();
Point computeSize = v.getControl().computeSize(SWT.DEFAULT, 200);
v.getList().setSize(computeSize);