Jun 012017

ADM

SWT Hello World Application

  • 01 June 2017
  • ADM

 

 

 

SWT Hello World Application - images/logos/eclipse.jpg

 

Here is a simple Hello World Application using SWT.

SWT has two classes that are key components, Display and Shell.

  • Display class: Instances of the Display class are responsible for managing the connection between SWT and the underlying operating system. Applications that are built with SWT will require one single instance of Display class.
  • Shell class: Instances of the Shell class represents the "windows" of a desktop application with all possible properties, like minimised, maximised, modal, etc.

Example

package com.admfactory.swt;

import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;

public class HelloWorldSWT {

    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();

	/** 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();
    }
}

As you can see the most important part of the application is the while loop that is used to keep the application opened.

Output

SWT Hello World Application - /images/SWTHelloWorld01.png

 

 

 

References