Tuesday, 3 January 2017

SWT: Graphics

SWT provides Graphics context ‘GC’ class, to work with graphics. By using GC, you can perform following tasks.
a.   Set the foreground and background colors
b.   Draw shapes like rectangle, circle etc.,
c.    Display images
d.   Change the font etc.,

Following step-by-step procedure explains simple drawing application using Canvas and GC.

Step 1: Define Canvas object. You can draw graphics on the surface of Canvas object.

Canvas canvas = new Canvas(shell, SWT.BORDER);
canvas.setSize(canvasWidth, canvasHeight);
canvas.setLocation(20, 20);

Step 2: Open the shell. Note that shee should be opened after defining Canvas object.
shell.open();

Step 3: Get the GC instance to draw graphics on canvas surface.

GC gc = new GC(canvas);

By using above gc instance, we can apply graphics on the canvas surface, If you try to draw any graphic outside the canvas surface area, it is not visible.

Step 4: Now you can use different methods provided by GC class, to draw graphics.

gc.setBackground(red);
gc.drawRectangle(150, 130, 200, 75);
gc.fillRectangle(30, 30, 200, 75);

gc.setForeground(blue);
gc.drawLine(0, 0, 400, 300);

gc.drawString("Hello World Graphics Application", 75, 0);

gc.drawOval(0, 0, 400, 300);

Step 5: Dispose the resources taken by SWT application.
gc.dispose();

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test
{

 private static int shellWidth = 1000;
 private static int shellHeight = 700;

 private static int canvasHeight = 300;
 private static int canvasWidth = 400;

 private static void addGraphicsToShell(Display display, Shell shell)
 {
  Canvas canvas = new Canvas(shell, SWT.BORDER);
  canvas.setSize(canvasWidth, canvasHeight);
  canvas.setLocation(20, 20);

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

  Color blue = display.getSystemColor(SWT.COLOR_BLUE);
  Color red = display.getSystemColor(SWT.COLOR_RED);

  GC gc = new GC(canvas);

  gc.setBackground(red);
  gc.drawRectangle(150, 130, 200, 75);
  gc.fillRectangle(30, 30, 200, 75);

  gc.setForeground(blue);
  gc.drawLine(0, 0, 400, 300);

  gc.drawString("Hello World Graphics Application", 75, 0);

  gc.drawOval(0, 0, 400, 300);

  gc.dispose();
 }

 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);
  shell.setSize(shellWidth, shellHeight);
  shell.setText("SWT Tutorial");

  addGraphicsToShell(display, shell);

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

 }
}



There is one major problem with above program, just minimize the window, maximize it back, now you can observe whatever the graphics you painted on Canvas are cleared. It is because, after maximizing, the graphics are not repainted on the canvas.

To resolve this issue, we should know when the graphics are repainted. We can do this by using PaintListener interface. The paintListener will detect whenever canvas is repainted, and execute the paintControl method.

First I moved all the graphics to drawGraphics method.

private static void drawGraphcis(Display display, GC gc)
{
         Color blue = display.getSystemColor(SWT.COLOR_BLUE);
         Color red = display.getSystemColor(SWT.COLOR_RED);

         gc.setBackground(red);
         gc.drawRectangle(150, 130, 200, 75);
         gc.fillRectangle(30, 30, 200, 75);

         gc.setForeground(blue);
         gc.drawLine(0, 0, 400, 300);

         gc.drawString("Hello World Graphics Application", 75, 0);

         gc.drawOval(0, 0, 400, 300);

}

Next, I added paintListener to canvas object like below.

canvas.addPaintListener(new PaintListener()
{
         @Override
         public void paintControl(PaintEvent e)
         {
                 GC gc = e.gc;
                 drawGraphcis(display, gc);
         }

});

Whenever repaint needed, I called drawGraphics method.


Following is the updated application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Test
{

 private static int shellWidth = 1000;
 private static int shellHeight = 700;

 private static int canvasHeight = 300;
 private static int canvasWidth = 400;

 private static void drawGraphcis(Display display, GC gc)
 {
  Color blue = display.getSystemColor(SWT.COLOR_BLUE);
  Color red = display.getSystemColor(SWT.COLOR_RED);

  gc.setBackground(red);
  gc.drawRectangle(150, 130, 200, 75);
  gc.fillRectangle(30, 30, 200, 75);

  gc.setForeground(blue);
  gc.drawLine(0, 0, 400, 300);

  gc.drawString("Hello World Graphics Application", 75, 0);

  gc.drawOval(0, 0, 400, 300);

 }

 private static void addGraphicsToShell(Display display, Shell shell)
 {
  Canvas canvas = new Canvas(shell, SWT.BORDER);
  canvas.setSize(canvasWidth, canvasHeight);
  canvas.setLocation(20, 20);

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

  GC gc = new GC(canvas);

  drawGraphcis(display, gc);

  canvas.addPaintListener(new PaintListener()
  {
   @Override
   public void paintControl(PaintEvent e)
   {
    GC gc = e.gc;
    drawGraphcis(display, gc);
   }

  });

  gc.dispose();

 }

 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);
  shell.setSize(shellWidth, shellHeight);
  shell.setText("SWT Tutorial");

  addGraphicsToShell(display, shell);

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

 }
}


Note

You can get GC object on any SWT widget, and apply graphics.



Previous                                                 Next                                                 Home

SWT: CoolBars

CoolBars are just like tool bars, and these can be dynamically repositioned by the user.

You can create cool bar using CoolBar instance.

CoolBar coolBar = new CoolBar(shell, SWT.BORDER);

You can add items to cool bar using CoolItem.

CoolItem coolItem1 = new CoolItem(coolBar, SWT.NONE);

Button button1 = new Button(coolBar, SWT.FLAT | SWT.BORDER);
button1.setText("Button");
button1.pack();

Point size = button1.getSize();
coolItem1.setControl(button1);
coolItem1.setSize(coolItem1.computeSize(size.x, size.y));

CoolBar provides 'setLocked' method, to lock the coolbar. When a coolbar is locked, its items cannot be repositioned. Whenever you click the button1, logic toggles the locking behavior of cool bar.

button1.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
                 coolBar.setLocked(!coolBar.getLocked());
         }
});


Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.CoolBar;
import org.eclipse.swt.widgets.CoolItem;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

public class Test {

 private static int shellWidth = 1000;
 private static int shellHeight = 700;

 private static void addWidgetsToShell(Display display, Shell shell) {
  CoolBar coolBar = new CoolBar(shell, SWT.BORDER);
  CoolItem coolItem1 = new CoolItem(coolBar, SWT.NONE);
  CoolItem coolItem2 = new CoolItem(coolBar, SWT.NONE);
  CoolItem coolItem3 = new CoolItem(coolBar, SWT.NONE);

  Button button1 = new Button(coolBar, SWT.FLAT | SWT.BORDER);
  button1.setText("Button");
  button1.pack();

  Button button2 = new Button(coolBar, SWT.PUSH);
  button2.setText("Another button");
  button2.pack();

  ToolBar tools = new ToolBar(coolBar, SWT.NONE);
  ToolItem b1 = new ToolItem(tools, SWT.FLAT);
  b1.setText("Tool");
  ToolItem b2 = new ToolItem(tools, SWT.FLAT);
  b2.setText("Bar");
  tools.pack();

  Point size = button1.getSize();
  coolItem1.setControl(button1);
  coolItem1.setSize(coolItem1.computeSize(size.x, size.y));

  size = button2.getSize();
  coolItem2.setControl(button2);
  coolItem2.setSize(coolItem2.computeSize(size.x, size.y));

  size = tools.getSize();
  coolItem3.setControl(tools);
  coolItem3.setSize(coolItem3.computeSize(size.x, size.y));
  coolItem3.setMinimumSize(size);

  coolBar.setWrapIndices(new int[] { 2 });
  coolBar.setSize(300, 120);

  button1.addSelectionListener(new SelectionAdapter() {
   public void widgetSelected(SelectionEvent e) {
    coolBar.setLocked(!coolBar.getLocked());
   }
  });
 }

 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);
  shell.setSize(shellWidth, shellHeight);
  shell.setText("SWT Tutorial");

  addWidgetsToShell(display, shell);

  /* 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

SWT: ToolBars

You can define a tool bar using ToolBar widget.

ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL);
toolBar.setSize(shellWidth, 150);
toolBar.setLocation(toolBarLocationX, toolBarLocationY);

How to add an item to toolbar?
By using 'ToolItem' class, you can add an item to toolbar.

ToolItem newFile = new ToolItem(toolBar, SWT.PUSH);
newFile.setText("New");

You can apply any one of the following styles to ToolItem.

Style
Description
CHECK
Style constant for check box behavior
PUSH
Style constant for push button behavior
RADIO
Style constant for radio button behavior
SEPARATOR
Style constant for line separator behavior
DROP_DOWN
Style constant for drop down menu/list behavior

Following statements create check box.
ToolItem checkItem = new ToolItem(toolBar, SWT.CHECK);
checkItem.setText("Check");

Following statements create push button.
ToolItem newFile = new ToolItem(toolBar, SWT.PUSH);
newFile.setText("New");
                
Following statement creates a separator.
ToolItem sep = new ToolItem(toolBar, SWT.SEPARATOR);

Following statements create radio button.
ToolItem radioItem1 = new ToolItem(toolBar, SWT.RADIO);
radioItem1.setText("Radio 1");

Following statements create drop down.
ToolItem dropdown = new ToolItem(toolBar, SWT.DROP_DOWN);
dropdown.setText("Drop-down");

Following logic adds a menu to drop down box.

Menu menu = new Menu(shell, SWT.POP_UP);
MenuItem choice = new MenuItem(menu, SWT.PUSH);
choice.setText("Choices");
MenuItem options = new MenuItem(menu, SWT.PUSH);
options.setText("options");

dropdown.addListener(SWT.Selection, new Listener() {
         @Override
         public void handleEvent(Event event) {
                 if (event.detail == SWT.ARROW) {
                          Rectangle rect = dropdown.getBounds();
                          Point pt = new Point(rect.x, rect.y + rect.height);
                          pt = toolBar.toDisplay(pt);
                          menu.setLocation(pt.x, pt.y);
                          menu.setVisible(true);
                 }
         }
});


Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

public class Test {

 private static int shellWidth = 1000;
 private static int shellHeight = 700;

 private static int toolBarLocationX = 10;
 private static int toolBarLocationY = 10;

 private static void addWidgetsToShell(Display display, Shell shell) {
  ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL);
  toolBar.setSize(shellWidth, 150);
  toolBar.setLocation(toolBarLocationX, toolBarLocationY);

  ToolItem newFile = new ToolItem(toolBar, SWT.PUSH);
  newFile.setText("New");

  ToolItem openFile = new ToolItem(toolBar, SWT.PUSH);
  openFile.setText("Open");

  ToolItem save = new ToolItem(toolBar, SWT.PUSH);
  save.setText("Save");

  ToolItem sep = new ToolItem(toolBar, SWT.SEPARATOR);

  ToolItem checkItem = new ToolItem(toolBar, SWT.CHECK);
  checkItem.setText("Check");

  ToolItem sep2 = new ToolItem(toolBar, SWT.SEPARATOR);

  ToolItem radioItem1 = new ToolItem(toolBar, SWT.RADIO);
  radioItem1.setText("Radio 1");
  ToolItem radioItem2 = new ToolItem(toolBar, SWT.RADIO);
  radioItem2.setText("Radio 2");

  ToolItem sep3 = new ToolItem(toolBar, SWT.SEPARATOR);

  ToolItem radioItem3 = new ToolItem(toolBar, SWT.RADIO);
  radioItem3.setText("Radio 3");
  ToolItem radioItem4 = new ToolItem(toolBar, SWT.RADIO);
  radioItem4.setText("Radio 4");

  ToolItem dropdown = new ToolItem(toolBar, SWT.DROP_DOWN);
  dropdown.setText("Drop-down");

  Menu menu = new Menu(shell, SWT.POP_UP);
  MenuItem choice = new MenuItem(menu, SWT.PUSH);
  choice.setText("Choices");
  MenuItem options = new MenuItem(menu, SWT.PUSH);
  options.setText("options");

  dropdown.addListener(SWT.Selection, new Listener() {
   @Override
   public void handleEvent(Event event) {
    if (event.detail == SWT.ARROW) {
     Rectangle rect = dropdown.getBounds();
     Point pt = new Point(rect.x, rect.y + rect.height);
     pt = toolBar.toDisplay(pt);
     menu.setLocation(pt.x, pt.y);
     menu.setVisible(true);
    }
   }
  });

 }

 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);
  shell.setSize(shellWidth, shellHeight);
  shell.setText("SWT Tutorial");

  addWidgetsToShell(display, shell);

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

 }
}


How radio buttons grouped together?
ToolItem radioItem1 = new ToolItem(toolBar, SWT.RADIO);
radioItem1.setText("Radio 1");
ToolItem radioItem2 = new ToolItem(toolBar, SWT.RADIO);
radioItem2.setText("Radio 2");


In case of toolbars, radio button behavior is done automatically. This automatic behavior happens only if radio buttons that are adjacent to one another. If any other ToolItem occurred between the radio buttons, then radio buttons don’t behave like group.


Previous                                                 Next                                                 Home

Monday, 2 January 2017

SWT: Trees

Trees are used to display information in hierarchical format. You can get notifications when an item in the hierarchy is selected.

Following styles are used while creating Tree instance.
Style
Description
SINGLE
Style constant for single selection behavior. You can able to select only one item in the tree at a time.
MULTI
Style constant for multi-selection behavior.  You can able to select multiple items in the tree.
CHECK
Style constant for check box behavior.
FULL_SELECTION
Style constant for full row selection behavior.
VIRTUAL
Style constant to allow virtual data. By using this, you can populate tree items on demand basis.
NO_SCROLL
Style constant for no scrollbar behavior.

How to define a tree?
By using Tree constructor, you can define a tree.

Tree tree = new Tree(shell, SWT.MULTI | SWT.BORDER);
tree.setSize(150, 150);
tree.setLocation(5, 5);

How to add an item to hierarchy in the tree?
By using TreeItem class, you can add an item to tree hierarchy. TreeItem class provides following constructors to define a TreeItem instance.

Following two constructors are used to attach TreeItem to a tree.
public TreeItem (Tree parent, int style)
public TreeItem (Tree parent, int style, int index)

Following two constructors are used to attach a TreeItem to another TreeItem.
public TreeItem (TreeItem parentItem, int style)
public TreeItem (TreeItem parentItem, int style, int index)


You can also add an image to TreeItem. Following statements adds an image to TreeItem.
Image icon = new Image(display, "help.bmp");
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setImage(icon);

By using SelectionListener, you can able to get all the TreeItems selected in the tree.

tree.addSelectionListener(new SelectionAdapter() {
         public void widgetSelected(SelectionEvent e) {
                 TreeItem[] selectedItems = tree.getSelection();
                 System.out.print("Selected Items: ");
                 for (int i = 0; i < selectedItems.length; i++) {
                          System.out.print(selectedItems[i].getText() + ", ");
                 }
                 System.out.println();
         }
});

Get the TreeItem expansion and collapsed status
By using TreeListener interface, you can get notification, whenever the tree item is collapsed (or) expanded.
TreeListener interface provides following methods.

Method
Description
public void treeCollapsed(TreeEvent e)
Notify when a tree branch is collapsed.
public void treeExpanded(TreeEvent e)
Notify when a tree branch is expanded.

Following is the complete working application.
package swt_app;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TreeEvent;
import org.eclipse.swt.events.TreeListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class Test {

 private static int shellWidth = 1000;
 private static int shellHeight = 700;

 private static void addWidgetsToShell(Display display, Shell shell) {
  Tree tree = new Tree(shell, SWT.MULTI | SWT.BORDER);

  tree.setSize(150, 150);
  tree.setLocation(5, 5);

  TreeItem child1 = new TreeItem(tree, SWT.NONE);
  child1.setText("child1");

  TreeItem child3 = new TreeItem(tree, SWT.NONE);
  child3.setText("child3");

  TreeItem child2 = new TreeItem(tree, SWT.NONE, 1);
  child2.setText("child2");

  TreeItem child2_1 = new TreeItem(child2, SWT.NONE);
  child2_1.setText("child2_1");

  TreeItem child2_2 = new TreeItem(child2, SWT.NONE);
  child2_2.setText("child2_2");

  tree.addSelectionListener(new SelectionAdapter() {
   public void widgetSelected(SelectionEvent e) {
    TreeItem[] selectedItems = tree.getSelection();
    System.out.print("Selected Items: ");
    for (int i = 0; i < selectedItems.length; i++) {
     System.out.print(selectedItems[i].getText() + ", ");
    }
    System.out.println();
   }
  });

  tree.addTreeListener(new TreeListener() {
   public void treeCollapsed(TreeEvent e) {
    System.out.println("Tree collapsed.");
   }

   public void treeExpanded(TreeEvent e) {
    System.out.println("Tree expanded.");
   }
  });
 }

 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);
  shell.setSize(shellWidth, shellHeight);
  shell.setText("SWT Tutorial");

  addWidgetsToShell(display, shell);

  /* 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