在我的代码中,org.eclipse.swt.widgets.ExpandBar
包含多个ExpandItem
。 ExpandBar
设置为滚动。如何在程序上滚动ExpandBar
?我查找了示例和API,但没有运气。
答案 0 :(得分:3)
好吧,将ExpandBar
包裹在ScrolledComposite
中并让它处理滚动。
这样做的好处是ScrolledComposite
有一个名为.setOrigin(int, int)
的方法,您可以使用该方法滚动到某个位置。
以下是一些示例代码:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
shell.setText("ExpandBar Example");
final ScrolledComposite scrolledComp = new ScrolledComposite(shell, SWT.V_SCROLL);
final ExpandBar bar = new ExpandBar(scrolledComp, SWT.NONE);
for (int i = 0; i < 3; i++)
{
Composite composite = new Composite(bar, SWT.NONE);
composite.setLayout(new GridLayout());
for (int j = 0; j < 10; j++)
new Label(composite, SWT.NONE).setText("Label " + i + " " + j);
ExpandItem item = new ExpandItem(bar, SWT.NONE, 0);
item.setText("Item " + i);
item.setHeight(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT).y);
item.setControl(composite);
}
bar.getItem(1).setExpanded(true);
bar.setSpacing(8);
/* Make sure to update the scrolled composite when we collapse/expand
* items */
Listener updateScrolledSize = new Listener()
{
@Override
public void handleEvent(Event arg0)
{
display.asyncExec(new Runnable()
{
@Override
public void run()
{
scrolledComp.setMinSize(bar.computeSize(SWT.DEFAULT, SWT.DEFAULT));
}
});
}
};
bar.addListener(SWT.Expand, updateScrolledSize);
bar.addListener(SWT.Collapse, updateScrolledSize);
scrolledComp.setContent(bar);
scrolledComp.setExpandHorizontal(true);
scrolledComp.setExpandVertical(true);
scrolledComp.setMinSize(bar.computeSize(SWT.DEFAULT, SWT.DEFAULT));
shell.setSize(400, 200);
shell.open();
/* Jump to the end */
scrolledComp.setOrigin(0, scrolledComp.getSize().y);
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
运行后看起来像这样:
正如你所看到的,滚动到最后。
<强>更新
好的,如果您想跳转到特定项目的位置,请执行以下操作:
添加Button
以测试功能。在Listener
内,获取y位置并滚动到它:
Button jumpTo = new Button(shell, SWT.PUSH);
jumpTo.setText("Jump to item");
jumpTo.addListener(SWT.Selection, new Listener()
{
private int counter = 0;
@Override
public void handleEvent(Event e)
{
int y = getYPosition(bar, counter);
/* Increment the counter */
counter = (counter + 1) % bar.getItemCount();
/* Scroll into view */
scrolledComp.setOrigin(0, y);
}
});
使用此方法获取y位置:
private static int getYPosition(ExpandBar bar, int position)
{
/* Calculate the position */
int y = 0;
for(int i = 0; i < position; i++)
{
/* Incorporate the spacing */
y += bar.getSpacing();
/* Get the item (On LINUX, use this line) */
ExpandItem item = bar.getItem(bar.getItemCount() - 1 - i);
/* Get the item (On WINDOWS, use this line) */
//ExpandItem item = bar.getItem(i);
/* Add the header height */
y += item.getHeaderHeight();
/* If the item is expanded, add it's height as well */
if(item.getExpanded())
y += item.getHeight();
}
return y;
}