How to centre a SWT shell in the middle of the screen

  • 01 June 2017
  • ADM

 

How to centre a SWT shell in the middle of the screen - images/logos/eclipse.jpg

 

This article will present how to centre an SWT Shell window in the middle of the primary monitor. For this article will be used the SWT Hello World Application.

There are four simple steps to achieve this:

  • create the shell;
  • get the primary monitor size;
  • calculate the centre position;
  • set the shell location.

For a better understanding please follow the code comments.

Example

package com.admfactory.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;

public class CentreShellSWT {

    public static void main(String[] args) {
	Display display = new Display();

	/** create the new window */
	Shell shell = new Shell(display);

	/** adding the window title */
	shell.setText("Hello World");

	/** setting up the window size */
	shell.setSize(600, 400);

	/** creating a new label widget on the new created shell */
	Label label = new Label(shell, SWT.NONE);

	/** setting up the label text */
	label.setText("Hello World");

	/** to resize the label to the required size, based on the text */
	label.pack();

	/** take the primary monitor */
	Monitor primary = display.getPrimaryMonitor();
	
	/** get the size of the screen */
	Rectangle bounds = primary.getBounds();
	
	/** get the size of the window */
	Rectangle rect = shell.getBounds();

	/** calculate the centre */
	int x = bounds.x + (bounds.width - rect.width) / 2;
	int y = bounds.y + (bounds.height - rect.height) / 2;

	/** set the new location */
	shell.setLocation(x, y);

	/** this will open the window and will make it visible */
	shell.open();

	/**
	 * this loop is to maintain the window open until a dispose event is
	 * received - usually a close event
	 */
	while (!shell.isDisposed()) {
	    if (!display.readAndDispatch())
		display.sleep();
	}
	display.dispose();
    }
}

 

References