如何在SWT中使用鼠标滚轮滚动已滚动的复合控件

3

请问是否可以使用鼠标滚轮来滚动 ScrolledComposite?默认情况下无法实现。


使用鼠标滚轮进行滚动默认情况下可以正常工作。您使用的是哪个操作系统? - Baz
3个回答

2

在Google搜索后,我找到了一个简单的解决方案,

scrolledComposite.addListener(SWT.Activate, new Listener() {
  public void handleEvent(Event e) {
    scrolledComposite.setFocus();
  }
});

2

显然,为您的复合控件创建鼠标滚轮监听器是必要的。您可以使用以下代码作为基础:

    scrolledComposite = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
    GridData scrollGridData = new GridData(SWT.FILL, SWT.FILL, true, true);
    scrolledComposite.setLayoutData(scrollGridData);
    layout = new GridLayout();
    scrolledComposite.setLayout(layout);

    compositeWrapper = new Composite(scrolledComposite);
    compositeWrapper.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    compositeWrapper.setLayout(layout);
    scrolledComposite.setExpandHorizontal(true);
    scrolledComposite.setExpandVertical(true);

    scrolledComposite.addListener(SWT.MouseWheel, new Listener() {
            public void handleEvent(Event event) {
                int wheelCount = event.count;
                wheelCount = (int) Math.ceil(wheelCount / 3.0f);
                while (wheelCount < 0) {
                    scrolledComposite.getVerticalBar().setIncrement(4);
                    wheelCount++;
                }

                while (wheelCount > 0) {
                    scrolledComposite.getVerticalBar().setIncrement(-4);
                    wheelCount--;
                }
            }
        });

非常感谢你,Alexander。 - Jayakrishnan Salim

2
我不确定@AlexanderGavrilov为什么要写那么多代码,下面的代码对我也适用:
scrolledComposite.addListener(SWT.MouseWheel, new Listener() {
    public void handleEvent(Event event) {
        scrolledComposite.getVerticalBar().setIncrement(e.count*3);
    }
});

e.count 可能为负数,而增量必须为正数,因此需要使用 Math.abs。 - Chris Stamm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接