Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWT - how to listen for mouse events, and retrieve their absolute position?

Tags:

java

swt

I am capturing mouse events inside of a shell with Composites by adding a Filter.

For now the events are positioned relative to the Composites, where they occure.
How can I retrieve MouseEvents absolute position? (Absolute position is the position with 0,0 in the left uper corner of the display).

parentShell.getDisplay().addFilter(SWT.MouseDown, new Listener() {
        @Override
        public void handleEvent(Event event) {
            //do not know the absolute position here
        }
    });
like image 854
Skip Avatar asked Dec 17 '25 23:12

Skip


2 Answers

You can use Control#toDisplay(int, int) to convert any relative coordinates to display relative absolute values.

public void handleEvent(Event event) {
    if (event.widget instanceof Control) {
        Point absolutePos = ((Control) event.widget).toDisplay(event.x, event.y);
        ...
    }
}

The above will work if the event you received is a mouse event, which it is in your example. You can also use Display#getCursorLocation() at any point to get absolute mouse location if you do not have a mouse event at hand.

like image 107
Waqas Ilyas Avatar answered Dec 19 '25 14:12

Waqas Ilyas


Following saved my day:

System.out.println("Click: " + parentShell.getDisplay().getCursorLocation());
like image 25
Skip Avatar answered Dec 19 '25 13:12

Skip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!