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

SWT ScrolledComposite滚动条禁用:如何启用并设置固定大小

SWT ScrolledComposite滚动条启用及固定大小修复方案

问题根源及修复要点

  • 返回错误的Composite:createContentArea需返回创建的ScrolledComposite而非内部容器comp,否则窗口会直接跳过滚动容器,导致滚动条失效。
  • 错误修改Shell布局:不应给parent.getShell()设置布局,这会破坏整个窗口的布局结构,应将布局应用到内部内容容器comp。
  • 滚动容器缺少布局配置:需给ScrolledComposite设置布局(如FillLayout),确保它能占满父容器空间;同时让内部容器的布局能撑开内容,触发滚动条逻辑。

修改后的完整代码

@Override
protected Composite createContentArea(Composite parent) {
    // 创建带水平/垂直滚动条的ScrolledComposite
    ScrolledComposite sc = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
    // 设置滚动容器的布局,使其占满父容器空间
    sc.setLayout(new FillLayout());
    // 开启滚动条始终显示
    sc.setAlwaysShowScrollBars(true);
    sc.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));

    // 创建内部内容容器
    Composite comp = super.createContentArea(sc);
    comp.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    // 给内部容器设置布局,保证内容能正确撑开
    FillLayout layout = new FillLayout();
    layout.marginWidth = 5;
    comp.setLayout(layout);

    // 添加内容链接控件
    Link l = new Link(comp, SWT.NONE);
    l.setText(
            "This a custom tooltip you can: \n- pop up any control you want\n- define delays\n - ... \nGo and get Eclipse from <a>http://www.eclipse.org</a>");
    l.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
    l.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            openURL();
        }
    });

    // 绑定滚动容器与内容,设置自动扩展及最小尺寸
    sc.setContent(comp);
    sc.setExpandHorizontal(true);
    sc.setExpandVertical(true);
    // 让滚动容器根据内容自动计算最小尺寸,也可替换为固定数值如sc.setMinSize(600, 400)
    sc.setMinSize(comp.computeSize(SWT.DEFAULT, SWT.DEFAULT));

    // 返回滚动容器作为内容区域
    return sc;
}

额外说明

  • 若需让ScrolledComposite自身保持固定大小,可添加sc.setSize(400, 300)(替换为目标宽高),同时确保父容器布局不会强制拉伸它。
  • 手动设置sc.setMinSize(宽度, 高度)时,当内容尺寸超过该值,滚动条会自动启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:05:39