Search code examples
javatextscrollswtscrolledcomposite

Prevent scrolling on text field? Java SWT


I have a multi line text field inside of a ScrolledComposite. If my mouse is outside of the text field scrolling works fine but if my mouse is on the text field it stops scrolling the ScrolledComposite. I didn't set V_Scroll on the textfield so it doesn't scroll the text but moves it a bit up or down. How can I just continue scrolling the ScrolledComposite? Platform: MacOS

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;

public class Application {

public static void main (String [] args)
{
    Display display = new Display ();
    Shell shell = new Shell (display);
    shell.setText("Application");
    shell.setLayout(new FillLayout());

    ScrolledComposite c1 = new ScrolledComposite(shell, SWT.BORDER | SWT.V_SCROLL);

    Composite content = new Composite(c1, SWT.NONE);
    content.setLayout(new GridLayout(1,false));
    Text field = new Text(content, SWT.BORDER | SWT.MULTI | SWT.WRAP);
    field.setText("\n\n\n\n\nsome text some text some text some text some text some text\n\n\n\n");

    c1.setContent(content);
    
    c1.setExpandHorizontal(true);
    c1.setExpandVertical(true);
    c1.setMinSize(600, 600);
    
    shell.setSize(600, 300);
    shell.open ();
    while (!shell.isDisposed ()) {
        if (!display.readAndDispatch ()) display.sleep ();
    }
    display.dispose ();
}

}

Solution

  • Add the following:

    ScrollBar vbar = c1.getVerticalBar();
    field.addMouseWheelListener(new MouseWheelListener(){
      public void mouseScrolled(MouseEvent e){
        int pos = vbar.getSelection();
        int increment = vbar.getIncrement() * e.count;
        pos -= increment;
        if (pos < vbar.getMinimum()){
          pos = vbar.getMinimum();
        }
        if (pos > vbar.getMaximum()){
          pos = vbar.getMaximum();
        }
        vbar.setSelection(pos);
        c1.setOrigin(0,pos);
      }
    });
    

    You'd have to add the listener to every (scrollable) widget in the composite. Also, this doesn't take into account what happens if you have scroll bars on your text field, although that could be handled as well.