Saturday 19 November 2016

SWT: Hello World Application

To develop a SWT application, you need to import following packages.

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

There are two basic classes you must require while building an application using SWT.

a.   Display
b.   Shell

Display class
Instance of Display class hold all the GUI objects. The components added to the Display instance are visible on the screen. In real world, one Display object is created for one application.

Shell class
Shell represents a window within the application. Shell is attached to Display object (or) Shell can be attached to another Shell. An application can have more than one shells.

Following step-by-step procedure explains demo application.

Step 1: Instantiate Display object, it represents SWT session.
Display display = new Display();

Step 2: Define Shell, it represent a window. You can add more than one shell to Display
Shell shell = new Shell(display);

Step 3:  Define widgets to add to the shell.
Label label = new Label(shell, SWT.CENTER);
label.setText("Hello_world");
label.setBounds(shell.getClientArea());
Step 4: Open shell window.
shell.open();

Step 5: Run the event dispatching loop until an exit condition occurs, which is typically when the main shell window is closed by the user.

while (!shell.isDisposed()) {
if (!display.readAndDispatch())
                 display.sleep();
         }

/* Dispose the display */
display.dispose();


Following is the complete working application.
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

public class Test {
 public static void main(String[] args) {

  /* Instantiate Display object, it represents SWT session */
  Display display = new Display();

  /*
   * Define Shell, it represent a window, You can add more than one shell
   * to Display
   */
  Shell shell = new Shell(display);

  /* Define widgets to add to the shell */
  Label label = new Label(shell, SWT.CENTER);
  label.setText("Hello_world");
  label.setBounds(shell.getClientArea());

  /* Open shell window */
  shell.open();

  /*
   * Run the event dispatching loop until an exit condition occurs, which
   * is typically when the main shell window is closed by the user.
   */

  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }

  /* Dispose the display */
  display.dispose();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment