Search code examples
javaeclipseeclipse-rcpjfacercp

How to get x and y position of user click in Eclipse plugin + RCP


I am developing a plugin for email client using JFace + RCP using Eclipse. I am not developing any screens using eclipse, mail client will be the screen for this plugin.

I want to get the user clicked position in client.


Solution

  • You can use the addFilter method of Display to add a listener that is called for all mouse down events in the SWT code:

    Display display = Display.getDefault();
    
    display.addFilter(SWT.MouseDown, new Listener()
      {
        @Override
        public void handleEvent(Event event)
         {
           System.out.println("event " + event);
    
           if (event.widget instanceof Control) {
             Control control = (Control)event.widget;
             System.out.println("display " + control.toDisplay(event.x, event.y));
           }
         }
     });
    

    The Event passed to handleEvent has x and y fields for the mouse down event - these are relative to the control containing the event. The control is given in the widget field. I have shown code to convert these values to be absolute display values.

    Note: This only works for mouse down events in the current application and only for SWT code. In the past Lotus Notes used a lot of native code where this would not work, I don't know if this is still the case.