You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通知ScrolledComposite进行调整?跨类场景下的实现方案

ScrolledComposite内容变化时的滚动条调整问题

常规处理方式

当ScrolledComposite的内容发生变化时,我们可以调用ScrolledComposite.setMinSize()方法来同步调整滚动条。示例代码如下:

Shell shell = new Shell();
shell.setSize(300, 200);
shell.setLayout(new FillLayout());

ScrolledComposite sc = new ScrolledComposite(shell, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
sc.setExpandHorizontal(true);
sc.setExpandVertical(true);

Composite content = new Composite(sc, SWT.NONE);
sc.setContent(content);

content.setLayout(new GridLayout());

Button button = new Button(content, SWT.NONE);
button.setText("Add a Button");
button.addListener(SWT.Selection, e -> {
    Button btn = new Button(content, SWT.NONE);
    btn.setText("" + System.currentTimeMillis());
    btn.requestLayout();
    
    sc.setMinSize(content.computeSize(SWT.DEFAULT, SWT.DEFAULT));
});

shell.open();

问题场景:组件分属独立类

如果ScrolledComposite和内容容器content分别在两个独立类中创建,甚至content都不知道父容器是ScrolledComposite,此时该如何通知ScrolledComposite调整滚动条?示例代码如下:

public static void main(String[] args) {
    new Test().execute();
}

class Test {
    
    void execute() {
        Shell shell = new Shell();
        shell.setSize(300, 200);
        shell.setLayout(new FillLayout());
        
        A a = new A();
        ScrolledComposite sc = a.createControl(shell);
        
        B b = new B();
        Control content = b.createContent(sc);
        sc.setContent(content);
        
        shell.open();
    }
    
}

class A {
    
    ScrolledComposite createControl(Composite parent) {
        ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
        sc.setExpandHorizontal(true);
        sc.setExpandVertical(true);
        
        return sc;
    }
    
}

class B {
    
    Control createContent(Composite parent) {
        Composite content = new Composite(parent, SWT.NONE);
        content.setLayout(new GridLayout());
        
        Button button = new Button(content, SWT.NONE);
        button.setText("Add a Button");
        button.addListener(SWT.Selection, e -> {
            Button btn = new Button(content, SWT.NONE);
            btn.setText("" + System.currentTimeMillis());
            btn.requestLayout();
        });
        
        return content;
    }
    
}

如上所示,类A和类B彼此独立、互不感知。

现有方案与思考

使用e4事件是一种可行方案:在B中发布内容变化事件,在A中订阅事件并触发滚动条调整。

不过这种方式略显繁琐。既然content的变化可以通过requestLayout()通知父容器,那是否可以直接在ScrolledCompositeLayout中处理滚动条的调整逻辑?


内容的提问来源于stack exchange,提问作者Bourbon_7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 02:00:20