Search code examples
eclipsedialogswteclipse-rcpjface

How to set the location of SWT Dialog?


I have a button. If clicked a Dialog opens up. The Dialog always appears at the center of the screen even though I want to place it to a certain location.

Why is that? How can I set the location of my Dialog?

@Override
public void widgetSelected(SelectionEvent e) {
        Dialog dialog = new MyDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "MyDialog");
        dialog.open();
        Point pt = ImageDisplayHelper.getDisplay().getCursorLocation();
        System.out.println("location pt: "+pt); // pt is a valid location something like Point {1368, 220}
        dialog.getShell().setLocation(pt); // no effect whatsoever
        dialog.getShell().setLocation(10, 10); // no effect whatsoever
}

Solution

  • The dialog open method displays the dialog and waits for it to be closed. So setting the location after calling open is too late.

    Instead call the create method of dialog, then set the location and finally call open:

    dialog.create();
    
    ... set location
    
    dialog.open();
    

    An alternative is to override the

    protected Point getInitialLocation(Point initialSize)
    

    method in the dialog and return the location you want.