添加元素时如何将 ScrolledComposite 的 ScrollBar 移动到底部?

问题描述

有一个 ScrolledComposite,带有一个可以在其中添加更多按钮的按钮,其想法是在添加新项目时始终将垂直滚动条移至底部。

如何实现?这是向 ScrolledComposite 添加按钮的示例代码:

public boolean open() {     
    shell = new Shell(getParent(),getStyle());
    shell.setText(getText());
    
    GridLayout gl_shell = new GridLayout(1,false);
    gl_shell.marginWidth = 20;
    shell.setLayout(gl_shell);
    
    final ScrolledComposite sc1 = new ScrolledComposite(shell,SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
    final Composite c1 = new Composite(sc1,SWT.NONE);
    sc1.setContent(c1);
    final GridLayout layout = new GridLayout();
    layout.numColumns = 1;
    c1.setLayout(layout);
    final Button b1 = new Button (c1,SWT.PUSH);
    b1.setText("first button");
    c1.setSize(200,200);

    final Button add = new Button(shell,SWT.PUSH);
    add.setText("add children");
    final int[] index = new int[]{0};
    add.addListener(SWT.Selection,new Listener() {
        public void handleEvent(final Event e) {
            index[0]++;
            final Button button = new Button(c1,SWT.PUSH);
            button.setText("button "+index[0]);
            // reset size of content so children can be seen - method 1
            c1.setSize(c1.computeSize(SWT.DEFAULT,SWT.DEFAULT));
            c1.layout();
        }
    });
    
    
    shell.layout();
    shell.pack(); //for wrap the dialog size to it's content width and height.
    
    //the dialog must be centered after doing shell.pack();
    Rectangle parentSize = getParent().getBounds();
    Rectangle shellSize = shell.getBounds();
    int x = parentSize.x + (parentSize.width - shellSize.width) / 2;
    int y = (int) (parentSize.y + (parentSize.height - shellSize.height) / 3.5);
    shell.setLocation(new Point(x,y));
    shell.open(); //we put this after setLocation() and pack() because we don't want to see the shell on the original position for some milliseconds
    
    Display display = getParent().getDisplay();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    
    
    return false;
}

解决方法

ScrolledComposite 有一个

public void showControl(Control control)

确保控件可见的方法。

还有

public void setShowFocusedControl(boolean show)

确保始终显示具有焦点的控件(内部使用 showControl)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...