Question

What I want to do is: When I change the title of Group widget (by calling setText() method), I need to check the title, if contains certain characters, I'll do something.

Now the problem is, how to listen to the text modify event of Group widget?

I tried addListener(SWT.Modify, listener); method, (see the example below), it's not working.

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

public class Test {

    public static void main(String[] args)
    {
        final Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(1, false));
        shell.setText("Stackoverflow");

        final Group group = new Group(shell, SWT.NONE);
        group.setText("title0");

        group.addListener(SWT.Modify, new Listener() {

            @Override
            public void handleEvent(Event event) {
                // TODO Auto-generated method stub
                System.out.println("Group title changed");
            }

        });

        Button btn = new Button(shell, SWT.NONE);
        btn.setText("Press to set title of Group."); 

        btn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                // TODO Auto-generated method stub
                group.setText("title1"); 
            }

        });

        shell.pack();
        shell.open();

        while (!shell.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        display.dispose();
    }

}
Was it helpful?

Solution

I have workaround here use setData() method on Widget class and add PaintListener to Group Widget

group.setData(new String(group.getText()));

    group.addPaintListener(new PaintListener() {

        @Override
        public void paintControl(PaintEvent e) {
            if (e.widget instanceof Group) {
                Group grp = (Group)e.widget;
                String data = (String)grp.getData();
                if (!data.equals(grp.getText())) {
                    System.out.println("Title changed");
                    grp.setData(grp.getText()); //Keep new changed title as data
                }
            }

        }
    });

Whenever title changes paint event will trigger. I have kept group widget title text as data and comparing the changes in paint listener.

Note that paint listener will be called many times, so suggest you keep very less code inside this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top