SWT is stand for Standard Widget Toolkit. I do not want to explain what the benefits of it , please search Google for it. Please access SWT Official Website if you want to know more about it.

Here is the simple SWT Hello World program

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
 
public class SWTHelloWorld {
 
public static void main (String [] args) {
	Display display = new Display ();
	Shell shell = new Shell(display);
 
	Text helloWorldTest = new Text(shell, SWT.NONE);
	helloWorldTest.setText("Hello World SWT");
	helloWorldTest.pack();
 
	shell.pack();
	shell.open ();
	while (!shell.isDisposed ()) {
		if (!display.readAndDispatch ()) display.sleep ();
	}
	display.dispose ();
}
}

P.S In order to run the above SWT example, we have to import SWT library into Eclipse workspace.

Please access my previous article How to import SWT library into Eclipse Workspace?

Explanation

The above SWT example will create a TextBox and display it as “Hello World”.

Most SWT application consists of three stages structure.

1.) Initialize Stage – Create a Display and Shell Instance

Display display = new Display ();
Shell shell = new Shell(display);

2.) Design (business login) Stage – Create a text widget to display “Hello World SWT”

Text helloWorldTest = new Text(shell, SWT.NONE);
helloWorldTest.setText("Hello World SWT");
helloWorldTest.pack();

3.) Display Stage – All coding has done, when shell.open method is invoked, all application’s GUI are rendered in display. Display class use display.readAndDispatch () to keep track of relevant user events happened in applications like closing of windows.

shell.pack(); //optional
shell.open ();
while (!shell.isDisposed ()) {
	if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();

Congratulation ! we created a simple SWT Hello World program.

What is shell.pack()?

It’s tell SWT application to auto resizes the widget (shell windows) to its preferred size, it’s always use only as much space as they need. It’s is helpful feature due to differences in resolution and platform rendering.

If we comment out shell.pack() in above Hello World program. Output will look like following

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts