Java 如何在SWT中使用鼠标滚轮滚动已滚动的组合

Java 如何在SWT中使用鼠标滚轮滚动已滚动的组合,java,swt,mousewheel,Java,Swt,Mousewheel,我想知道是否可以使用鼠标滚轮滚动ScrolledComposite。默认情况下,它不工作 显然,有必要为您的组合创建鼠标滚轮侦听器。您可以使用以下内容作为基础: scrolledComposite = new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL); GridData scrollGridData = new GridData(SWT.FILL, SWT.FILL, true, true); scrol

我想知道是否可以使用鼠标滚轮滚动
ScrolledComposite
。默认情况下,它不工作

显然,有必要为您的组合创建鼠标滚轮侦听器。您可以使用以下内容作为基础:

    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--;
                }
            }
        });
scrolledComposite=新的scrolledComposite(父级,SWT.H|u SCROLL | SWT.V|u SCROLL);
GridData scrollGridData=新的GridData(SWT.FILL,SWT.FILL,true,true);
scrolledComposite.setLayoutData(scrollGridData);
布局=新的GridLayout();
scrolledComposite.setLayout(布局);
compositeWrapper=新组合(scrolledComposite);
setLayoutData(新的GridData(SWT.FILL,SWT.FILL,true,true));
compositeWrapper.setLayout(布局);
scrolledComposite.setExpandHorizontal(true);
scrolledComposite.setExpandVertical(true);
scrolledComposite.addListener(SWT.MouseWheel,new Listener()){
公共无效handleEvent(事件){
int wheelCount=event.count;
wheelCount=(int)Math.ceil(wheelCount/3.0f);
while(轮数<0){
scrolledComposite.getVerticalBar().setIncrement(4);
轮数++;
}
而(轮数>0){
scrolledComposite.getVerticalBar().setIncrement(-4);
轮数--;
}
}
});

我不确定@AlexanderGavrilov为什么要写这么多代码,以下代码对我也很有用:

scrolledComposite.addListener(SWT.MouseWheel, new Listener() {
    public void handleEvent(Event event) {
        scrolledComposite.getVerticalBar().setIncrement(e.count*3);
    }
});

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

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

非常感谢Alexander。默认情况下,使用鼠标滚轮滚动效果很好。您使用的是哪个操作系统?e.count可以是负数,increment必须是正数,因此需要Math.abs。