Search code examples
javaeventseclipse-pluginswt

How can I stop an SWT composite control from firing a MouseExit event when the mouse enters a component control?


I have subclassed org.eclipse.swt.widgets.Composite to create a new composite control. I want to capture MouseEnter and MouseExit events in this control but the problem I have is that when the mouse is hovered over a component in the control (say, a Label) the MouseExit event is fired, even though the label is part of the whole Composite.

Is there any way to stop this event being fired? I only want to see the event if the mouse leaves the total boundary of the control. Here is some example code to show you what I mean.

public class MyControl extends Composite{

Label label;

public MyControl(Composite parent, String label) {
    super(parent, SWT.NONE);
    label = new Label(this,0);
    label.setText(label);

    this.addListener(SWT.MouseEnter, new Listener() {
        @Override
        public void handleEvent(Event event) {
            // handle this event
        }           
    });
    this.addListener(SWT.MouseExit, new Listener() {
        @Override
        public void handleEvent(Event event) {
            // handle this event
        }           
    });
}

}


Solution

  • You can simply put an logic in your event handler to see if the control is a child of your new control and ignore it. Something like the following: (I haven't tested the code, but I think this should work for you)

        this.addListener(SWT.MouseExit, new Listener() {
            @Override
            public void handleEvent(Event event) {
                for (Control control : ParentClass.this.getChildren()) {
                    if (control == event.item)
                        return;
                }
                // handler logic goes here
            }           
        });