How to track a mouse over a SWT composition from sub-controls?

I have my own control:

screenshot of my composite

I want to track a mouse and add a MouseTrackListener . Unfortunately, MouseEnter and MouseLeave events MouseEnter also generated when the mouse moves over parts of my composite element (this is a label and a button).

enter image description here

 [Mouse enter] - mouse enters the empty space [Mouse hover] - mouse is over the empty space [Mouse exit] - mouse moved over label [Mouse enter] - mouse leaves label and enters empty space [Mouse hover] - mouse over empty space [Mouse exit] - mouse leaves composite 

How can I track a composite as one part, not subcomponents?

 public class MyComposite extends Composite { public MyComposite(final Composite parent, final int style) { super(parent, style); final Label lbl = new Label(this, SWT.NONE); lbl.setBounds(10, 10, 78, 15); lbl.setText("My Composite"); final Button btn = new Button(this, SWT.NONE); btn.setBounds(190, 29, 75, 25); btn.setText("Ok"); pack(); } public static void main(final String[] args) { final Shell shell = new Shell(Display.getDefault()); shell.setText("Testcase"); shell.setLayout(new FillLayout()); final MyComposite comp = new MyComposite(shell, SWT.NONE); comp.addMouseTrackListener(new MouseTrackListener() { @Override public void mouseHover(final MouseEvent e) { System.out.println("[Mouse hover]"); } @Override public void mouseExit(final MouseEvent e) { System.out.println("[Mouse exit]"); } @Override public void mouseEnter(final MouseEvent e) { System.out.println("[Mouse enter]"); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } } 
+4
source share
1 answer

If you want to receive only mouse movement events, you can add an untyped event to the Composite . It should be something like

 final Composite comp = new Composite(shell, org.eclipse.swt.SWT.NONE); comp.addListener(SWT.MouseMove, new Listener() { public void handleEvent(Event event) { System.out.println("hit"); } }); 

If you add the same Listener instance to all MyComposite , you can capture all mouse movements.

Alternatively, you can use Display.addFilter to catch all mouse events and filter if those that happen on your Composite instance or any of its children.

The third option is to use Composite.setCapture to get all mouse events when the mouse enters the Composite area and stops capturing when it leaves.

Of these, I think the first option is probably the best performer.

+5
source

Source: https://habr.com/ru/post/1480712/


All Articles