Tuesday, February 19, 2013

Centering SWT ColorDialog

SWT includes ColorDialog class which exposes the native color dialog. Unfortunately, the dialog opens in the upper-left corner of the parent shell and there is no API to change this behavior. Fortunately, there is a trick that can be used to center the dialog instead.

final Shell parent = ...
final Rectangle bounds = parent.getBounds();

// There is no means to compute the size of the color dialog. In the following
// computations, measurements of the dialog on Windows 7 are used.

final int x = bounds.x + bounds.width / 2 - 120;       
final int y = bounds.y + bounds.height / 2 - 170;      

final Shell shell = new Shell( parent );
        
try
{
    shell.setBounds( x, y, 0, 0 );
            
    final ColorDialog dialog = new ColorDialog( shell );
            
    dialog.setText( ... dialog title ... );
    dialog.setRGB( ... initial color ... );
            
    final RGB pickedColor = dialog.open();
            
    if( pickedColor != null )
    {
        ...
    }
}
finally
{
    shell.dispose();
}

The same trick can be used for centering other native dialogs exposed by SWT.

No comments: