Java/SWT JFace Eclipse/2D

Материал из Java эксперт
Перейти к: навигация, поиск

Alpha Fade In

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-21 22:36:43 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class AlphaFadeIn {

 Display display = new Display();
 Shell shell = new Shell(display);
 public AlphaFadeIn() {
   shell.setLayout(new FillLayout());
   final Canvas canvas = new Canvas(shell, SWT.NULL);
   
   ImageData imageData = new ImageData("jexp.gif");
   
   ImageData imageData2 = imageData.scaledTo(100, 100);
   Image image2 = new Image(display, imageData2);
   
   byte[] alphaValues = new byte[imageData.height * imageData.width];
   for(int j=0; j<imageData.height; j++) {
     for(int i=0; i<imageData.width; i++) {
       alphaValues[j*imageData.width + i] = (byte) (255 - 255 * i / imageData.width);
     }
   }
   
   
   
   imageData.alphaData = alphaValues;
   
   final Image image = new Image(display, imageData);
   
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       e.gc.drawImage(image, 10, 10);
     }
   });
   shell.setSize(200, 100);
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new AlphaFadeIn();
 }

}


 </source>
   
  
 
  



Animations Example

   <source lang="java">

/*******************************************************************************

* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-22 11:06:42 by JACK $Id$
*  
******************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.ImageLoader; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Animations {

 Display display = new Display();
 Shell shell = new Shell(display);
 public Animations() {
   shell.setLayout(new FillLayout());
   ImageLoader imageLoader = new ImageLoader();
   final ImageData[] imageDatas = imageLoader.load("jexp.gif");
   final Image image = new Image(display, imageDatas[0].width, imageDatas[0].height);
   final Canvas canvas = new Canvas(shell, SWT.NULL);
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       e.gc.drawImage(image, 0, 0);
     }
   });
   final GC gc = new GC(image);
   final Thread thread = new Thread() {
     int frameIndex = 0;
     public void run() {
       while (!isInterrupted()) {
         frameIndex %= imageDatas.length;
         final ImageData frameData = imageDatas[frameIndex];
         display.asyncExec(new Runnable() {
           public void run() {
             Image frame =
               new Image(display, frameData);
             gc.drawImage(frame, frameData.x, frameData.y);
             frame.dispose();
             canvas.redraw();
           }
         });
         
         try {
           // delay
           Thread.sleep(imageDatas[frameIndex].delayTime * 10);
         } catch (InterruptedException e) {
           return;
         }
         
         frameIndex += 1;
       }
       
     }
   };
   
   shell.addShellListener(new ShellAdapter() {
     public void shellClosed(ShellEvent e) {
       thread.interrupt();
     }
   });
   shell.setSize(400, 200);
   shell.open();
   
   thread.start();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new Animations();
 }

}


 </source>
   
  
 
  



Class Analyzer

   <source lang="java">

/*******************************************************************************

* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-7-4 19:32:27 by JACK $Id$
*  
******************************************************************************/

import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.eclipse.draw2d.AbstractBorder; import org.eclipse.draw2d.ChopboxAnchor; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.MouseListener; import org.eclipse.draw2d.PolygonDecoration; import org.eclipse.draw2d.PolylineConnection; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.draw2d.XYLayout; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.ruposite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; class ClassFigure extends Figure {

 ImageRegistry registry = new ImageRegistry();
 // image keys.
 String KEY_CLASS = "class";
 String KEY_METHOD_PUBLIC = "method_public";
 String KEY_METHOD_DEFAULT = "method_default";
 String KEY_METHOD_PROTECTED = "method_protected";
 String KEY_METHOD_PRIVATE = "method_private";
 String KEY_FIELD_PUBLIC = "field_public";
 String KEY_FIELD_DEFAULT = "field_default";
 String KEY_FIELD_PROTECTED = "field_protected";
 String KEY_FIELD_PRIVATE = "field_private";
 String[] keys =
   {
     KEY_CLASS,
     KEY_METHOD_PUBLIC,
     KEY_METHOD_DEFAULT,
     KEY_METHOD_PROTECTED,
     KEY_METHOD_PRIVATE,
     KEY_FIELD_PUBLIC,
     KEY_FIELD_DEFAULT,
     KEY_FIELD_PROTECTED,
     KEY_FIELD_PRIVATE };
 public Box fieldBox = new Box();
 public Box methodBox = new Box();
 public ClassFigure(Class cls) {
   setLayoutManager(new ToolbarLayout());
   setBorder(new LineBorder(ColorConstants.black));
   setBackgroundColor(ColorConstants.yellow);
   setOpaque(true);
   for (int i = 0; i < keys.length; i++)
     registry.put(
       keys[i],
       ImageDescriptor.createFromFile(
         null,
         "icons/java/" + keys[i] + ".gif"));
   Label title = new Label(cls.getName(), registry.get(KEY_CLASS));
   add(title);
   add(fieldBox);
   add(methodBox);
   // fields.
   Field[] fields = cls.getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
     Field field = fields[i];
     Image image = null;
     if (Modifier.isPublic(field.getModifiers())) {
       image = registry.get(KEY_FIELD_PUBLIC);
     } else if (Modifier.isProtected(field.getModifiers())) {
       image = registry.get(KEY_FIELD_PROTECTED);
     } else if (Modifier.isPrivate(field.getModifiers())) {
       image = registry.get(KEY_FIELD_PRIVATE);
     } else {
       image = registry.get(KEY_FIELD_DEFAULT);
     }
     fieldBox.add(new Label(fields[i].getName(), image));
   }
   // fields.
   Method[] methods = cls.getDeclaredMethods();
   for (int i = 0; i < methods.length; i++) {
     Method method = methods[i];
     Image image = null;
     if (Modifier.isPublic(method.getModifiers())) {
       image = registry.get(KEY_METHOD_PUBLIC);
     } else if (Modifier.isProtected(method.getModifiers())) {
       image = registry.get(KEY_METHOD_PROTECTED);
     } else if (Modifier.isPrivate(method.getModifiers())) {
       image = registry.get(KEY_METHOD_PRIVATE);
     } else {
       image = registry.get(KEY_METHOD_DEFAULT);
     }
     methodBox.add(new Label(methods[i].getName(), image));
   }
 }

} class Box extends Figure {

 public Box() {
   setBorder(new BoxBorder());
   ToolbarLayout toolbarLayout = new ToolbarLayout();
   toolbarLayout.setStretchMinorAxis(false);
   setLayoutManager(toolbarLayout);
 }
 private class BoxBorder extends AbstractBorder {
   /*
    * (non-Javadoc)
    * 
    * @see org.eclipse.draw2d.Border#getInsets(org.eclipse.draw2d.IFigure)
    */
   public Insets getInsets(IFigure figure) {
     return new Insets(1, 0, 0, 0);
   }
   /*
    * (non-Javadoc)
    * 
    * @see org.eclipse.draw2d.Border#paint(org.eclipse.draw2d.IFigure,
    *      org.eclipse.draw2d.Graphics,
    *      org.eclipse.draw2d.geometry.Insets)
    */
   public void paint(IFigure figure, Graphics graphics, Insets insets) {
     Rectangle rect = getPaintRectangle(figure, insets);
     graphics.drawLine(rect.getTopLeft(), rect.getTopRight());
   }
 }

} /**

*  
*/

public class ClassAnalyzer extends ApplicationWindow {

 Text className;
 Canvas canvas;
 Figure contents;
 XYLayout xyLayout;
 /**
  * @param parentShell
  */
 public ClassAnalyzer(Shell parentShell) {
   super(parentShell);
   addToolBar(SWT.NULL);
 }
 private void showClass(Class cls) {
   if (cls == null)
     return;
   // removes all existing items.
   contents.removeAll();
   // draws super class.
   Label sup = null;
   if (cls.getSuperclass() != null) {
     final Class superClass = cls.getSuperclass();
     sup = new Label(superClass.getName());
     sup.setBorder(new LineBorder());
     sup.setBackgroundColor(ColorConstants.lightGreen);
     sup.setOpaque(true);
     sup.addMouseListener(new MouseListener() {
       public void mousePressed(org.eclipse.draw2d.MouseEvent me) {
       }
       public void mouseReleased(org.eclipse.draw2d.MouseEvent me) {
       }
       public void mouseDoubleClicked(
         org.eclipse.draw2d.MouseEvent me) {
         showClass(superClass);
       }
     });
   }
   if (sup != null) {
     contents.add(sup);
     xyLayout.setConstraint(sup, new Rectangle(20, 20, -1, -1));
   }
   ClassFigure classFigure = new ClassFigure(cls);
   contents.add(classFigure);
   if (sup == null)
     xyLayout.setConstraint(classFigure, new Rectangle(20, 20, -1, -1));
   else
     xyLayout.setConstraint(
       classFigure,
       new Rectangle(20, sup.getBounds().height + 40, -1, -1));
   // adds connection.
   if (sup != null) {
     PolylineConnection connection = new PolylineConnection();
     ChopboxAnchor source = new ChopboxAnchor(classFigure);
     ChopboxAnchor target = new ChopboxAnchor(sup);
     connection.setSourceAnchor(source);
     connection.setTargetAnchor(target);
     PolygonDecoration decoration = new PolygonDecoration();
     PointList list = new PointList();
     list.addPoint(-2, -2);
     list.addPoint(0, 0);
     list.addPoint(-2, 2);
     decoration.setTemplate(list);
     connection.setTargetDecoration(decoration);
     contents.add(connection);
   }
   // resizes the shell.
   getShell().setSize(
     contents.getPreferredSize().width + 30,
     contents.getPreferredSize().height + 80);
 }
 /*
  * (non-Javadoc)
  * 
  * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
  */
 protected Control createContents(Composite parent) {
   Composite composite = new Composite(parent, SWT.NULL);
   composite.setLayout(new FillLayout());
   canvas = new Canvas(composite, SWT.NULL);
   canvas.setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WHITE));
   LightweightSystem lws = new LightweightSystem(canvas);
   contents = new Figure();
   xyLayout = new XYLayout();
   contents.setLayoutManager(xyLayout);
   lws.setContents(contents);
   showClass(this.getClass());
   // Creates tool bar items.
   getToolBarManager().add(new Action("Set class ...") {
     public void run() {
       InputDialog dialog =
         new InputDialog(
           getShell(),
           "",
           "Please enter the class name",
           "",
           null);
       if (dialog.open() != Dialog.OK)
         return;
       contents.removeAll();
       Class cls = null;
       try {
         cls = Class.forName(dialog.getValue());
       } catch (ClassNotFoundException e) {
         e.printStackTrace();
       }
       if (cls != null) {
         showClass(cls);
       }
     }
   });
   getToolBarManager().update(true);
   return composite;
 }
 public static void main(String[] args) {
   ClassAnalyzer window = new ClassAnalyzer(null);
   window.setBlockOnOpen(true);
   window.open();
   Display.getCurrent().dispose();
 }

}


 </source>
   
  
 
  



Demonstrates animation

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates animation.
*/

public class Animator {

 // The width (and height) of the image
 private static final int IMAGE_WIDTH = 100;
 // The timer interval in milliseconds
 private static final int TIMER_INTERVAL = 10;
 // The location of the "ball"
 private int x = 0;
 private int y = 0;
 // The direction the "ball" is moving
 private int directionX = 1;
 private int directionY = 1;
 // We draw everything on this canvas
 private Canvas canvas;
 /**
  * Runs the application
  */
 public void run() {
   final Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Animator");
   createContents(shell);
   shell.open();
   // Set up the timer for the animation
   Runnable runnable = new Runnable() {
     public void run() {
       animate();
       display.timerExec(TIMER_INTERVAL, this);
     }
   };
   // Launch the timer
   display.timerExec(TIMER_INTERVAL, runnable);
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   // Kill the timer
   display.timerExec(-1, runnable);
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(final Shell shell) {
   shell.setLayout(new FillLayout());
   // Create the canvas for drawing
   canvas = new Canvas(shell, SWT.NO_BACKGROUND);
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       // Draw the background
       event.gc.fillRectangle(canvas.getBounds());
       // Set the color of the ball
       event.gc.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_RED));
       // Draw the ball
       event.gc.fillOval(x, y, IMAGE_WIDTH, IMAGE_WIDTH);
     }
   });
 }
 /**
  * Animates the next frame
  */
 public void animate() {
   // Determine the ball"s location
   x += directionX;
   y += directionY;
   // Determine out of bounds
   Rectangle rect = canvas.getClientArea();
   if (x < 0) {
     x = 0;
     directionX = 1;
   } else if (x > rect.width - IMAGE_WIDTH) {
     x = rect.width - IMAGE_WIDTH;
     directionX = -1;
   }
   if (y < 0) {
     y = 0;
     directionY = 1;
   } else if (y > rect.height - IMAGE_WIDTH) {
     y = rect.height - IMAGE_WIDTH;
     directionY = -1;
   }
   // Force a redraw
   canvas.redraw();
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new Animator().run();
 }

}


 </source>
   
  
 
  



Demonstrates animation. It uses double buffering.

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates animation. It uses double buffering
*/

public class AnimatorDoubleBuffer {

 // The width (and height) of the image
 
 
 private static final int IMAGE_WIDTH = 100;
 // The timer interval in milliseconds
 private static final int TIMER_INTERVAL = 10;
 // The location of the "ball"
 private int x = 0;
 private int y = 0;
 // The direction the "ball" is moving
 private int directionX = 1;
 private int directionY = 1;
 // We draw everything on this canvas
 private Canvas canvas;
 /**
  * Runs the application
  */
 public void run() {
   final Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Animator Double Buffer");
   createContents(shell);
   shell.open();
   // Set up the timer for the animation
   Runnable runnable = new Runnable() {
     public void run() {
       animate();
       display.timerExec(TIMER_INTERVAL, this);
     }
   };
   // Launch the timer
   display.timerExec(TIMER_INTERVAL, runnable);
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   // Kill the timer
   display.timerExec(-1, runnable);
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(final Shell shell) {
   shell.setLayout(new FillLayout());
   // Create the canvas for drawing
   canvas = new Canvas(shell, SWT.NO_BACKGROUND);
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       // Create the image to fill the canvas
       Image image = new Image(shell.getDisplay(), canvas.getBounds());
       // Set up the offscreen gc
       GC gcImage = new GC(image);
       // Draw the background
       gcImage.setBackground(event.gc.getBackground());
       gcImage.fillRectangle(image.getBounds());
       // Set the color of the ball
       gcImage.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_RED));
       // Draw the ball
       gcImage.fillOval(x, y, IMAGE_WIDTH, IMAGE_WIDTH);
       // Draw the offscreen buffer to the screen
       event.gc.drawImage(image, 0, 0);
       // Clean up
       image.dispose();
       gcImage.dispose();
     }
   });
 }
 /**
  * Animates the next frame
  */
 public void animate() {
   // Determine the ball"s location
   x += directionX;
   y += directionY;
   // Determine out of bounds
   Rectangle rect = canvas.getClientArea();
   if (x < 0) {
     x = 0;
     directionX = 1;
   } else if (x > rect.width - IMAGE_WIDTH) {
     x = rect.width - IMAGE_WIDTH;
     directionX = -1;
   }
   if (y < 0) {
     y = 0;
     directionY = 1;
   } else if (y > rect.height - IMAGE_WIDTH) {
     y = rect.height - IMAGE_WIDTH;
     directionY = -1;
   }
   // Force a redraw
   canvas.redraw();
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new AnimatorDoubleBuffer().run();
 }

}


 </source>
   
  
 
  



Demonstrates drawing an Arc

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates drawing an Arc
*/

public class ArcExample {

 private Text txtWidth = null;
 private Text txtHeight = null;
 private Text txtBeginAngle = null;
 private Text txtAngle = null;
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Arc Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout(SWT.VERTICAL));
   // Create the composite that holds the input fields
   Composite widgetComposite = new Composite(shell, SWT.NONE);
   widgetComposite.setLayout(new GridLayout(2, false));
   // Create the input fields
   new Label(widgetComposite, SWT.NONE).setText("Width:");
   txtWidth = new Text(widgetComposite, SWT.BORDER);
   new Label(widgetComposite, SWT.NONE).setText("Height");
   txtHeight = new Text(widgetComposite, SWT.BORDER);
   new Label(widgetComposite, SWT.NONE).setText("Begin Angle:");
   txtBeginAngle = new Text(widgetComposite, SWT.BORDER);
   new Label(widgetComposite, SWT.NONE).setText("Angle:");
   txtAngle = new Text(widgetComposite, SWT.BORDER);
   // Create the button that launches the redraw
   Button button = new Button(widgetComposite, SWT.PUSH);
   button.setText("Redraw");
   shell.setDefaultButton(button);
   // Create the canvas to draw the arc on
   final Canvas drawingCanvas = new Canvas(shell, SWT.NONE);
   drawingCanvas.addPaintListener(new ArcExamplePaintListener());
   // Add a handler to redraw the arc when pressed
   button.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       drawingCanvas.redraw();
     }
   });
 }
 /**
  * This class gets the user input and draws the requested arc
  */
 private class ArcExamplePaintListener implements PaintListener {
   public void paintControl(PaintEvent e) {
     // Get the canvas for drawing and its dimensions
     Canvas canvas = (Canvas) e.widget;
     int x = canvas.getBounds().width;
     int y = canvas.getBounds().height;
     // Determine user input, defaulting everything to zero.
     // Any blank fields are converted to zero
     int width = 0;
     int height = 0;
     int begin = 0;
     int angle = 0;
     try {
       width = txtWidth.getText().length() == 0 ? 0 : Integer.parseInt(txtWidth
           .getText());
       height = txtHeight.getText().length() == 0 ? 0 : Integer
           .parseInt(txtHeight.getText());
       begin = txtBeginAngle.getText().length() == 0 ? 0 : Integer
           .parseInt(txtBeginAngle.getText());
       angle = txtAngle.getText().length() == 0 ? 0 : Integer.parseInt(txtAngle
           .getText());
     } catch (NumberFormatException ex) {
       // Any problems, reset them all to zero
       width = 0;
       height = 0;
       begin = 0;
       angle = 0;
     }
     // Set the drawing color to black
     e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_BLACK));
     // Draw the arc, centered on the canvas
     e.gc
         .fillArc((x - width) / 2, (y - height) / 2, width, height, begin, angle);
   }
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new ArcExample().run();
 }

}


 </source>
   
  
 
  



Demonstrates drawing lines

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.*; import org.eclipse.swt.events.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.layout.*; /**

* This class demonstrates drawing lines
*/

public class LineExample {

 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Line Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout());
   // Create a canvas to draw on
   Canvas canvas = new Canvas(shell, SWT.NONE);
   // Add a handler to do the drawing
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       // Get the canvas and its size
       Canvas canvas = (Canvas) e.widget;
       int maxX = canvas.getSize().x;
       int maxY = canvas.getSize().y;
       // Calculate the middle
       int halfX = (int) maxX / 2;
       int halfY = (int) maxY / 2;
       // Set the drawing color to blue
       e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_BLUE));
       // Set the width of the lines to draw
       e.gc.setLineWidth(10);
       // Draw a vertical line halfway across the canvas
       e.gc.drawLine(halfX, 0, halfX, maxY);
       // Draw a horizontal line halfway down the canvas
       e.gc.drawLine(0, halfY, maxX, halfY);
     }
   });
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new LineExample().run();
 }

}


 </source>
   
  
 
  



Demonstrates drawing ovals

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates drawing ovals
*/

public class OvalExample {

 private Text txtWidth = null;
 private Text txtHeight = null;
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Oval Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout(SWT.VERTICAL));
   // Create the composite that holds the input fields
   Composite widgetComposite = new Composite(shell, SWT.NONE);
   widgetComposite.setLayout(new GridLayout(2, false));
   // Create the input fields
   new Label(widgetComposite, SWT.NONE).setText("Width:");
   txtWidth = new Text(widgetComposite, SWT.BORDER);
   new Label(widgetComposite, SWT.NONE).setText("Height");
   txtHeight = new Text(widgetComposite, SWT.BORDER);
   // Create the button that launches the redraw
   Button button = new Button(widgetComposite, SWT.PUSH);
   button.setText("Redraw");
   shell.setDefaultButton(button);
   // Create the canvas to draw the oval on
   final Canvas drawingCanvas = new Canvas(shell, SWT.NONE);
   drawingCanvas.addPaintListener(new OvalExamplePaintListener());
   // Add a handler to redraw the oval when pressed
   button.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       drawingCanvas.redraw();
     }
   });
 }
 /**
  * This class gets the user input and draws the requested oval
  */
 private class OvalExamplePaintListener implements PaintListener {
   public void paintControl(PaintEvent e) {
     // Get the canvas for drawing and its width and height
     Canvas canvas = (Canvas) e.widget;
     int x = canvas.getBounds().width;
     int y = canvas.getBounds().height;
     // Determine user input, defaulting everything to zero.
     // Any blank fields are converted to zero
     int width = 0;
     int height = 0;
     try {
       width = txtWidth.getText().length() == 0 ? 0 : Integer.parseInt(txtWidth
           .getText());
       height = txtHeight.getText().length() == 0 ? 0 : Integer
           .parseInt(txtHeight.getText());
     } catch (NumberFormatException ex) {
       // Any problems, set them both to zero
       width = 0;
       height = 0;
     }
     // Set the drawing width for the oval
     e.gc.setLineWidth(4);
     // Draw the requested oval
     e.gc.drawOval((x - width) / 2, (y - height) / 2, width, height);
   }
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new OvalExample().run();
 }

}


 </source>
   
  
 
  



Demonstrates drawing points. It draws a sine wave

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.*; /**

* This class demonstrates drawing points. It draws a sine wave.
*/

public class PointExample {

 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Point Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout());
   // Create the canvas for drawing on
   Canvas canvas = new Canvas(shell, SWT.NONE);
   // Add the paint handler to draw the sine wave
   canvas.addPaintListener(new PointExamplePaintListener());
   // Use a white background
   canvas.setBackground(shell.getDisplay().getSystemColor(SWT.COLOR_WHITE));
 }
 /**
  * This class draws a sine wave using points
  */
 private class PointExamplePaintListener implements PaintListener {
   public void paintControl(PaintEvent e) {
     // Get the canvas and its dimensions
     Canvas canvas = (Canvas) e.widget;
     int maxX = canvas.getSize().x;
     int maxY = canvas.getSize().y;
     // Calculate the middle
     int halfX = (int) maxX / 2;
     int halfY = (int) maxY / 2;
     // Set the line color and draw a horizontal axis
     e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_BLACK));
     e.gc.drawLine(0, halfY, maxX, halfY);
     // Draw the sine wave
     for (int i = 0; i < maxX; i++) {
       e.gc.drawPoint(i, getNormalizedSine(i, halfY, maxX));
     }
   }
   /**
    * Calculates the sine value
    * 
    * @param x the value along the x-axis
    * @param halfY the value of the y-axis
    * @param maxX the width of the x-axis
    * @return int
    */
   int getNormalizedSine(int x, int halfY, int maxX) {
     double piDouble = 2 * Math.PI;
     double factor = piDouble / maxX;
     return (int) (Math.sin(x * factor) * halfY + halfY);
   }
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new PointExample().run();
 }

}


 </source>
   
  
 
  



Demonstrates drawing polygons

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates drawing polygons
*/

public class PolygonExample {

 private Text txtWidth = null;
 private Text txtHeight = null;
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Polygon Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout(SWT.VERTICAL));
   // Create the canvas to draw the polygons on
   Canvas drawingCanvas = new Canvas(shell, SWT.NONE);
   drawingCanvas.addPaintListener(new PolygonExamplePaintListener());
 }
 /**
  * This class gets the user input and draws the requested oval
  */
 private class PolygonExamplePaintListener implements PaintListener {
   public void paintControl(PaintEvent e) {
     // Get the canvas for drawing and its dimensions
     Canvas canvas = (Canvas) e.widget;
     int x = canvas.getBounds().width;
     int y = canvas.getBounds().height;
     // Set the drawing color
     e.gc.setBackground(e.display.getSystemColor(SWT.COLOR_BLACK));
     // Create the points for drawing a triangle in the upper left
     int[] upper_left = { 0, 0, 200, 0, 0, 200};
     // Create the points for drawing a triangle in the lower right
     int[] lower_right = { x, y, x, y - 200, x - 200, y};
     // Draw the triangles
     e.gc.fillPolygon(upper_left);
     e.gc.fillPolygon(lower_right);
   }
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new PolygonExample().run();
 }

}


 </source>
   
  
 
  



Demonstrates how to draw text

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates how to draw text
*/

public class DrawText {

 // The string to draw
 private static final String HELLO = "Hello,\n&World!\tFrom SWT";
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   final Shell shell = new Shell(display);
   // Load an image to use as the background
   final Image image = new Image(display, this.getClass().getResourceAsStream(
       "jexp.gif"));
   shell.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       /* Stretch the image to fill the window*/
       
       Rectangle rect = shell.getClientArea();
       event.gc.drawImage(image, 0, 0, image.getImageData().width, image
           .getImageData().height, 0, 0, rect.width, rect.height);
       // This will draw the string on one line, with non-printing characters
       // for \n and \t, with an ampersand, and with an opaque background
       event.gc.drawString(HELLO, 5, 0);
       // This will draw the string on one line, with non-printing characters
       // for \n and \t, with an ampersand, and with a transparent background
       event.gc.drawString(HELLO, 5, 40, true);
       // This will draw the string on two lines, with a tab between World! and
       // From, with an ampersand, and with an opaque background
       event.gc.drawText(HELLO, 5, 80);
       // This will draw the string on two lines, with a tab between World! and
       // From, with an ampersand, and with a transparent background
       event.gc.drawText(HELLO, 5, 120, true);
       // This will draw the string on two lines, with a tab between World! and
       // From, with the W underlined, and with a transparent background
       event.gc.drawText(HELLO, 5, 160, SWT.DRAW_MNEMONIC | SWT.DRAW_DELIMITER
           | SWT.DRAW_TAB | SWT.DRAW_TRANSPARENT);
     }
   });
   shell.setText("Draw Text");
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   image.dispose();
   display.dispose();
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new DrawText().run();
 }

}


 </source>
   
  
 
  



Demonstrates how to draw text in colors

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates how to draw text in colors
*/

public class ColorFont {

 // The color indices to use for the text
 private static final int[] COLOR_INDICES = { SWT.COLOR_BLUE, SWT.COLOR_GREEN,
     SWT.COLOR_RED, SWT.COLOR_GRAY};
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   final Shell shell = new Shell(display);
   // Handler to do the drawing
   shell.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       // Loop through the colors, moving down the screen each iteration
       for (int i = 0, n = COLOR_INDICES.length, y = 0, height = event.gc
           .getFontMetrics().getHeight(); i < n; i++, y += height) {
         event.gc.setForeground(shell.getDisplay().getSystemColor(
             COLOR_INDICES[i]));
         event.gc.drawText("Hooray for Color!", 0, y);
       }
     }
   });
   shell.setText("Color Font");
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new ColorFont().run();
 }

}


 </source>
   
  
 
  



Demonstrates how to draw vertical text

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates how to draw vertical text
*/

public class VerticalTextSpanish {

 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   final Shell shell = new Shell(display);
   final Font font = new Font(display, "Arial", 36, SWT.ITALIC);
   // Create "Hello" image
   final Image hello = GraphicsUtils.createRotatedText("Hola", font, shell
       .getForeground(), shell.getBackground(), SWT.UP);
   // Create "Good Bye" image
   final Image goodBye = GraphicsUtils.createRotatedText("Chao Pescado", font,
       shell.getForeground(), shell.getBackground(), SWT.DOWN);
   shell.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       // Set the font
       event.gc.setFont(font);
       // Draw hello in the upper left
       event.gc.drawImage(hello, 0, 0);
       // Draw good bye in the lower right
       // Note how we calculate the origin
       Rectangle rcImage = goodBye.getBounds();
       Rectangle rect = shell.getClientArea();
       event.gc.drawImage(goodBye, rect.width - rcImage.width, rect.height
           - rcImage.height);
     }
   });
   shell.setText("Vertical Text Spanish");
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   goodBye.dispose();
   hello.dispose();
   font.dispose();
   display.dispose();
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new VerticalTextSpanish().run();
 }

}


 </source>
   
  
 
  



Demonstrates the effects of the flags on the constructor

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class demonstrates the effects of the flags on the constructor:
* 
* Image(Device device, Image srcImage, int flag)
*/

public class ShowImageFlags {

 // Members to hold the images
 private Image image;
 private Image copy;
 private Image disable;
 private Image gray;
 /**
  * Runs the program
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Show Image Flags");
   // Load the image
   image = new Image(display, this.getClass().getResourceAsStream(
       "jexp.gif"));
   // Create the duplicate image
   copy = new Image(display, image, SWT.IMAGE_COPY);
   // Create the disabled image
   disable = new Image(display, image, SWT.IMAGE_DISABLE);
   // Create the gray image
   gray = new Image(display, image, SWT.IMAGE_GRAY);
   createContents(shell);
   shell.pack();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   // Dispose the images
   image.dispose();
   copy.dispose();
   disable.dispose();
   gray.dispose();
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout());
   // Create labels to hold each image
   new Label(shell, SWT.NONE).setImage(image);
   new Label(shell, SWT.NONE).setImage(copy);
   new Label(shell, SWT.NONE).setImage(disable);
   new Label(shell, SWT.NONE).setImage(gray);
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new ShowImageFlags().run();
 }

}


 </source>
   
  
 
  



Displays information about the display device

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /**

* This class displays information about the display device.
*/

public class ShowDevice {

 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Display Device");
   createContents(shell);
   shell.pack();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout());
   // Create a text box to hold the data
   Text text = new Text(shell, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
   // Get the display device
   Device device = shell.getDisplay();
   // Put its data into a buffer
   StringBuffer buf = new StringBuffer();
   buf.append("getBounds(): ").append(device.getBounds()).append("\n");
   buf.append("getClientArea(): ").append(device.getClientArea()).append("\n");
   buf.append("getDepth(): ").append(device.getDepth()).append("\n");
   buf.append("getDPI(): ").append(device.getDPI()).append("\n");
   // By setting warnings to true and then getting warnings, we know if the
   // current platform supports it
   device.setWarnings(true);
   buf.append("Warnings supported: ").append(device.getWarnings()).append("\n");
   // Put the collected information into the text box
   text.setText(buf.toString());
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new ShowDevice().run();
 }

}


 </source>
   
  
 
  



Draw2D Sample

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-7-3 17:22:26 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.draw2d.Button; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.ruposite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; public class Draw2DSample extends ApplicationWindow {

 /* (non-Javadoc)
  * @see org.eclipse.jface.window.ApplicationWindow#addToolBar(int)
  */
 protected void addToolBar(int style) {
   super.addToolBar(style);
 }
 /* (non-Javadoc)
  * @see org.eclipse.jface.window.Window#createContents(org.eclipse.swt.widgets.ruposite)
  */
 protected Control createContents(Composite parent) {
   Composite composite = new Composite(parent, SWT.NULL);
   composite.setLayout(new FillLayout());
   
   Canvas canvas = new Canvas(composite, SWT.NULL);
   
   LightweightSystem lws = new LightweightSystem(canvas);
   Button button = new Button("Button", new Image(getShell().getDisplay(), "jexp.gif"));
   lws.setContents(button);
   
   return composite;
 }
 /**
  * @param parentShell
  */
 public Draw2DSample(Shell parentShell) {
   super(parentShell);
 }
 public static void main(String[] args) {
   Draw2DSample window = new Draw2DSample(null);
   window.setBlockOnOpen(true);
   window.open();
 }

}


 </source>
   
  
 
  



Drawings

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-18 18:33:36 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Drawings {

 Display display = new Display();
 Shell shell = new Shell(display);
 public Drawings() {
   shell.setLayout(new FillLayout());
   
   Canvas canvas = new Canvas(shell, SWT.BORDER);
   canvas.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
   
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       

// e.gc.drawString("SWT.LINE_SOLID (default)", 10, 10); // e.gc.drawString("SWT.LINE_DASH", 10, 30); // e.gc.drawString("SWT.LINE_DOT", 10, 50); // e.gc.drawString("SWT.LINE_DASHDOT", 10, 70); // e.gc.drawString("SWT.LINE_DASHDOTDOT", 10, 90); // e.gc.drawString("Line width = 1 (default)", 10, 120); // e.gc.drawString("Line width = 3", 10, 140); // // int start = 150; // e.gc.setLineWidth(1); // e.gc.setLineStyle(SWT.LINE_SOLID); // e.gc.drawLine(start, 15, start + 200, 15); // e.gc.setLineStyle(SWT.LINE_DASH); // e.gc.drawLine(start, 35, start + 200, 35); // e.gc.setLineStyle(SWT.LINE_DOT); // e.gc.drawLine(start, 55, start + 200, 55); // e.gc.setLineStyle(SWT.LINE_DASHDOT); // e.gc.drawLine(start, 75, start + 200, 75); // e.gc.setLineStyle(SWT.LINE_DASHDOTDOT); // e.gc.drawLine(start, 95, start + 200, 95); // // e.gc.setLineStyle(SWT.LINE_SOLID); // e.gc.drawLine(start, 125, start + 200, 125); // e.gc.setLineWidth(3); // e.gc.drawLine(start, 145, start + 200, 145);


// int[] points = new int[3 * 2]; // points[0] = 10; // The point at the top. // points[1] = 10; // // points[2] = 10; // The point at the left bottom. // points[3] = 100; // // points[4] = 100; // the point at the right bottom // points[5] = 100; // // //e.gc.drawPolyline(points);

       e.gc.setLineStyle(SWT.LINE_SOLID);
       e.gc.setBackground(display.getSystemColor(SWT.COLOR_DARK_GREEN));
       e.gc.fillArc(10, 10, 200, 100, 0, -90);
       e.gc.setLineStyle(SWT.LINE_DOT);
       e.gc.drawLine(0, 60, 220, 60);
       e.gc.drawLine(110, 0, 110, 120);
     }
   });
   
   shell.pack();
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new Drawings();
 }

}


 </source>
   
  
 
  



Drawing with transformations, paths and alpha blending

   <source lang="java">

/*

* Drawing with transformations, paths and alpha blending
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.graphics.Transform; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; public class Snippet10 {

 public static void main(String[] args) {
   final Display display = new Display();
   final Shell shell = new Shell(display);
   shell.setText("Advanced Graphics");
   FontData fd = shell.getFont().getFontData()[0];
   final Font font = new Font(display, fd.getName(), 60, SWT.BOLD
       | SWT.ITALIC);
   final Image image = new Image(display, 640, 480);
   final Rectangle rect = image.getBounds();
   GC gc = new GC(image);
   gc.setBackground(display.getSystemColor(SWT.COLOR_RED));
   gc.fillOval(rect.x, rect.y, rect.width, rect.height);
   gc.dispose();
   shell.addListener(SWT.Paint, new Listener() {
     public void handleEvent(Event event) {
       GC gc = event.gc;
       Transform tr = new Transform(display);
       tr.translate(50, 120);
       tr.rotate(-30);
       gc.drawImage(image, 0, 0, rect.width, rect.height, 0, 0,
           rect.width / 2, rect.height / 2);
       gc.setAlpha(100);
       gc.setTransform(tr);
       Path path = new Path(display);
       path.addString("SWT", 0, 0, font);
       gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
       gc.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
       gc.fillPath(path);
       gc.drawPath(path);
       tr.dispose();
       path.dispose();
     }
   });
   shell.setSize(shell.ruputeSize(rect.width / 2, rect.height / 2));
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   image.dispose();
   font.dispose();
   display.dispose();
 }

}


 </source>
   
  
 
  



Draw lines and polygons with different cap and join styles

   <source lang="java">

/*

* Draw lines and polygons with different cap and join styles
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; public class Snippet168 {

 public static void main(String[] args) {
   final Display display = new Display();
   Shell shell = new Shell(display);
   shell.addListener(SWT.Paint, new Listener() {
     public void handleEvent(Event event) {
       int x = 20, y = 20, w = 120, h = 60;
       GC gc = event.gc;
       gc.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
       gc.setLineWidth(10);
       int[] caps = { SWT.CAP_FLAT, SWT.CAP_ROUND, SWT.CAP_SQUARE };
       for (int i = 0; i < caps.length; i++) {
         gc.setLineCap(caps[i]);
         gc.drawLine(x, y, x + w, y);
         y += 20;
       }
       int[] joins = { SWT.JOIN_BEVEL, SWT.JOIN_MITER, SWT.JOIN_ROUND };
       for (int i = 0; i < joins.length; i++) {
         gc.setLineJoin(joins[i]);
         gc
             .drawPolygon(new int[] { x, y, x + w / 2, y + h,
                 x + w, y });
         y += h + 20;
       }
     }
   });
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
 }

}


 </source>
   
  
 
  



Draw Round Rectangle

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; public class RoundRectangleExample {

 private Text txtArcWidth = null;
 private Text txtArcHeight = null;
 /**
  * Runs the application
  */
 public void run() {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("RoundRectangle Example");
   createContents(shell);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       display.sleep();
     }
   }
   display.dispose();
 }
 /**
  * Creates the main window"s contents
  * 
  * @param shell the main window
  */
 private void createContents(Shell shell) {
   shell.setLayout(new FillLayout(SWT.VERTICAL));
   // Create the composite that holds the input fields
   Composite widgetComposite = new Composite(shell, SWT.NONE);
   widgetComposite.setLayout(new GridLayout(2, false));
   // Create the input fields
   new Label(widgetComposite, SWT.NONE).setText("Arc Width:");
   txtArcWidth = new Text(widgetComposite, SWT.BORDER);
   new Label(widgetComposite, SWT.NONE).setText("Arc Height");
   txtArcHeight = new Text(widgetComposite, SWT.BORDER);
   // Create the button that launches the redraw
   Button button = new Button(widgetComposite, SWT.PUSH);
   button.setText("Redraw");
   shell.setDefaultButton(button);
   // Create the canvas to draw the round rectangle on
   final Canvas drawingCanvas = new Canvas(shell, SWT.NONE);
   drawingCanvas.addPaintListener(new RoundRectangleExamplePaintListener());
   // Add a handler to redraw the round rectangle when pressed
   button.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       drawingCanvas.redraw();
     }
   });
 }
 /**
  * This class gets the user input and draws the requested round rectangle
  */
 private class RoundRectangleExamplePaintListener implements PaintListener {
   public void paintControl(PaintEvent e) {
     // Get the canvas for drawing and its width and height
     Canvas canvas = (Canvas) e.widget;
     int x = canvas.getBounds().width;
     int y = canvas.getBounds().height;
     // Determine user input, defaulting everything to zero.
     // Any blank fields are converted to zero
     int arcWidth = 0;
     int arcHeight = 0;
     try {
       arcWidth = txtArcWidth.getText().length() == 0 ? 0 : Integer
           .parseInt(txtArcWidth.getText());
       arcHeight = txtArcWidth.getText().length() == 0 ? 0 : Integer
           .parseInt(txtArcHeight.getText());
     } catch (NumberFormatException ex) {
       // Any problems, set them both to zero
       arcWidth = 0;
       arcHeight = 0;
     }
     // Set the line width
     e.gc.setLineWidth(4);
     // Draw the round rectangle
     e.gc.drawRoundRectangle(10, 10, x - 20, y - 20, arcWidth, arcHeight);
   }
 }
 /**
  * The application entry point
  * 
  * @param args the command line arguments
  */
 public static void main(String[] args) {
   new RoundRectangleExample().run();
 }

}


 </source>
   
  
 
  



Draw Text Demo

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-19 13:48:04 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class DrawTextDemo {

 Display display = new Display();
 Shell shell = new Shell(display);
 public DrawTextDemo() {
   shell.setLayout(new FillLayout());
   
   final Canvas canvas = new Canvas(shell, SWT.NO_BACKGROUND);
   
   final Image image = new Image(display, "jexp.gif");
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       Rectangle size = image.getBounds();
       // Draws the background image.
       e.gc.drawImage(image, 0, 0, size.width, size.height, 0, 0, canvas.getSize().x, canvas.getSize().y);
       
       Font font = new Font(display, "Tahoma", 18, SWT.BOLD);
       e.gc.setFont(font);
       e.gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
       e.gc.setBackground(display.getSystemColor(SWT.COLOR_BLUE));
       String english = "SWT rocks!";
       String chinese = "\u4e2d\u6587\u6c49\u5b57\u6d4b\u8bd5";
       
       e.gc.drawString(english, 10, 10);
       e.gc.drawString(chinese, 10, 80, true);
       
       String text = "Text to be drawn in the center";
       Point textSize = e.gc.textExtent(text);
       e.gc.drawText(text, (canvas.getSize().x - textSize.x)/2, (canvas.getSize().y - textSize.y)/2);
       
       font.dispose();
     }
   });
   
   shell.setSize(300, 150);
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new DrawTextDemo();
 }

}


 </source>
   
  
 
  



GC Creation

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-18 15:03:44 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; /**

* 
*/

public class GCCreation {

 Display display = new Display();
 Shell shell = new Shell(display);
 public GCCreation() {
   Image image = new Image(display, "jexp.gif");
   
   // Clones the image. 
   Image image2 = new Image(display, image.getImageData());
   // Draws an oval
   GC gc = new GC(image2);
   gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
   gc.drawOval(10, 10, 90, 40);
   gc.dispose();
   
   CLabel label = new CLabel(shell, SWT.NULL);
   label.setImage(image);
   label.setBounds(10, 10, 130, 130);
   
   CLabel label2 = new CLabel(shell, SWT.NULL);
   label2.setImage(image2);
   label2.setBounds(150, 10, 130, 130);
   shell.pack();
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 public static void main(String[] args) {
   new GCCreation();
 }

}


 </source>
   
  
 
  



GC example: draw a thick line

   <source lang="java">

/*

* GC example snippet: draw a thick line
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Snippet13 {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.open();
   GC gc = new GC(shell);
   gc.setLineWidth(4);
   gc.drawRectangle(20, 20, 100, 100);
   gc.dispose();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }

}


 </source>
   
  
 
  



GC: implement a simple scribble program

   <source lang="java">

/*

* GC example snippet: implement a simple scribble program
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; public class Snippet66 {

 public static void main(String[] args) {
   Display display = new Display();
   final Shell shell = new Shell(display);
   Listener listener = new Listener() {
     int lastX = 0, lastY = 0;
     public void handleEvent(Event event) {
       switch (event.type) {
       case SWT.MouseMove:
         if ((event.stateMask & SWT.BUTTON1) == 0)
           break;
         GC gc = new GC(shell);
         gc.drawLine(lastX, lastY, event.x, event.y);
         gc.dispose();
       // FALL THROUGH
       case SWT.MouseDown:
         lastX = event.x;
         lastY = event.y;
         break;
       }
     }
   };
   shell.addListener(SWT.MouseDown, listener);
   shell.addListener(SWT.MouseMove, listener);
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }

}


 </source>
   
  
 
  



GC: measure a string

   <source lang="java">

/*

* GC example snippet: measure a string
*
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; public class Snippet93 {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setLayout(new RowLayout());
   Label label = new Label(shell, SWT.NONE);
   GC gc = new GC(label);
   Point size = gc.textExtent("Hello");
   gc.dispose();
   label.setText("Hello -> " + size);
   shell.pack();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }

}


 </source>
   
  
 
  



How to draw directly on an SWT Control

   <source lang="java">

import java.util.ResourceBundle; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; 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.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; /*

* This example builds on HelloWorld1 and demonstrates how to draw directly
* on an SWT Control.
*/

public class HelloWorld5 {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new HelloWorld5().open(display);
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }
 public Shell open(Display display) {
   final Color red = new Color(display, 0xFF, 0, 0);
   final Shell shell = new Shell(display);
   shell.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       GC gc = event.gc;
       gc.setForeground(red);
       Rectangle rect = shell.getClientArea();
       gc.drawRectangle(rect.x + 10, rect.y + 10, rect.width - 20,
           rect.height - 20);
       gc.drawString("Hello_world", rect.x + 20,
           rect.y + 20);
     }
   });
   shell.addDisposeListener(new DisposeListener() {
     public void widgetDisposed(DisposeEvent e) {
       red.dispose();
     }
   });
   shell.open();
   return shell;
 }

}


 </source>
   
  
 
  



Palettes

   <source lang="java">

/*******************************************************************************

* All Right Reserved. Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-21 20:12:55 by JACK $Id$
*  
******************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Palettes {

 Display display = new Display();
 Shell shell = new Shell(display);
 public Palettes() {
   shell.setLayout(new FillLayout());
   PaletteData paletteData = new PaletteData(0xFF0000, 0x00FF00, 0x0000FF);
   ImageData imageData = new ImageData(100, 100, 24, paletteData);
   for (int i = 0; i < 100; i++) { // each column.
     for (int j = 0; j < 100; j++) { // each row.
       if (j < 30 || (i > 35 && i < 65))
         imageData.setPixel(i, j, 0xFF);
       else
         imageData.setPixel(i, j, 0xFFFF00);
     }
   }
   //    int pixelValue = imageData.getPixel(50, 50);
   //    int redComponent = pixelValue & imageData.palette.redMask;
   //    int greenComponent = pixelValue & imageData.palette.greenMask;
   //    int blueComponent = pixelValue & imageData.palette.blueMask;
   PaletteData paletteData2 =
     new PaletteData(new RGB[] { new RGB(0, 0, 255), // blue
     new RGB(255, 255, 0) // yellow
   });
   
   ImageData imageData2 = new ImageData(100, 100, 1, paletteData2);
   for (int i = 0; i < 100; i++) { // each column.
     for (int j = 0; j < 100; j++) { // each row.
       if (j < 30 || (i > 35 && i < 65))
         imageData2.setPixel(i, j, 0);
       else
         imageData2.setPixel(i, j, 1);
     }
   }
   
   System.out.println(imageData.palette.getRGB(imageData.getPixel(50, 50)));
   
   final Image image2 = new Image(display, imageData2);
   final Image image = new Image(display, imageData);
   final Canvas canvas = new Canvas(shell, SWT.NULL);
   canvas.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       e.gc.drawImage(image2, 0, 0);
     }
   });
   shell.pack();
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new Palettes();
 }

}


 </source>
   
  
 
  



SWT 2D Chart: Flowchart

   <source lang="java">

/* SWT/JFace in Action GUI Design with Eclipse 3.0 Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic ISBN: 1932394273 Publisher: Manning

  • /

import java.util.Enumeration; import java.util.Hashtable; import org.eclipse.draw2d.AbstractConnectionAnchor; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.ConnectionAnchor; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.FreeformLayeredPane; import org.eclipse.draw2d.FreeformLayout; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.ManhattanConnectionRouter; import org.eclipse.draw2d.MarginBorder; import org.eclipse.draw2d.MouseEvent; import org.eclipse.draw2d.MouseListener; import org.eclipse.draw2d.MouseMotionListener; import org.eclipse.draw2d.PolylineConnection; import org.eclipse.draw2d.PolylineDecoration; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.PrecisionPoint; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Flowchart {

 public static void main(String args[]) {
   Shell shell = new Shell();
   shell.setSize(200, 300);
   shell.open();
   shell.setText("Flowchart");
   LightweightSystem lws = new LightweightSystem(shell);
   ChartFigure flowchart = new ChartFigure();
   lws.setContents(flowchart);
   TerminatorFigure start = new TerminatorFigure();
   start.setName("Start");
   start.setBounds(new Rectangle(40, 20, 80, 20));
   DecisionFigure dec = new DecisionFigure();
   dec.setName("Should I?");
   dec.setBounds(new Rectangle(30, 60, 100, 60));
   ProcessFigure proc = new ProcessFigure();
   proc.setName("Do it!");
   proc.setBounds(new Rectangle(40, 140, 80, 40));
   TerminatorFigure stop = new TerminatorFigure();
   stop.setName("End");
   stop.setBounds(new Rectangle(40, 200, 80, 20));
   PathFigure path1 = new PathFigure();
   path1.setSourceAnchor(start.outAnchor);
   path1.setTargetAnchor(dec.inAnchor);
   PathFigure path2 = new PathFigure();
   path2.setSourceAnchor(dec.yesAnchor);
   path2.setTargetAnchor(proc.inAnchor);
   PathFigure path3 = new PathFigure();
   path3.setSourceAnchor(dec.noAnchor);
   path3.setTargetAnchor(stop.inAnchor);
   PathFigure path4 = new PathFigure();
   path4.setSourceAnchor(proc.outAnchor);
   path4.setTargetAnchor(stop.inAnchor);
   flowchart.add(start);
   flowchart.add(dec);
   flowchart.add(proc);
   flowchart.add(stop);
   flowchart.add(path1);
   flowchart.add(path2);
   flowchart.add(path3);
   flowchart.add(path4);
   new Dnd(start);
   new Dnd(proc);
   new Dnd(dec);
   new Dnd(stop);
   Display display = Display.getDefault();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
 }

} class ChartFigure extends FreeformLayeredPane {

 public ChartFigure() {
   setLayoutManager(new FreeformLayout());
   setBorder(new MarginBorder(5));
   setBackgroundColor(ColorConstants.white);
   setOpaque(true);
 }

} class Dnd extends MouseMotionListener.Stub implements MouseListener {

 public Dnd(IFigure figure) {
   figure.addMouseMotionListener(this);
   figure.addMouseListener(this);
 }
 Point start;
 public void mouseReleased(MouseEvent e) {
 }
 public void mouseClicked(MouseEvent e) {
 }
 public void mouseDoubleClicked(MouseEvent e) {
 }
 public void mousePressed(MouseEvent e) {
   start = e.getLocation();
 }
 public void mouseDragged(MouseEvent e) {
   Point p = e.getLocation();
   Dimension d = p.getDifference(start);
   start = p;
   Figure f = ((Figure) e.getSource());
   f.setBounds(f.getBounds().getTranslated(d.width, d.height));
 }

} class TerminatorFigure extends ActivityFigure {

 FixedAnchor inAnchor, outAnchor;
 public TerminatorFigure() {
   inAnchor = new FixedAnchor(this);
   inAnchor.place = new Point(1, 0);
   targetAnchors.put("in_term", inAnchor);
   outAnchor = new FixedAnchor(this);
   outAnchor.place = new Point(1, 2);
   sourceAnchors.put("out_term", outAnchor);
 }
 public void paintFigure(Graphics g) {
   Rectangle r = bounds;
   g.drawArc(r.x + r.width / 8, r.y, r.width / 4, r.height - 1, 90, 180);
   g.drawLine(r.x + r.width / 4, r.y, r.x + 3 * r.width / 4, r.y);
   g.drawLine(r.x + r.width / 4, r.y + r.height - 1,
       r.x + 3 * r.width / 4, r.y + r.height - 1);
   g.drawArc(r.x + 5 * r.width / 8, r.y, r.width / 4, r.height - 1, 270,
       180);
   g.drawText(message, r.x + 3 * r.width / 8, r.y + r.height / 8);
 }

} class FixedAnchor extends AbstractConnectionAnchor {

 Point place;
 public FixedAnchor(IFigure owner) {
   super(owner);
 }
 public Point getLocation(Point loc) {
   Rectangle r = getOwner().getBounds();
   int x = r.x + place.x * r.width / 2;
   int y = r.y + place.y * r.height / 2;
   Point p = new PrecisionPoint(x, y);
   getOwner().translateToAbsolute(p);
   return p;
 }

} class DecisionFigure extends ActivityFigure {

 FixedAnchor inAnchor, yesAnchor, noAnchor;
 public DecisionFigure() {
   inAnchor = new FixedAnchor(this);
   inAnchor.place = new Point(1, 0);
   targetAnchors.put("in_dec", inAnchor);
   noAnchor = new FixedAnchor(this);
   noAnchor.place = new Point(2, 1);
   sourceAnchors.put("no", noAnchor);
   yesAnchor = new FixedAnchor(this);
   yesAnchor.place = new Point(1, 2);
   sourceAnchors.put("yes", yesAnchor);
 }
 public void paintFigure(Graphics g) {
   Rectangle r = bounds;
   PointList pl = new PointList(4);
   pl.addPoint(r.x + r.width / 2, r.y);
   pl.addPoint(r.x, r.y + r.height / 2);
   pl.addPoint(r.x + r.width / 2, r.y + r.height - 1);
   pl.addPoint(r.x + r.width, r.y + r.height / 2);
   g.drawPolygon(pl);
   g.drawText(message, r.x + r.width / 4 + 5, r.y + 3 * r.height / 8);
   g.drawText("N", r.x + 7 * r.width / 8, r.y + 3 * r.height / 8);
   g.drawText("Y", r.x + r.width / 2 - 2, r.y + 3 * r.height / 4);
 }

} class PathFigure extends PolylineConnection {

 public PathFigure() {
   setTargetDecoration(new PolylineDecoration());
   setConnectionRouter(new ManhattanConnectionRouter());
 }

} class ProcessFigure extends ActivityFigure {

 FixedAnchor inAnchor, outAnchor;
 public ProcessFigure() {
   inAnchor = new FixedAnchor(this);
   inAnchor.place = new Point(1, 0);
   targetAnchors.put("in_proc", inAnchor);
   outAnchor = new FixedAnchor(this);
   outAnchor.place = new Point(1, 2);
   sourceAnchors.put("out_proc", outAnchor);
 }
 public void paintFigure(Graphics g) {
   Rectangle r = bounds;
   g.drawText(message, r.x + r.width / 4, r.y + r.height / 4);
   g.drawRectangle(r.x, r.y, r.width - 1, r.height - 1);
 }

} abstract class ActivityFigure extends Figure {

 Rectangle r = new Rectangle();
 Hashtable targetAnchors = new Hashtable();
 Hashtable sourceAnchors = new Hashtable();
 String message = new String();
 public void setName(String msg) {
   message = msg;
   repaint();
 }
 public ConnectionAnchor ConnectionAnchorAt(Point p) {
   ConnectionAnchor closest = null;
   long min = Long.MAX_VALUE;
   Hashtable conn = getSourceConnectionAnchors();
   conn.putAll(getTargetConnectionAnchors());
   Enumeration e = conn.elements();
   while (e.hasMoreElements()) {
     ConnectionAnchor c = (ConnectionAnchor) e.nextElement();
     Point p2 = c.getLocation(null);
     long d = p.getDistance2(p2);
     if (d < min) {
       min = d;
       closest = c;
     }
   }
   return closest;
 }
 public ConnectionAnchor getSourceConnectionAnchor(String name) {
   return (ConnectionAnchor) sourceAnchors.get(name);
 }
 public ConnectionAnchor getTargetConnectionAnchor(String name) {
   return (ConnectionAnchor) targetAnchors.get(name);
 }
 public String getSourceAnchorName(ConnectionAnchor c) {
   Enumeration e = sourceAnchors.keys();
   String name;
   while (e.hasMoreElements()) {
     name = (String) e.nextElement();
     if (sourceAnchors.get(name).equals(c))
       return name;
   }
   return null;
 }
 public String getTargetAnchorName(ConnectionAnchor c) {
   Enumeration e = targetAnchors.keys();
   String name;
   while (e.hasMoreElements()) {
     name = (String) e.nextElement();
     if (targetAnchors.get(name).equals(c))
       return name;
   }
   return null;
 }
 public ConnectionAnchor getSourceConnectionAnchorAt(Point p) {
   ConnectionAnchor closest = null;
   long min = Long.MAX_VALUE;
   Enumeration e = getSourceConnectionAnchors().elements();
   while (e.hasMoreElements()) {
     ConnectionAnchor c = (ConnectionAnchor) e.nextElement();
     Point p2 = c.getLocation(null);
     long d = p.getDistance2(p2);
     if (d < min) {
       min = d;
       closest = c;
     }
   }
   return closest;
 }
 public Hashtable getSourceConnectionAnchors() {
   return sourceAnchors;
 }
 public ConnectionAnchor getTargetConnectionAnchorAt(Point p) {
   ConnectionAnchor closest = null;
   long min = Long.MAX_VALUE;
   Enumeration e = getTargetConnectionAnchors().elements();
   while (e.hasMoreElements()) {
     ConnectionAnchor c = (ConnectionAnchor) e.nextElement();
     Point p2 = c.getLocation(null);
     long d = p.getDistance2(p2);
     if (d < min) {
       min = d;
       closest = c;
     }
   }
   return closest;
 }
 public Hashtable getTargetConnectionAnchors() {
   return targetAnchors;
 }

} class FigureFactory {

 public static IFigure createTerminatorFigure() {
   return new TerminatorFigure();
 }
 public static IFigure createDecisionFigure() {
   return new DecisionFigure();
 }
 public static IFigure createProcessFigure() {
   return new ProcessFigure();
 }
 public static PathFigure createPathFigure() {
   return new PathFigure();
 }
 public static ChartFigure createChartFigure() {
   return new ChartFigure();
 }

}


 </source>
   
  
 
  



SWT 2D Simple Demo

   <source lang="java">

/*******************************************************************************

* Copyright (c) 2004 Berthold Daum. All rights reserved. This program and the
* accompanying materials are made available under the terms of the Common
* Public License v1.0 which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
* 
* Contributors: Berthold Daum
******************************************************************************/

import java.awt.RenderingHints; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.ruposite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class SWT2D {

 // Shell fur Popup-Editor
 Shell eShell = null;
 // Text-Widget fur Editor
 Text eText = null;
 // Liste eingegebener Zeichenketten
 ArrayList wordList = new ArrayList(12);
 public static void main(String[] args) {
   SWT2D swtawt = new SWT2D();
   swtawt.run();
 }
 private void run() {
   // Create top level shell
   final Display display = new Display();
   final Shell shell = new Shell(display);
   shell.setText("Java 2D Example");
   // GridLayout for canvas and button
   shell.setLayout(new GridLayout());
   // Create container for AWT canvas
   final Composite canvasComp = new Composite(shell, SWT.EMBEDDED);
   // Set preferred size
   GridData data = new GridData();
   data.widthHint = 600;
   data.heightHint = 500;
   canvasComp.setLayoutData(data);
   // Create AWT Frame for Canvas
   java.awt.Frame canvasFrame = SWT_AWT.new_Frame(canvasComp);
   // Create Canvas and add it to the Frame
   final java.awt.Canvas canvas = new java.awt.Canvas();
   canvasFrame.add(canvas);
   // Get graphical context and cast to Java2D
   final java.awt.Graphics2D g2d = (java.awt.Graphics2D) canvas
       .getGraphics();
   // Enable antialiasing
   g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
       RenderingHints.VALUE_ANTIALIAS_ON);
   // Remember initial transform
   final java.awt.geom.AffineTransform origTransform = g2d.getTransform();
   // Create Clear button and position it
   Button clearButton = new Button(shell, SWT.PUSH);
   clearButton.setText("Clear");
   data = new GridData();
   data.horizontalAlignment = GridData.CENTER;
   clearButton.setLayoutData(data);
   // Event processing for Clear button
   clearButton.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       // Delete word list and redraw canvas
       wordList.clear();
       canvasComp.redraw();
     }
   });
   // Process canvas mouse clicks
   canvas.addMouseListener(new java.awt.event.MouseListener() {
     public void mouseClicked(java.awt.event.MouseEvent e) {
     }
     public void mouseEntered(java.awt.event.MouseEvent e) {
     }
     public void mouseExited(java.awt.event.MouseEvent e) {
     }
     public void mousePressed(java.awt.event.MouseEvent e) {
       // Manage pop-up editor
       display.syncExec(new Runnable() {
         public void run() {
           if (eShell == null) {
             // Create new Shell: non-modal!
             eShell = new Shell(shell, SWT.NO_TRIM
                 | SWT.MODELESS);
             eShell.setLayout(new FillLayout());
             // Text input field
             eText = new Text(eShell, SWT.BORDER);
             eText.setText("Text rotation in the SWT?");
             eShell.pack();
             // Set position (Display coordinates)
             java.awt.Rectangle bounds = canvas.getBounds();
             org.eclipse.swt.graphics.Point pos = canvasComp
                 .toDisplay(bounds.width / 2,
                     bounds.height / 2);
             Point size = eShell.getSize();
             eShell.setBounds(pos.x, pos.y, size.x, size.y);
             // Open Shell
             eShell.open();
           } else if (!eShell.isVisible()) {
             // Editor versteckt, sichtbar machen
             eShell.setVisible(true);
           } else {
             // Editor is visible - get text
             String t = eText.getText();
             // set editor invisible
             eShell.setVisible(false);
             // Add text to list and redraw canvas
             wordList.add(t);
             canvasComp.redraw();
           }
         }
       });
     }
     public void mouseReleased(java.awt.event.MouseEvent e) {
     }
   });
   // Redraw the canvas
   canvasComp.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       // Pass the redraw task to AWT event queue
       java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
           // Compute canvas center
           java.awt.Rectangle bounds = canvas.getBounds();
           int originX = bounds.width / 2;
           int originY = bounds.height / 2;
           // Reset canvas
           g2d.setTransform(origTransform);
           g2d.setColor(java.awt.Color.WHITE);
           g2d.fillRect(0, 0, bounds.width, bounds.height);
           // Set font
           g2d.setFont(new java.awt.Font("Myriad",
               java.awt.Font.PLAIN, 32));
           double angle = 0d;
           // Prepare star shape
           double increment = Math.toRadians(30);
           Iterator iter = wordList.iterator();
           while (iter.hasNext()) {
             // Determine text colors in RGB color cycle
             float red = (float) (0.5 + 0.5 * Math.sin(angle));
             float green = (float) (0.5 + 0.5 * Math.sin(angle
                 + Math.toRadians(120)));
             float blue = (float) (0.5 + 0.5 * Math.sin(angle
                 + Math.toRadians(240)));
             g2d.setColor(new java.awt.Color(red, green, blue));
             // Redraw text
             String text = (String) iter.next();
             g2d.drawString(text, originX + 50, originY);
             // Rotate for next text output
             g2d.rotate(increment, originX, originY);
             angle += increment;
           }
         }
       });
     }
   });
   // Finish shell and open it
   shell.pack();
   shell.open();
   // SWT event processing
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }

}


 </source>
   
  
 
  



SWT 2D Unicode

   <source lang="java">

/*

* -----------------------------------------------------------------------------
* (c) Copyright IBM Corp. 2004 All rights reserved.
* 
* The sample program(s) is/are owned by International Business Machines
* Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and
* licensed, not sold.
* 
* You may copy, modify, and distribute this/these sample program(s) in any form
* without payment to IBM, for any purpose including developing, using,
* marketing or distributing programs that include or are derivative works of
* the sample program(s).
* 
* The sample program(s) is/are provided to you on an "AS IS" basis, without
* warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do
* not allow for the exclusion or limitation of implied warranties, so the above
* limitations or exclusions may not apply to you. IBM shall not be liable for
* any damages you suffer as a result of using, modifying or distributing the
* sample program(s) or its/their derivatives.
* 
* Each copy of any portion of this/these sample program(s) or any derivative
* work, must include the above copyright notice and disclaimer of warranty.
* 
* -----------------------------------------------------------------------------
*/

import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Draw2DTest {

 public static void main(String[] args) {
   final Graphics2DRenderer renderer = new Graphics2DRenderer();
   Shell shell = new Shell();
   shell.setSize(350, 350);
   shell.open();
   shell.setText("Draw2d Hello World");
   LightweightSystem lws = new LightweightSystem(shell);
   IFigure figure = new Figure() {
     protected void paintClientArea(org.eclipse.draw2d.Graphics graphics) {
       Dimension controlSize = getSize();
       renderer.prepareRendering(graphics);
       // prepares the Graphics2D renderer
       // gets the Graphics2D context and switch on the antialiasing
       Graphics2D g2d = renderer.getGraphics2D();
       g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
           RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
       // paints the background with a color gradient
       g2d.setPaint(new GradientPaint(0.0f, 0.0f,
           java.awt.Color.yellow, (float) controlSize.width,
           (float) controlSize.width, java.awt.Color.white));
       g2d.fillRect(0, 0, controlSize.width, controlSize.width);
       // draws rotated text
       g2d.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD,
           16));
       g2d.setColor(java.awt.Color.blue);
       g2d.translate(controlSize.width / 2, controlSize.width / 2);
       int nbOfSlices = 18;
       for (int i = 0; i < nbOfSlices; i++) {
         g2d.drawString("Angle = " + (i * 360 / nbOfSlices)
             + "\u00B0", 30, 0);
         g2d.rotate(-2 * Math.PI / nbOfSlices);
       }
       // now that we are done with Java2D, renders Graphics2D
       // operation
       // on the SWT graphics context
       renderer.render(graphics);
       // now we can continue with pure SWT paint operations
       graphics.drawOval(0, 0, controlSize.width, controlSize.width);
     }
   };
   lws.setContents(figure);
   Display display = Display.getDefault();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   renderer.dispose();
 }

} /*

* -----------------------------------------------------------------------------
* (c) Copyright IBM Corp. 2004 All rights reserved.
* 
* The sample program(s) is/are owned by International Business Machines
* Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and
* licensed, not sold.
* 
* You may copy, modify, and distribute this/these sample program(s) in any form
* without payment to IBM, for any purpose including developing, using,
* marketing or distributing programs that include or are derivative works of
* the sample program(s).
* 
* The sample program(s) is/are provided to you on an "AS IS" basis, without
* warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do
* not allow for the exclusion or limitation of implied warranties, so the above
* limitations or exclusions may not apply to you. IBM shall not be liable for
* any damages you suffer as a result of using, modifying or distributing the
* sample program(s) or its/their derivatives.
* 
* Each copy of any portion of this/these sample program(s) or any derivative
* work, must include the above copyright notice and disclaimer of warranty.
* 
* -----------------------------------------------------------------------------
*/

/**

* Helper class allowing the use of Java2D on SWT or Draw2D graphical context.
* 
* @author Yannick Saillet
*/

class Graphics2DRenderer {

 private static final PaletteData PALETTE_DATA = new PaletteData(0xFF0000,
     0xFF00, 0xFF);
 private BufferedImage awtImage;
 private Image swtImage;
 private ImageData swtImageData;
 private int[] awtPixels;
 /** RGB value to use as transparent color */
 private static final int TRANSPARENT_COLOR = 0x123456;
 /**
  * Prepare to render on a SWT graphics context.
  */
 public void prepareRendering(GC gc) {
   org.eclipse.swt.graphics.Rectangle clip = gc.getClipping();
   prepareRendering(clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Prepare to render on a Draw2D graphics context.
  */
 public void prepareRendering(org.eclipse.draw2d.Graphics graphics) {
   org.eclipse.draw2d.geometry.Rectangle clip = graphics
       .getClip(new org.eclipse.draw2d.geometry.Rectangle());
   prepareRendering(clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Prepare the AWT offscreen image for the rendering of the rectangular
  * region given as parameter.
  */
 private void prepareRendering(int clipX, int clipY, int clipW, int clipH) {
   // check that the offscreen images are initialized and large enough
   checkOffScreenImages(clipW, clipH);
   // fill the region in the AWT image with the transparent color
   java.awt.Graphics awtGraphics = awtImage.getGraphics();
   awtGraphics.setColor(new java.awt.Color(TRANSPARENT_COLOR));
   awtGraphics.fillRect(clipX, clipY, clipW, clipH);
 }
 /**
  * Returns the Graphics2D context to use.
  */
 public Graphics2D getGraphics2D() {
   if (awtImage == null)
     return null;
   return (Graphics2D) awtImage.getGraphics();
 }
 /**
  * Complete the rendering by flushing the 2D renderer on a SWT graphical
  * context.
  */
 public void render(GC gc) {
   if (awtImage == null)
     return;
   org.eclipse.swt.graphics.Rectangle clip = gc.getClipping();
   transferPixels(clip.x, clip.y, clip.width, clip.height);
   gc.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height, clip.x,
       clip.y, clip.width, clip.height);
 }
 /**
  * Complete the rendering by flushing the 2D renderer on a Draw2D graphical
  * context.
  */
 public void render(org.eclipse.draw2d.Graphics graphics) {
   if (awtImage == null)
     return;
   org.eclipse.draw2d.geometry.Rectangle clip = graphics
       .getClip(new org.eclipse.draw2d.geometry.Rectangle());
   transferPixels(clip.x, clip.y, clip.width, clip.height);
   graphics.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height,
       clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Transfer a rectangular region from the AWT image to the SWT image.
  */
 private void transferPixels(int clipX, int clipY, int clipW, int clipH) {
   int step = swtImageData.depth / 8;
   byte[] data = swtImageData.data;
   awtImage.getRGB(clipX, clipY, clipW, clipH, awtPixels, 0, clipW);
   for (int i = 0; i < clipH; i++) {
     int idx = (clipY + i) * swtImageData.bytesPerLine + clipX * step;
     for (int j = 0; j < clipW; j++) {
       int rgb = awtPixels[j + i * clipW];
       for (int k = swtImageData.depth - 8; k >= 0; k -= 8) {
         data[idx++] = (byte) ((rgb >> k) & 0xFF);
       }
     }
   }
   if (swtImage != null)
     swtImage.dispose();
   swtImage = new Image(Display.getDefault(), swtImageData);
 }
 /**
  * Dispose the resources attached to this 2D renderer.
  */
 public void dispose() {
   if (awtImage != null)
     awtImage.flush();
   if (swtImage != null)
     swtImage.dispose();
   awtImage = null;
   swtImageData = null;
   awtPixels = null;
 }
 /**
  * Ensure that the offscreen images are initialized and are at least as
  * large as the size given as parameter.
  */
 private void checkOffScreenImages(int width, int height) {
   int currentImageWidth = 0;
   int currentImageHeight = 0;
   if (swtImage != null) {
     currentImageWidth = swtImage.getImageData().width;
     currentImageHeight = swtImage.getImageData().height;
   }
   // if the offscreen images are too small, recreate them
   if (width > currentImageWidth || height > currentImageHeight) {
     dispose();
     width = Math.max(width, currentImageWidth);
     height = Math.max(height, currentImageHeight);
     awtImage = new BufferedImage(width, height,
         BufferedImage.TYPE_INT_ARGB);
     swtImageData = new ImageData(width, height, 24, PALETTE_DATA);
     swtImageData.transparentPixel = TRANSPARENT_COLOR;
     awtPixels = new int[width * height];
   }
 }

}


 </source>
   
  
 
  



SWT Draw 2D

   <source lang="java">

/* SWT/JFace in Action GUI Design with Eclipse 3.0 Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic ISBN: 1932394273 Publisher: Manning

  • /

import org.eclipse.swt.SWT; 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 DrawExample {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("Drawing Example");
   Canvas canvas = new Canvas(shell, SWT.NONE);
   canvas.setSize(150, 150);
   canvas.setLocation(20, 20);
   shell.open();
   shell.setSize(200, 220);
   GC gc = new GC(canvas);
   gc.drawRectangle(10, 10, 40, 45);
   gc.drawOval(65, 10, 30, 35);
   gc.drawLine(130, 10, 90, 80);
   gc.drawPolygon(new int[] { 20, 70, 45, 90, 70, 70 });
   gc.drawPolyline(new int[] { 10, 120, 70, 100, 100, 130, 130, 75 });
   gc.dispose();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }

}


 </source>
   
  
 
  



SWT Draw2D Example

   <source lang="java">

/* SWT/JFace in Action GUI Design with Eclipse 3.0 Matthew Scarpino, Stephen Holder, Stanford Ng, and Laurent Mihalkovic ISBN: 1932394273 Publisher: Manning

  • /

import org.eclipse.draw2d.ButtonGroup; import org.eclipse.draw2d.ButtonModel; import org.eclipse.draw2d.ChangeEvent; import org.eclipse.draw2d.ChangeListener; import org.eclipse.draw2d.CheckBox; import org.eclipse.draw2d.Clickable; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.draw2d.ToggleModel; import org.eclipse.draw2d.XYLayout; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Draw2D_Example {

 public static void main(String args[]) {
   final Label label = new Label("Press a button!");
   Shell shell = new Shell();
   LightweightSystem lws = new LightweightSystem(shell);
   Figure parent = new Figure();
   parent.setLayoutManager(new XYLayout());
   lws.setContents(parent);
   Clickable above = new CheckBox("I"m above!");
   parent.add(above, new Rectangle(10, 10, 80, 20));
   ButtonModel aModel = new ToggleModel();
   aModel.addChangeListener(new ChangeListener() {
     public void handleStateChanged(ChangeEvent e) {
       label.setText("Above");
     }
   });
   above.setModel(aModel);
   Clickable below = new CheckBox("I"m below!");
   parent.add(below, new Rectangle(10, 40, 80, 20));
   ButtonModel bModel = new ToggleModel();
   bModel.addChangeListener(new ChangeListener() {
     public void handleStateChanged(ChangeEvent e) {
       label.setText("Below");
     }
   });
   below.setModel(bModel);
   ButtonGroup bGroup = new ButtonGroup();
   bGroup.add(aModel);
   bGroup.add(bModel);
   bGroup.setDefault(bModel);
   parent.add(label, new Rectangle(10, 70, 80, 20));
   shell.setSize(130, 120);
   shell.open();
   shell.setText("Example");
   Display display = Display.getDefault();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
 }

}


 </source>
   
  
 
  



SWT Graphics Example

   <source lang="java">

import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Iterator; import java.util.MissingResourceException; import java.util.Random; import java.util.ResourceBundle; import java.util.Vector; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Path; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.ColorDialog; import org.eclipse.swt.widgets.rubo; import org.eclipse.swt.widgets.ruposite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Sash; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Spinner; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; public class GraphicsExample {

 Composite parent;
 GraphicsTab[] tabs;
 GraphicsTab tab;
 Object[] tabBackground;
 boolean animate;
 Listener redrawListener;
 ToolBar toolBar;
 Tree tabList;
 Canvas canvas;
 Composite controlPanel, tabPanel;
 ToolItem playItem, pauseItem, backItem, dbItem;
 Spinner timerSpinner;
 Menu backMenu;
 MenuItem customMI;
 Image customImage;
 Color customColor;
 Vector images;
 static boolean advanceGraphics, advanceGraphicsInit;
 static final int TIMER = 30;
 public GraphicsExample(final Composite parent) {
   this.parent = parent;
   redrawListener = new Listener() {
     public void handleEvent(Event e) {
       redraw();
     }
   };
   GridData data;
   GridLayout layout = new GridLayout(3, false);
   layout.horizontalSpacing = 1;
   parent.setLayout(layout);
   tabs = createTabs();
   images = new Vector();
   createToolBar(parent);
   createTabList(parent);
   final Sash sash = new Sash(parent, SWT.VERTICAL);
   createTabPanel(parent);
   data = new GridData(SWT.FILL, SWT.CENTER, true, false);
   data.horizontalSpan = 3;
   toolBar.setLayoutData(data);
   data = new GridData(SWT.CENTER, SWT.FILL, false, true);
   data.widthHint = tabList.ruputeSize(SWT.DEFAULT, SWT.DEFAULT).x + 50;
   tabList.setLayoutData(data);
   data = new GridData(SWT.CENTER, SWT.FILL, false, true);
   sash.setLayoutData(data);
   data = new GridData(SWT.FILL, SWT.FILL, true, true);
   tabPanel.setLayoutData(data);
   sash.addListener(SWT.Selection, new Listener() {
     public void handleEvent(Event event) {
       if (event.detail != SWT.DRAG) {
         GridData data = (GridData) tabList.getLayoutData();
         data.widthHint = event.x
             - tabList.ruputeTrim(0, 0, 0, 0).width;
         parent.layout(true);
         animate = pauseItem.getEnabled();
       } else {
         animate = false;
       }
     }
   });
   setTab(tab);
   startAnimationTimer();
 }
 boolean checkAdvancedGraphics() {
   if (advanceGraphicsInit)
     return advanceGraphics;
   advanceGraphicsInit = true;
   Display display = Display.getCurrent();
   try {
     Path path = new Path(display);
     path.dispose();
   } catch (SWTException e) {
     Shell shell = display.getActiveShell(), newShell = null;
     if (shell == null)
       shell = newShell = new Shell(display);
     MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
     dialog.setText("Warning"); //$NON-NLS-1$
     dialog.setMessage("LibNotFound"); //$NON-NLS-1$
     dialog.open();
     if (newShell != null)
       newShell.dispose();
     return false;
   }
   return advanceGraphics = true;
 }
 void createCanvas(Composite parent) {
   canvas = new Canvas(parent, SWT.NO_BACKGROUND);
   canvas.addListener(SWT.Paint, new Listener() {
     public void handleEvent(Event event) {
       GC gc;
       Rectangle rect = canvas.getClientArea();
       Image buffer = null;
       if (dbItem.getSelection()) {
         buffer = new Image(canvas.getDisplay(), rect);
         gc = new GC(buffer);
       } else {
         gc = event.gc;
       }
       paintBackground(gc, rect);
       GraphicsTab tab = getTab();
       if (tab != null)
         tab.paint(gc, rect.width, rect.height);
       if (gc != event.gc)
         gc.dispose();
       if (buffer != null) {
         event.gc.drawImage(buffer, 0, 0);
         buffer.dispose();
       }
     }
   });
 }
 void createControlPanel(Composite parent) {
   Group group;
   controlPanel = group = new Group(parent, SWT.NONE);
   group.setText(getResourceString("Settings")); //$NON-NLS-1$
   controlPanel.setLayout(new RowLayout());
 }
 void createTabPanel(Composite parent) {
   tabPanel = new Composite(parent, SWT.NONE);
   GridData data;
   GridLayout layout = new GridLayout(1, false);
   layout.marginHeight = layout.marginWidth = 0;
   tabPanel.setLayout(layout);
   createCanvas(tabPanel);
   createControlPanel(tabPanel);
   data = new GridData(SWT.FILL, SWT.FILL, true, true);
   canvas.setLayoutData(data);
   data = new GridData(SWT.FILL, SWT.CENTER, true, false);
   controlPanel.setLayoutData(data);
 }
 void createToolBar(final Composite parent) {
   final Display display = parent.getDisplay();
   toolBar = new ToolBar(parent, SWT.FLAT);
   Listener toolBarListener = new Listener() {
     public void handleEvent(Event event) {
       switch (event.type) {
       case SWT.Selection: {
         if (event.widget == playItem) {
           animate = true;
           playItem.setEnabled(!animate);
           pauseItem.setEnabled(animate);
         } else if (event.widget == pauseItem) {
           animate = false;
           playItem.setEnabled(!animate);
           pauseItem.setEnabled(animate);
         } else if (event.widget == backItem) {
           final ToolItem toolItem = (ToolItem) event.widget;
           final ToolBar toolBar = toolItem.getParent();
           Rectangle toolItemBounds = toolItem.getBounds();
           Point point = toolBar.toDisplay(new Point(
               toolItemBounds.x, toolItemBounds.y));
           backMenu.setLocation(point.x, point.y
               + toolItemBounds.height);
           backMenu.setVisible(true);
         }
       }
         break;
       }
     }
   };
   playItem = new ToolItem(toolBar, SWT.PUSH);
   playItem.setText(getResourceString("Play")); //$NON-NLS-1$
   playItem.setImage(loadImage(display, "play.gif")); //$NON-NLS-1$
   playItem.addListener(SWT.Selection, toolBarListener);
   pauseItem = new ToolItem(toolBar, SWT.PUSH);
   pauseItem.setText(getResourceString("Pause")); //$NON-NLS-1$
   pauseItem.setImage(loadImage(display, "pause.gif")); //$NON-NLS-1$
   pauseItem.addListener(SWT.Selection, toolBarListener);
   backItem = new ToolItem(toolBar, SWT.PUSH);
   backItem.setText(getResourceString("Background")); //$NON-NLS-1$
   backItem.addListener(SWT.Selection, toolBarListener);
   String[] names = new String[] { getResourceString("White"), //$NON-NLS-1$
       getResourceString("Black"), //$NON-NLS-1$
       getResourceString("Red"), //$NON-NLS-1$
       getResourceString("Green"), //$NON-NLS-1$
       getResourceString("Blue"), //$NON-NLS-1$
       getResourceString("CustomColor"), //$NON-NLS-1$
   };
   Color[] colors = new Color[] { display.getSystemColor(SWT.COLOR_WHITE),
       display.getSystemColor(SWT.COLOR_BLACK),
       display.getSystemColor(SWT.COLOR_RED),
       display.getSystemColor(SWT.COLOR_GREEN),
       display.getSystemColor(SWT.COLOR_BLUE), null, };
   backMenu = new Menu(parent);
   Listener listener = new Listener() {
     public void handleEvent(Event event) {
       MenuItem item = (MenuItem) event.widget;
       if (customMI == item) {
         ColorDialog dialog = new ColorDialog(parent.getShell());
         RGB rgb = dialog.open();
         if (rgb == null)
           return;
         if (customColor != null)
           customColor.dispose();
         customColor = new Color(display, rgb);
         if (customImage != null)
           customImage.dispose();
         customImage = createImage(display, customColor);
         item.setData(new Object[] { customColor, customImage });
         item.setImage(customImage);
       }
       tabBackground = (Object[]) item.getData();
       backItem.setImage((Image) tabBackground[1]);
       canvas.redraw();
     }
   };
   for (int i = 0; i < names.length; i++) {
     MenuItem item = new MenuItem(backMenu, SWT.NONE);
     item.setText(names[i]);
     item.addListener(SWT.Selection, listener);
     Image image = null;
     if (colors[i] != null) {
       image = createImage(display, colors[i]);
       images.addElement(image);
       item.setImage(image);
     } else {
       // custom menu item
       customMI = item;
     }
     item.setData(new Object[] { colors[i], image });
     if (tabBackground == null) {
       tabBackground = (Object[]) item.getData();
       backItem.setImage((Image) tabBackground[1]);
     }
   }
   dbItem = new ToolItem(toolBar, SWT.CHECK);
   dbItem.setText(getResourceString("DoubleBuffer")); //$NON-NLS-1$
   dbItem.setImage(loadImage(display, "db.gif")); //$NON-NLS-1$
   ToolItem separator = new ToolItem(toolBar, SWT.SEPARATOR);
   Composite comp = new Composite(toolBar, SWT.NONE);
   GridData data;
   GridLayout layout = new GridLayout(1, false);
   layout.verticalSpacing = 0;
   layout.marginWidth = layout.marginHeight = 3;
   comp.setLayout(layout);
   timerSpinner = new Spinner(comp, SWT.BORDER | SWT.WRAP);
   data = new GridData(SWT.CENTER, SWT.CENTER, false, false);
   timerSpinner.setLayoutData(data);
   Label label = new Label(comp, SWT.NONE);
   label.setText(getResourceString("Animation")); //$NON-NLS-1$
   data = new GridData(SWT.CENTER, SWT.CENTER, false, false);
   label.setLayoutData(data);
   timerSpinner.setMaximum(1000);
   timerSpinner.setSelection(TIMER);
   timerSpinner.setSelection(TIMER);
   separator.setControl(comp);
   separator.setWidth(comp.ruputeSize(SWT.DEFAULT, SWT.DEFAULT).x);
 }
 Image createImage(Display display, Color color) {
   Image image = new Image(display, 16, 16);
   GC gc = new GC(image);
   gc.setBackground(color);
   Rectangle rect = image.getBounds();
   gc.fillRectangle(rect);
   if (color.equals(display.getSystemColor(SWT.COLOR_BLACK))) {
     gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
   }
   gc.drawRectangle(rect.x, rect.y, rect.width - 1, rect.height - 1);
   gc.dispose();
   return image;
 }
 void createTabList(Composite parent) {
   tabList = new Tree(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL
       | SWT.BORDER);
   HashSet set = new HashSet();
   for (int i = 0; i < tabs.length; i++) {
     GraphicsTab tab = tabs[i];
     set.add(tab.getCategory());
   }
   for (Iterator iter = set.iterator(); iter.hasNext();) {
     String text = (String) iter.next();
     TreeItem item = new TreeItem(tabList, SWT.NONE);
     item.setText(text);
   }
   TreeItem[] items = tabList.getItems();
   for (int i = 0; i < items.length; i++) {
     TreeItem item = items[i];
     for (int j = 0; j < tabs.length; j++) {
       GraphicsTab tab = tabs[j];
       if (item.getText().equals(tab.getCategory())) {
         TreeItem item1 = new TreeItem(item, SWT.NONE);
         item1.setText(tab.getText());
         item1.setData(tab);
       }
     }
   }
   tabList.addListener(SWT.Selection, new Listener() {
     public void handleEvent(Event event) {
       TreeItem item = (TreeItem) event.item;
       if (item != null) {
         setTab((GraphicsTab) item.getData());
       }
     }
   });
 }
 GraphicsTab[] createTabs() {
   return new GraphicsTab[] { new LineTab(this), new StarPolyTab(this),
       tab = new IntroTab(this), new BlackHoleTab(this), };
 }
 /**
  * Disposes all resources created by the receiver.
  */
 public void dispose() {
   if (tabs != null) {
     for (int i = 0; i < tabs.length; i++) {
       GraphicsTab tab = tabs[i];
       tab.dispose();
     }
   }
   tabs = null;
   if (images != null) {
     for (int i = 0; i < images.size(); i++) {
       ((Image) images.elementAt(i)).dispose();
     }
   }
   images = null;
   if (customColor != null)
     customColor.dispose();
   customColor = null;
   if (customImage != null)
     customImage.dispose();
   customImage = null;
 }
 TreeItem findItemByData(TreeItem[] items, Object data) {
   for (int i = 0; i < items.length; i++) {
     TreeItem item = items[i];
     if (item.getData() == data)
       return item;
     item = findItemByData(item.getItems(), data);
     if (item != null)
       return item;
   }
   return null;
 }
 /**
  * Gets the current tab.
  */
 public GraphicsTab getTab() {
   return tab;
 }
 Listener getRedrawListener() {
   return redrawListener;
 }
 /**
  * Gets a string from the resource bundle. We don"t want to crash because of
  * a missing String. Returns the key if not found.
  */
 static String getResourceString(String key) {
     return "key";
 }
 static Image loadImage(Display display, Class clazz, String string) {
   InputStream stream = clazz.getResourceAsStream(string);
   if (stream == null)
     return null;
   Image image = null;
   try {
     image = new Image(display, stream);
   } catch (SWTException ex) {
   } finally {
     try {
       stream.close();
     } catch (IOException ex) {
     }
   }
   return image;
 }
 Image loadImage(Display display, String name) {
   Image image = loadImage(display, GraphicsExample.class, name);
   if (image != null)
     images.addElement(image);
   return image;
 }
 void paintBackground(GC gc, Rectangle rect) {
   gc.setBackground((Color) tabBackground[0]);
   gc.fillRectangle(rect);
 }
 /**
  * Redraws the current tab.
  */
 public void redraw() {
   canvas.redraw();
 }
 /**
  * Grabs input focus.
  */
 public void setFocus() {
   tabList.setFocus();
 }
 /**
  * Sets the current tab.
  */
 public void setTab(GraphicsTab tab) {
   this.tab = tab;
   Control[] children = controlPanel.getChildren();
   for (int i = 0; i < children.length; i++) {
     Control control = children[i];
     control.dispose();
   }
   if (tab != null) {
     tab.createControlPanel(controlPanel);
     animate = tab.isAnimated();
   }
   playItem.setEnabled(!animate);
   pauseItem.setEnabled(animate);
   GridData data = (GridData) controlPanel.getLayoutData();
   children = controlPanel.getChildren();
   data.exclude = children.length == 0;
   controlPanel.setVisible(!data.exclude);
   if (data.exclude) {
     tabPanel.layout();
   } else {
     tabPanel.layout(children);
   }
   if (tab != null) {
     TreeItem[] selection = tabList.getSelection();
     if (selection.length == 0 || selection[0].getData() != tab) {
       TreeItem item = findItemByData(tabList.getItems(), tab);
       if (item != null)
         tabList.setSelection(new TreeItem[] { item });
     }
   }
   canvas.redraw();
 }
 void startAnimationTimer() {
   final Display display = Display.getCurrent();
   display.timerExec(timerSpinner.getSelection(), new Runnable() {
     public void run() {
       if (canvas.isDisposed())
         return;
       if (animate) {
         GraphicsTab tab = getTab();
         if (tab != null && tab.isAnimated()) {
           Rectangle rect = canvas.getClientArea();
           tab.next(rect.width, rect.height);
           canvas.redraw();
           canvas.update();
         }
       }
       display.timerExec(timerSpinner.getSelection(), this);
     }
   });
 }
 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText(getResourceString("SWTGraphics")); //$NON-NLS-1$
   final GraphicsExample example = new GraphicsExample(shell);
   shell.addListener(SWT.Close, new Listener() {
     public void handleEvent(Event event) {
       example.dispose();
     }
   });
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
 }

} /*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/

abstract class GraphicsTab {

 GraphicsExample example;
 public GraphicsTab(GraphicsExample example) {
   this.example = example;
 }
 /**
  * Creates the widgets used to control the drawing.
  */
 public void createControlPanel(Composite parent) {
 }
 /**
  * Disposes resources created by the receiver.
  */
 public void dispose() {
 }
 /**
  * Answer the receiver"s name.
  */
 public abstract String getText();
 /**
  * Answer the receiver"s category.
  */
 public String getCategory() {
   return GraphicsExample.getResourceString("Misc"); //$NON-NLS-1$
 }
 /**
  * Answer whether the receiver is animated or not.
  */
 public boolean isAnimated() {
   return false;
 }
 /**
  * Advance the animation.
  */
 public void next(int width, int height) {
 }
 /**
  * Paint the receiver into the specified GC.
  */
 public void paint(GC gc, int width, int height) {
 }

} /*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/

class LineTab extends GraphicsTab {

 public LineTab(GraphicsExample example) {
   super(example);
 }
 public String getText() {
   return GraphicsExample.getResourceString("Line"); //$NON-NLS-1$
 }
 public void paint(GC gc, int width, int height) {
   gc.drawLine(0, 0, width, height);
   gc.drawLine(width, 0, 0, height);
 }

} /*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/

class StarPolyTab extends GraphicsTab {

 int[] radial;
 static final int POINTS = 11;
 Combo fillRuleCb;
 public StarPolyTab(GraphicsExample example) {
   super(example);
   radial = new int[POINTS * 2];
 }
 public void createControlPanel(Composite parent) {
   new Label(parent, SWT.NONE).setText(GraphicsExample
       .getResourceString("FillRule")); //$NON-NLS-1$
   fillRuleCb = new Combo(parent, SWT.DROP_DOWN);
   fillRuleCb.add("FILL_EVEN_ODD");
   fillRuleCb.add("FILL_WINDING");
   fillRuleCb.select(0);
   fillRuleCb.addListener(SWT.Selection, example.getRedrawListener());
 }
 public String getCategory() {
   return GraphicsExample.getResourceString("Polygons"); //$NON-NLS-1$
 }
 public String getText() {
   return GraphicsExample.getResourceString("StarPolygon"); //$NON-NLS-1$
 }
 public void paint(GC gc, int width, int height) {
   int centerX = width / 2;
   int centerY = height / 2;
   int pos = 0;
   for (int i = 0; i < POINTS; ++i) {
     double r = Math.PI * 2 * pos / POINTS;
     radial[i * 2] = (int) ((1 + Math.cos(r)) * centerX);
     radial[i * 2 + 1] = (int) ((1 + Math.sin(r)) * centerY);
     pos = (pos + POINTS / 2) % POINTS;
   }
   Display display = Display.getCurrent();
   gc.setFillRule(fillRuleCb.getSelectionIndex() != 0 ? SWT.FILL_WINDING
       : SWT.FILL_EVEN_ODD);
   gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
   gc.fillPolygon(radial);
   gc.drawPolygon(radial);
 }

} /*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/

class BlackHoleTab extends GraphicsTab {

 int size = 1;
 public BlackHoleTab(GraphicsExample example) {
   super(example);
 }
 public String getText() {
   return GraphicsExample.getResourceString("BlackHole"); //$NON-NLS-1$
 }
 public boolean isAnimated() {
   return true;
 }
 public void next(int width, int height) {
   if (size > width * 3 / 2)
     size = 0;
   else
     size += 10;
 }
 public void paint(GC gc, int width, int height) {
   Display display = Display.getCurrent();
   gc.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
   gc.fillOval((width - size) / 2, (height - size) / 2, size, size);
 }

} /*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
* 
* Contributors: IBM Corporation - initial API and implementation
******************************************************************************/

class IntroTab extends GraphicsTab {

 Font font;
 Image image;
 Random random = new Random();
 float x, y;
 float incX = 10.0f;
 float incY = 5.0f;
 int textWidth, textHeight;
 String text = "SWT";
 public IntroTab(GraphicsExample example) {
   super(example);
 }
 public void dispose() {
   if (image != null)
     image.dispose();
   image = null;
   if (font != null)
     font.dispose();
   font = null;
 }
 public String getCategory() {
   return GraphicsExample.getResourceString("Introduction"); //$NON-NLS-1$
 }
 public String getText() {
   return GraphicsExample.getResourceString("SWT"); //$NON-NLS-1$
 }
 public boolean isAnimated() {
   return true;
 }
 public void next(int width, int height) {
   x += incX;
   y += incY;
   float random = (float) Math.random();
   if (x + textWidth > width) {
     x = width - textWidth;
     incX = random * -width / 16 - 1;
   }
   if (x < 0) {
     x = 0;
     incX = random * width / 16 + 1;
   }
   if (y + textHeight > height) {
     y = (height - textHeight) - 2;
     incY = random * -height / 16 - 1;
   }
   if (y < 0) {
     y = 0;
     incY = random * height / 16 + 1;
   }
 }
 public void paint(GC gc, int width, int height) {
   if (!example.checkAdvancedGraphics())
     return;
   Display display = Display.getCurrent();
   if (image == null) {
     image = example.loadImage(Display.getCurrent(), "irmaos.jpg");
     Rectangle rect = image.getBounds();
     FontData fd = display.getSystemFont().getFontData()[0];
     font = new Font(display, fd.getName(), rect.height / 4, SWT.BOLD);
     gc.setFont(font);
     Point size = gc.stringExtent(text);
     textWidth = size.x;
     textHeight = size.y;
   }
   Path path = new Path(display);
   path.addString(text, x, y, font);
   gc.setClipping(path);
   Rectangle rect = image.getBounds();
   gc.drawImage(image, 0, 0, rect.width, rect.height, 0, 0, width, height);
   gc.setClipping((Rectangle) null);
   gc.setForeground(display.getSystemColor(SWT.COLOR_BLUE));
   gc.drawPath(path);
 }

}


 </source>
   
  
 
  



SWT OpenGL snippet: draw a square

   <source lang="java">

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     Sebastian Davids - initial implementation
*     IBM Corporation
*******************************************************************************/

package org.eclipse.swt.snippets; /*

* SWT OpenGL snippet: draw a square
* 
* This snippet requires the experimental org.eclipse.swt.opengl plugin, which
* is not included in swt by default. For information on this plugin see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/opengl/opengl.html
* 
* For a list of all SWT example snippets see
* http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-swt-home/dev.html#snippets
*/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.opengl.*; import org.eclipse.swt.widgets.*; public class Snippet174 {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText("OpenGL in SWT");
   shell.setLayout(new FillLayout());
   final Canvas canvas = new Canvas(shell, SWT.NO_BACKGROUND);
   canvas.addControlListener(new ControlAdapter() {
     public void controlResized(ControlEvent e) {
       resize(canvas);
     }
   });
   final GLContext context = init(canvas);
   shell.addDisposeListener(new DisposeListener() {
     public void widgetDisposed(DisposeEvent e) {
       context.dispose();
     }
   });
   new Runnable() {
     public void run() {
       if (canvas.isDisposed())
         return;
       render();
       context.swapBuffers();
       canvas.getDisplay().timerExec(50, this);
     }
   }.run();
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
 }
 static GLContext init(Canvas canvas) {
   GLContext context = new GLContext(canvas);
   context.setCurrent();
   resize(canvas);
   GL.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
   GL.glColor3f(0.0f, 0.0f, 0.0f);
   GL.glClearDepth(1.0f);
   GL.glEnable(GL.GL_DEPTH_TEST);
   GL.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
   return context;
 }
 static void render() {
   GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
   GL.glLoadIdentity();
   GL.glTranslatef(0.0f, 0.0f, -6.0f);
   GL.glBegin(GL.GL_QUADS);
   GL.glVertex3f(-1.0f, 1.0f, 0.0f);
   GL.glVertex3f(1.0f, 1.0f, 0.0f);
   GL.glVertex3f(1.0f, -1.0f, 0.0f);
   GL.glVertex3f(-1.0f, -1.0f, 0.0f);
   GL.glEnd();
 }
 static void resize(Canvas canvas) {
   Rectangle rect = canvas.getClientArea();
   int width = rect.width;
   int height = Math.max(rect.height, 1);
   GL.glViewport(0, 0, width, height);
   GL.glMatrixMode(GL.GL_PROJECTION);
   GL.glLoadIdentity();
   float aspect = (float) width / (float) height;
   GLU.gluPerspective(45.0f, aspect, 0.5f, 400.0f);
   GL.glMatrixMode(GL.GL_MODELVIEW);
   GL.glLoadIdentity();
 }

}


 </source>
   
  
 
  



SWT Paint Example

   <source lang="java">

import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.accessibility.*; import java.io.*; import java.text.*; import java.util.*; public class PaintExample {

 private Composite mainComposite;
 private Canvas activeForegroundColorCanvas;
 private Canvas activeBackgroundColorCanvas;
 private Color paintColorBlack, paintColorWhite; // alias for paintColors[0] and [1]
 private Color[] paintColors;
 private Font paintDefaultFont; // do not free
 private static final int numPaletteRows = 3;
 private static final int numPaletteCols = 50;
 private ToolSettings toolSettings; // current active settings
 private PaintSurface paintSurface; // paint surface for drawing
 static final int Pencil_tool = 0;
 static final int Airbrush_tool = 1;
 static final int Line_tool = 2;
 static final int PolyLine_tool = 3;
 static final int Rectangle_tool = 4;
 static final int RoundedRectangle_tool = 5;
 static final int Ellipse_tool = 6;
 static final int Text_tool = 7;
 static final int None_fill = 8;
 static final int Outline_fill = 9;
 static final int Solid_fill = 10;
 static final int Solid_linestyle = 11;
 static final int Dash_linestyle = 12;
 static final int Dot_linestyle = 13;
 static final int DashDot_linestyle = 14;
 static final int Font_options = 15;
 
 static final int Default_tool = Pencil_tool;
 static final int Default_fill = None_fill;
 static final int Default_linestyle = Solid_linestyle;
 
 public static final Tool[] tools = {
   new Tool(Pencil_tool, "Pencil", "tool", SWT.RADIO),
   new Tool(Airbrush_tool, "Airbrush", "tool", SWT.RADIO),
   new Tool(Line_tool, "Line", "tool", SWT.RADIO),
   new Tool(PolyLine_tool, "PolyLine", "tool", SWT.RADIO),
   new Tool(Rectangle_tool, "Rectangle", "tool", SWT.RADIO),
   new Tool(RoundedRectangle_tool, "RoundedRectangle", "tool", SWT.RADIO),
   new Tool(Ellipse_tool, "Ellipse", "tool", SWT.RADIO),
   new Tool(Text_tool, "Text", "tool", SWT.RADIO),
   new Tool(None_fill, "None", "fill", SWT.RADIO, new Integer(ToolSettings.ftNone)),
   new Tool(Outline_fill, "Outline", "fill", SWT.RADIO, new Integer(ToolSettings.ftOutline)),
   new Tool(Solid_fill, "Solid", "fill", SWT.RADIO, new Integer(ToolSettings.ftSolid)),
   new Tool(Solid_linestyle, "Solid", "linestyle", SWT.RADIO, new Integer(SWT.LINE_SOLID)),
   new Tool(Dash_linestyle, "Dash", "linestyle", SWT.RADIO, new Integer(SWT.LINE_DASH)),
   new Tool(Dot_linestyle, "Dot", "linestyle", SWT.RADIO, new Integer(SWT.LINE_DOT)),
   new Tool(DashDot_linestyle, "DashDot", "linestyle", SWT.RADIO, new Integer(SWT.LINE_DASHDOT)),
   new Tool(Font_options, "Font", "options", SWT.PUSH)
 };
 /**
  * Creates an instance of a PaintExample embedded inside
  * the supplied parent Composite.
  * 
  * @param parent the container of the example
  */
 public PaintExample(Composite parent) {
   mainComposite = parent;
   initResources();
   initActions();
   init();
 }
 /**
  * Invokes as a standalone program.
  */
 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setText(getResourceString("window.title"));
   shell.setLayout(new GridLayout());
   PaintExample instance = new PaintExample(shell);
   instance.createToolBar(shell);
   Composite composite = new Composite(shell, SWT.NONE);
   composite.setLayout(new FillLayout());
   composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
   instance.createGUI(composite);
   instance.setDefaults();
   setShellSize(display, shell);
   shell.open();
   while (! shell.isDisposed()) {
     if (! display.readAndDispatch()) display.sleep();
   }
   instance.dispose();
 }
 
 /**
  * Creates the toolbar.
  * Note: Only called by standalone.
  */
 private void createToolBar(Composite parent) {
   ToolBar toolbar = new ToolBar (parent, SWT.NONE);
   String group = null;
   for (int i = 0; i < tools.length; i++) {
     Tool tool = tools[i];
     if (group != null && !tool.group.equals(group)) {
       new ToolItem (toolbar, SWT.SEPARATOR);
     }
     group = tool.group;
     ToolItem item = addToolItem(toolbar, tool);
     if (i == Default_tool || i == Default_fill || i == Default_linestyle) item.setSelection(true);
   }
 }
 /**
  * Adds a tool item to the toolbar.
  * Note: Only called by standalone.
  */
 private ToolItem addToolItem(final ToolBar toolbar, final Tool tool) {
   final String id = tool.group + "." + tool.name;
   ToolItem item = new ToolItem (toolbar, tool.type);
   item.setText (getResourceString(id + ".label"));
   item.setToolTipText(getResourceString(id + ".tooltip"));
   item.setImage(tool.image);
   item.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       tool.action.run();
     }
   });
   final int childID = toolbar.indexOf(item);
   toolbar.getAccessible().addAccessibleListener(new AccessibleAdapter() {
     public void getName(org.eclipse.swt.accessibility.AccessibleEvent e) {
       if (e.childID == childID) {
         e.result = getResourceString(id + ".description");
       }
     }
   });
   return item;
 }
 /**
  * Sets the default tool item states.
  */
 public void setDefaults() {
   setPaintTool(Default_tool);
   setFillType(Default_fill);
   setLineStyle(Default_linestyle);
   setForegroundColor(paintColorBlack);
   setBackgroundColor(paintColorWhite);
 }
 /**
  * Creates the GUI.
  */
 public void createGUI(Composite parent) {
   GridLayout gridLayout;
   GridData gridData;
   /*** Create principal GUI layout elements ***/    
   Composite displayArea = new Composite(parent, SWT.NONE);
   gridLayout = new GridLayout();
   gridLayout.numColumns = 1;
   displayArea.setLayout(gridLayout);
   // Creating these elements here avoids the need to instantiate the GUI elements
   // in strict layout order.  The natural layout ordering is an artifact of using
   // SWT layouts, but unfortunately it is not the same order as that required to
   // instantiate all of the non-GUI application elements to satisfy referential
   // dependencies.  It is possible to reorder the initialization to some extent, but
   // this can be very tedious.
   
   // paint canvas
   final Canvas paintCanvas = new Canvas(displayArea, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL |
     SWT.NO_REDRAW_RESIZE | SWT.NO_BACKGROUND);
   gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL);
   paintCanvas.setLayoutData(gridData);
   paintCanvas.setBackground(paintColorWhite);
   
   // color selector frame
   final Composite colorFrame = new Composite(displayArea, SWT.NONE);
   gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
   colorFrame.setLayoutData(gridData);
   // tool settings frame
   final Composite toolSettingsFrame = new Composite(displayArea, SWT.NONE);
   gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
   toolSettingsFrame.setLayoutData(gridData);
   // status text
   final Text statusText = new Text(displayArea, SWT.BORDER | SWT.SINGLE | SWT.READ_ONLY);
   gridData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
   statusText.setLayoutData(gridData);
   /*** Create the remaining application elements inside the principal GUI layout elements ***/  
   // paintSurface
   paintSurface = new PaintSurface(paintCanvas, statusText, paintColorWhite);
   // finish initializing the tool data
   tools[Pencil_tool].data = new PencilTool(toolSettings, paintSurface);
   tools[Airbrush_tool].data = new AirbrushTool(toolSettings, paintSurface);
   tools[Line_tool].data = new LineTool(toolSettings, paintSurface);
   tools[PolyLine_tool].data = new PolyLineTool(toolSettings, paintSurface);
   tools[Rectangle_tool].data = new RectangleTool(toolSettings, paintSurface);
   tools[RoundedRectangle_tool].data = new RoundedRectangleTool(toolSettings, paintSurface);
   tools[Ellipse_tool].data = new EllipseTool(toolSettings, paintSurface);
   tools[Text_tool].data = new TextTool(toolSettings, paintSurface);
   // colorFrame    
   gridLayout = new GridLayout();
   gridLayout.numColumns = 3;
   gridLayout.marginHeight = 0;
   gridLayout.marginWidth = 0;
   colorFrame.setLayout(gridLayout);
   // activeForegroundColorCanvas, activeBackgroundColorCanvas
   activeForegroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
   gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
   gridData.heightHint = 24;
   gridData.widthHint = 24;
   activeForegroundColorCanvas.setLayoutData(gridData);
   activeBackgroundColorCanvas = new Canvas(colorFrame, SWT.BORDER);
   gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
   gridData.heightHint = 24;
   gridData.widthHint = 24;
   activeBackgroundColorCanvas.setLayoutData(gridData);
   // paletteCanvas
   final Canvas paletteCanvas = new Canvas(colorFrame, SWT.BORDER | SWT.NO_BACKGROUND);
   gridData = new GridData(GridData.FILL_HORIZONTAL);
   gridData.heightHint = 24;
   paletteCanvas.setLayoutData(gridData);
   paletteCanvas.addListener(SWT.MouseDown, new Listener() {
     public void handleEvent(Event e) {
       Rectangle bounds = paletteCanvas.getClientArea();
       Color color = getColorAt(bounds, e.x, e.y);        
         
       if (e.button == 1) setForegroundColor(color);
       else setBackgroundColor(color);
     }
     private Color getColorAt(Rectangle bounds, int x, int y) {
       if (bounds.height <= 1 && bounds.width <= 1) return paintColorWhite;
       final int row = (y - bounds.y) * numPaletteRows / bounds.height;
       final int col = (x - bounds.x) * numPaletteCols / bounds.width;
       return paintColors[Math.min(Math.max(row * numPaletteCols + col, 0), paintColors.length - 1)];
     }
   });
   Listener refreshListener = new Listener() {
     public void handleEvent(Event e) {
       if (e.gc == null) return;
       Rectangle bounds = paletteCanvas.getClientArea();
       for (int row = 0; row < numPaletteRows; ++row) {
         for (int col = 0; col < numPaletteCols; ++col) {
           final int x = bounds.width * col / numPaletteCols;
           final int y = bounds.height * row / numPaletteRows;
           final int width = Math.max(bounds.width * (col + 1) / numPaletteCols - x, 1);
           final int height = Math.max(bounds.height * (row + 1) / numPaletteRows - y, 1);
           e.gc.setBackground(paintColors[row * numPaletteCols + col]);
           e.gc.fillRectangle(bounds.x + x, bounds.y + y, width, height);
         }
       }
     }
   };
   paletteCanvas.addListener(SWT.Resize, refreshListener);
   paletteCanvas.addListener(SWT.Paint, refreshListener);
   //paletteCanvas.redraw();
   
   // toolSettingsFrame
   gridLayout = new GridLayout();
   gridLayout.numColumns = 4;
   gridLayout.marginHeight = 0;
   gridLayout.marginWidth = 0;
   toolSettingsFrame.setLayout(gridLayout);
   Label label = new Label(toolSettingsFrame, SWT.NONE);
   label.setText(getResourceString("settings.AirbrushRadius.text"));
   final Scale airbrushRadiusScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
   airbrushRadiusScale.setMinimum(5);
   airbrushRadiusScale.setMaximum(50);
   airbrushRadiusScale.setSelection(toolSettings.airbrushRadius);
   airbrushRadiusScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
   airbrushRadiusScale.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       toolSettings.airbrushRadius = airbrushRadiusScale.getSelection();
       updateToolSettings();
     }
   });
   label = new Label(toolSettingsFrame, SWT.NONE);
   label.setText(getResourceString("settings.AirbrushIntensity.text"));
   final Scale airbrushIntensityScale = new Scale(toolSettingsFrame, SWT.HORIZONTAL);
   airbrushIntensityScale.setMinimum(1);
   airbrushIntensityScale.setMaximum(100);
   airbrushIntensityScale.setSelection(toolSettings.airbrushIntensity);
   airbrushIntensityScale.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
   airbrushIntensityScale.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent e) {
       toolSettings.airbrushIntensity = airbrushIntensityScale.getSelection();
       updateToolSettings();
     }
   });
 }
   
 /**
  * Disposes of all resources associated with a particular
  * instance of the PaintExample.
  */  
 public void dispose() {
   if (paintSurface != null) paintSurface.dispose();    
   if (paintColors != null) {
     for (int i = 0; i < paintColors.length; ++i) {
       final Color color = paintColors[i];
       if (color != null) color.dispose();
     }
   }
   paintDefaultFont = null;
   paintColors = null;
   paintSurface = null;
   freeResources();
 }
 /**
  * Frees the resource bundle resources.
  */
 public void freeResources() {
   for (int i = 0; i < tools.length; ++i) {
     Tool tool = tools[i];
     final Image image = tool.image;
     if (image != null) image.dispose();
     tool.image = null;
   }
 }
 
 /**
  * Returns the Display.
  * 
  * @return the display we"re using
  */
 public Display getDisplay() {
   return mainComposite.getDisplay();
 }
 
 /**
  * Gets a string from the resource bundle.
  * We don"t want to crash because of a missing String.
  * Returns the key if not found.
  */
 public static String getResourceString(String key) {
     return key;
 }
 /**
  * Gets a string from the resource bundle and binds it
  * with the given arguments. If the key is not found,
  * return the key.
  */
 public static String getResourceString(String key, Object[] args) {
   try {
     return MessageFormat.format(getResourceString(key), args);
   } catch (MissingResourceException e) {
     return key;
   } catch (NullPointerException e) {
     return "!" + key + "!";
   }
 }
 /**
  * Initialize colors, fonts, and tool settings.
  */
 private void init() {
   Display display = mainComposite.getDisplay();
   
   paintColorWhite = new Color(display, 255, 255, 255);
   paintColorBlack = new Color(display, 0, 0, 0);
   
   paintDefaultFont = display.getSystemFont();
   paintColors = new Color[numPaletteCols * numPaletteRows];
   paintColors[0] = paintColorBlack;
   paintColors[1] = paintColorWhite;
   for (int i = 2; i < paintColors.length; i++) {
     paintColors[i] = new Color(display,
       ((i*7)%255),((i*23)%255), ((i*51)%255));
   }
   toolSettings = new ToolSettings();
   toolSettings.rumonForegroundColor = paintColorBlack;
   toolSettings.rumonBackgroundColor = paintColorWhite;
   toolSettings.rumonFont = paintDefaultFont;
 }
 /**
  * Sets the action field of the tools
  */
 private void initActions() {
   for (int i = 0; i < tools.length; ++i) {
     final Tool tool = tools[i];
     String group = tool.group;
     if (group.equals("tool")) {
       tool.action = new Runnable() {
         public void run() {
           setPaintTool(tool.id);
         }
       };
     } else if (group.equals("fill")) {
       tool.action = new Runnable() {
         public void run() {
           setFillType(tool.id);
         }
       };
     } else if (group.equals("linestyle")) {
       tool.action = new Runnable() {
         public void run() {
           setLineStyle(tool.id);
         }
       };
     } else if (group.equals("options")) {
       tool.action = new Runnable() {
         public void run() {
           FontDialog fontDialog = new FontDialog(paintSurface.getShell(), SWT.PRIMARY_MODAL);
           FontData[] fontDatum = toolSettings.rumonFont.getFontData();
           if (fontDatum != null && fontDatum.length > 0) {
             fontDialog.setFontList(fontDatum);
           }
           fontDialog.setText(getResourceString("options.Font.dialog.title"));
           paintSurface.hideRubberband();
           FontData fontData = fontDialog.open();
           paintSurface.showRubberband();
           if (fontData != null) {
             try {
               Font font = new Font(mainComposite.getDisplay(), fontData);
               toolSettings.rumonFont = font;
               updateToolSettings();
             } catch (SWTException ex) {
             }
           }
         }
       };
     }
   }
 }
 /**
  * Loads the image resources.
  */
 public void initResources() {
   final Class clazz = PaintExample.class;
     try {
       for (int i = 0; i < tools.length; ++i) {
         Tool tool = tools[i];
         String id = tool.group + "." + tool.name;
         InputStream sourceStream = clazz.getResourceAsStream(getResourceString(id + ".image"));
         ImageData source = new ImageData(sourceStream);
         ImageData mask = source.getTransparencyMask();
         tool.image = new Image(null, source, mask);
         try {
           sourceStream.close();
         } catch (IOException e) {
           e.printStackTrace();
         }
       }
       return;
     } catch (Throwable t) {
     }
   String error = "Unable to load resources";
   freeResources();
   throw new RuntimeException(error);
 }
 /**
  * Grabs input focus.
  */
 public void setFocus() {
   mainComposite.setFocus();
 }
 
 /**
  * Sets the tool foreground color.
  * 
  * @param color the new color to use
  */
 public void setForegroundColor(Color color) {
   if (activeForegroundColorCanvas != null)
     activeForegroundColorCanvas.setBackground(color);
   toolSettings.rumonForegroundColor = color;
   updateToolSettings();
 }
 /**
  * Set the tool background color.
  * 
  * @param color the new color to use
  */
 public void setBackgroundColor(Color color) {
   if (activeBackgroundColorCanvas != null)
     activeBackgroundColorCanvas.setBackground(color);
   toolSettings.rumonBackgroundColor = color;
   updateToolSettings();
 }
 /**
  * Selects a tool given its ID.
  */
 public void setPaintTool(int id) {
   PaintTool paintTool = (PaintTool) tools[id].data;
   paintSurface.setPaintSession(paintTool);
   updateToolSettings();
 }
 
 /**
  * Selects a filltype given its ID.
  */
 public void setFillType(int id) {
   Integer fillType = (Integer) tools[id].data;
   toolSettings.rumonFillType = fillType.intValue();
   updateToolSettings();    
 }
 /**
  * Selects line type given its ID.
  */
 public void setLineStyle(int id) {
   Integer lineType = (Integer) tools[id].data;
   toolSettings.rumonLineStyle = lineType.intValue();
   updateToolSettings();    
 }
 /**
  * Sets the size of the shell to it"s "packed" size,
  * unless that makes it bigger than the display,
  * in which case set it to 9/10 of display size.
  */
 private static void setShellSize (Display display, Shell shell) {
   Rectangle bounds = display.getBounds();
   Point size = shell.ruputeSize (SWT.DEFAULT, SWT.DEFAULT);
   if (size.x > bounds.width) size.x = bounds.width * 9 / 10;
   if (size.y > bounds.height) size.y = bounds.height * 9 / 10;
   shell.setSize (size);
 }
 /**
  * Notifies the tool that its settings have changed.
  */
 private void updateToolSettings() {
   final PaintTool activePaintTool = paintSurface.getPaintTool();
   if (activePaintTool == null) return;
   
   activePaintTool.endSession();
   activePaintTool.set(toolSettings);
   activePaintTool.beginSession();
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* Tool Settings objects group tool-related configuration information.
*/

class ToolSettings {

 public static final int ftNone = 0, ftOutline = 1, ftSolid = 2;
 /**
  * commonForegroundColor: current tool foreground colour
  */
 public Color commonForegroundColor;
 /**
  * commonBackgroundColor: current tool background colour
  */
 public Color commonBackgroundColor;
 /**
  * commonFont: current font
  */
 public Font commonFont;
 /**
  * commonFillType: current fill type
*

One of ftNone, ftOutline, ftSolid.

  */
 public int commonFillType = ftNone;
 /**
  * commonLineStyle: current line type
  */
 public int commonLineStyle = SWT.LINE_SOLID;
 
 /**
  * airbrushRadius: coverage radius in pixels
  */
 public int airbrushRadius = 10;
 
 /**
  * airbrushIntensity: average surface area coverage in region defined by radius per "jot"
  */
 public int airbrushIntensity = 30;
 
 /**
  * roundedRectangleCornerDiameter: the diameter of curvature of corners in a rounded rectangle
  */
 public int roundedRectangleCornerDiameter = 16;

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

class Tool {

 public int id;
 public String name;
 public String group;
 public int type;
 public Runnable action;
 public Image image = null;
 public Object data;
 
 public Tool(int id, String name, String group, int type) {
   super();
   this.id = id;
   this.name = name;
   this.group = group;
   this.type = type;
 }
 public Tool(int id, String name, String group, int type, Object data) {
   this(id, name, group, type);
   this.data = data;
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A text drawing tool.
*/

class TextTool extends BasicPaintSession implements PaintTool {

 private ToolSettings settings;
 private String drawText = PaintExample.getResourceString("tool.Text.settings.defaulttext");
 /**
  * Constructs a PaintTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public TextTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 
 /**
  * Returns name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Text.label");
 }
 
 /**
  * Activates the tool.
  */
 public void beginSession() {
   getPaintSurface().setStatusMessage(PaintExample.getResourceString(
     "session.Text.message"));
 }
 
 /**
  * Deactivates the tool.
    */
 public void endSession() {
   getPaintSurface().clearRubberbandSelection();
 }
 
 /**
  * Aborts the current operation.
  */
 public void resetSession() {
   getPaintSurface().clearRubberbandSelection();
 }
 
 /**
  * Handles a mouseDown event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDown(MouseEvent event) {
   if (event.button == 1) {
     // draw with left mouse button
     getPaintSurface().rumitRubberbandSelection();
   } else {
     // set text with right mouse button
     getPaintSurface().clearRubberbandSelection();
     Shell shell = getPaintSurface().getShell();
     final Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
     dialog.setText(PaintExample.getResourceString("tool.Text.dialog.title"));
     dialog.setLayout(new GridLayout());
     Label label = new Label(dialog, SWT.NONE);
     label.setText(PaintExample.getResourceString("tool.Text.dialog.message"));
     label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
     final Text field = new Text(dialog, SWT.SINGLE | SWT.BORDER);
     field.setText(drawText);
     field.selectAll();
     field.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
     Composite buttons = new Composite(dialog, SWT.NONE);
     GridLayout layout = new GridLayout(2, true);
     layout.marginWidth = 0;
     buttons.setLayout(layout);
     buttons.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false));
     Button ok = new Button(buttons, SWT.PUSH);
     ok.setText(PaintExample.getResourceString("OK"));
     ok.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false));
     ok.addSelectionListener(new SelectionAdapter() {
       public void widgetSelected(SelectionEvent e) {
         drawText = field.getText();
         dialog.dispose();
       }
     });
     Button cancel = new Button(buttons, SWT.PUSH);
     cancel.setText(PaintExample.getResourceString("Cancel"));
     cancel.addSelectionListener(new SelectionAdapter() {
       public void widgetSelected(SelectionEvent e) {
         dialog.dispose();
       }
     });
     dialog.setDefaultButton(ok);
     dialog.pack();
     dialog.open();
     Display display = dialog.getDisplay();
     while (! shell.isDisposed() && ! dialog.isDisposed()) {
       if (! display.readAndDispatch()) display.sleep();
     }
   }  
 }
 /**
  * Handles a mouseDoubleClick event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDoubleClick(MouseEvent event) {
 }
 /**
  * Handles a mouseUp event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseUp(MouseEvent event) {
 }
 
 /**
  * Handles a mouseMove event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseMove(MouseEvent event) {
   final PaintSurface ps = getPaintSurface();
   ps.setStatusCoord(ps.getCurrentPosition());
   ps.clearRubberbandSelection();
   ps.addRubberbandSelection(
     new TextFigure(settings.rumonForegroundColor, settings.rumonFont,
       drawText, event.x, event.y));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Rectangle object
*/

class TextFigure extends Figure {

 private Color  color;
 private Font   font;
 private String text;
 private int x, y;
 /**
  * Constructs a TextFigure
  * 
  * @param color the color for this object
  * @param font  the font for this object
  * @param text  the text to draw, tab and new-line expansion is performed
  * @param x     the virtual X coordinate of the top-left corner of the text bounding box
  * @param y     the virtual Y coordinate of the top-left corner of the text bounding box
  */
 public TextFigure(Color color, Font font, String text, int x, int y) {
   this.color = color; this.font = font; this.text = text; this.x = x; this.y = y;
 }
 public void draw(FigureDrawContext fdc) {
   Point p = fdc.toClientPoint(x, y);
   fdc.gc.setFont(font);
   fdc.gc.setForeground(color);
   fdc.gc.drawText(text, p.x, p.y, true);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   Font oldFont = fdc.gc.getFont();
   fdc.gc.setFont(font);
   Point textExtent = fdc.gc.textExtent(text);
   fdc.gc.setFont(oldFont);
   region.add(fdc.toClientRectangle(x, y, x + textExtent.x, y + textExtent.y));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D SolidRectangle object
*/

class SolidRoundedRectangleFigure extends Figure {

 private Color color;
 private int x1, y1, x2, y2, diameter;
 /**
  * Constructs a SolidRectangle
  * These objects are defined by any two diametrically opposing corners.
  * 
  * @param color the color for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  * @param diameter the diameter of curvature of all four corners
  */
 public SolidRoundedRectangleFigure(Color color, int x1, int y1, int x2, int y2, int diameter) {
   this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
   this.diameter = diameter;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setBackground(color);
   fdc.gc.fillRoundRectangle(r.x, r.y, r.width, r.height, diameter, diameter);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D SolidRectangle object
*/

class SolidRectangleFigure extends Figure {

 private Color color;
 private int x1, y1, x2, y2;
 /**
  * Constructs a SolidRectangle
  * These objects are defined by any two diametrically opposing corners.
  * 
  * @param color the color for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  */
 public SolidRectangleFigure(Color color, int x1, int y1, int x2, int y2) {
   this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setBackground(color);
   fdc.gc.fillRectangle(r.x, r.y, r.width, r.height);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Line object
*/

class SolidPolygonFigure extends Figure {

 private Color color;
 private int[] points;
 /**
  * Constructs a SolidPolygon
  * These objects are defined by a sequence of vertices.
  * 
  * @param color the color for this object
  * @param vertices the array of vertices making up the polygon
  * @param numPoint the number of valid points in the array (n >= 3)
  */
 public SolidPolygonFigure(Color color, Point[] vertices, int numPoints) {
   this.color = color;
   this.points = new int[numPoints * 2];
   for (int i = 0; i < numPoints; ++i) {
     points[i * 2] = vertices[i].x;
     points[i * 2 + 1] = vertices[i].y;
   }
 }
 public void draw(FigureDrawContext fdc) {
   int[] drawPoints = new int[points.length];
   for (int i = 0; i < points.length; i += 2) {
     drawPoints[i] = points[i] * fdc.xScale - fdc.xOffset;
     drawPoints[i + 1] = points[i + 1] * fdc.yScale - fdc.yOffset;
   }
   fdc.gc.setBackground(color);
   fdc.gc.fillPolygon(drawPoints);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   int xmin = Integer.MAX_VALUE, ymin = Integer.MAX_VALUE;
   int xmax = Integer.MIN_VALUE, ymax = Integer.MIN_VALUE;
   for (int i = 0; i < points.length; i += 2) {
     if (points[i] < xmin) xmin = points[i];
     if (points[i] > xmax) xmax = points[i];
     if (points[i+1] < ymin) ymin = points[i+1];
     if (points[i+1] > ymax) ymax = points[i+1];
   }    
   region.add(fdc.toClientRectangle(xmin, ymin, xmax, ymax));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Solid Ellipse object
*/

class SolidEllipseFigure extends Figure {

 private Color color;
 private int x1, y1, x2, y2;
 /**
  * Constructs a SolidEllipse
  * These objects are defined by any two diametrically opposing corners of a box
  * bounding the ellipse.
  * 
  * @param color the color for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  */
 public SolidEllipseFigure(Color color, int x1, int y1, int x2, int y2) {
   this.color = color; this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setBackground(color);
   fdc.gc.fillOval(r.x, r.y, r.width, r.height);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* The superclass for paint tools that contruct objects from individually
* picked segments.
*/

abstract class SegmentedPaintSession extends BasicPaintSession {

 /**
  * The set of control points making up the segmented selection
  */
 private Vector /* of Point */ controlPoints = new Vector();
 /**
  * The previous figure (so that we can abort with right-button)
  */
 private Figure previousFigure = null;
 /**
  * The current figure (so that we can abort with right-button)
  */
 private Figure currentFigure = null;
 /**
  * Constructs a PaintSession.
  * 
  * @param paintSurface the drawing surface to use
  */
 protected SegmentedPaintSession(PaintSurface paintSurface) {
   super(paintSurface);
 }
 /**
  * Activates the tool.
  */
 public void beginSession() {
   getPaintSurface().setStatusMessage(PaintExample.getResourceString(
     "session.SegmentedInteractivePaint.message.anchorMode"));
   previousFigure = null;
   currentFigure = null;
   controlPoints.clear();
 }
 
 /**
  * Deactivates the tool.
    */
 public void endSession() {
   getPaintSurface().clearRubberbandSelection();
   if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
 }
 
 /**
  * Resets the tool.
  * Aborts any operation in progress.
  */
 public void resetSession() {
   getPaintSurface().clearRubberbandSelection();
   if (previousFigure != null) getPaintSurface().drawFigure(previousFigure);
   
   getPaintSurface().setStatusMessage(PaintExample.getResourceString(
     "session.SegmentedInteractivePaint.message.anchorMode"));
   previousFigure = null;
   currentFigure = null;
   controlPoints.clear();
 }
 /**
  * Handles a mouseDown event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDown(MouseEvent event) {
   if (event.button != 1) return;
   getPaintSurface().setStatusMessage(PaintExample.getResourceString(
     "session.SegmentedInteractivePaint.message.interactiveMode"));
   previousFigure = currentFigure;
   if (controlPoints.size() > 0) {
     final Point lastPoint = (Point) controlPoints.elementAt(controlPoints.size() - 1);
     if (lastPoint.x == event.x || lastPoint.y == event.y) return; // spurious event
   }
   controlPoints.add(new Point(event.x, event.y));
 }
 /**
  * Handles a mouseDoubleClick event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDoubleClick(MouseEvent event) {
   if (event.button != 1) return;
   if (controlPoints.size() >= 2) {
     getPaintSurface().clearRubberbandSelection();
     previousFigure = createFigure(
       (Point[]) controlPoints.toArray(new Point[controlPoints.size()]),
       controlPoints.size(), true);
   }
   resetSession();
 }
 /**
  * Handles a mouseUp event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseUp(MouseEvent event) {
   if (event.button != 1) {
     resetSession(); // abort if right or middle mouse button pressed
     return;
   }
 }
 
 /**
  * Handles a mouseMove event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseMove(MouseEvent event) {
   final PaintSurface ps = getPaintSurface();
   if (controlPoints.size() == 0) {
     ps.setStatusCoord(ps.getCurrentPosition());
     return; // spurious event
   } else {
     ps.setStatusCoordRange((Point) controlPoints.elementAt(controlPoints.size() - 1),
       ps.getCurrentPosition());
   }
   ps.clearRubberbandSelection();
   Point[] points = (Point[]) controlPoints.toArray(new Point[controlPoints.size() + 1]);
   points[controlPoints.size()] = ps.getCurrentPosition();
   currentFigure = createFigure(points, points.length, false);
   ps.addRubberbandSelection(currentFigure);
 }  
 /**
  * Template Method: Creates a Figure for drawing rubberband entities and the final product
  * 
  * @param points the array of control points
  * @param numPoints the number of valid points in the array (n >= 2)
  * @param closed true if the user double-clicked on the final control point
  */
 protected abstract Figure createFigure(Point[] points, int numPoints, boolean closed);

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A drawing tool.
*/

class RoundedRectangleTool extends DragPaintSession implements PaintTool {

 private ToolSettings settings;
 /**
  * Constructs a RoundedRectangleTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public RoundedRectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 
 /**
  * Returns name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.RoundedRectangle.label");
 }
 /*
  * Template methods for drawing
  */
 protected Figure createFigure(Point a, Point b) {
   ContainerFigure container = new ContainerFigure();
   if (settings.rumonFillType != ToolSettings.ftNone)
     container.add(new SolidRoundedRectangleFigure(settings.rumonBackgroundColor,
       a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
   if (settings.rumonFillType != ToolSettings.ftSolid)
     container.add(new RoundedRectangleFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor,
       settings.rumonLineStyle, a.x, a.y, b.x, b.y, settings.roundedRectangleCornerDiameter));
   return container;
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Rectangle object
*/

class RoundedRectangleFigure extends Figure {

 private Color foregroundColor, backgroundColor;
 private int lineStyle, x1, y1, x2, y2, diameter;
 /**
  * Constructs a Rectangle
  * These objects are defined by any two diametrically opposing corners.
  * 
  * @param color the color for this object
  * @param lineStyle the line style for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  * @param diameter the diameter of curvature of all four corners
  */
 public RoundedRectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2, int diameter) {
   this.foregroundColor = foregroundColor;
   this.backgroundColor = backgroundColor;
   this.lineStyle = lineStyle;
   this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
   this.diameter = diameter;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setForeground(foregroundColor);
   fdc.gc.setBackground(backgroundColor);
   fdc.gc.setLineStyle(lineStyle);
   fdc.gc.drawRoundRectangle(r.x, r.y, r.width - 1, r.height - 1, diameter, diameter);
   fdc.gc.setLineStyle(SWT.LINE_SOLID);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A drawing tool.
*/

class RectangleTool extends DragPaintSession implements PaintTool {

 private ToolSettings settings;
 /**
  * Constructs a RectangleTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public RectangleTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 
 /**
  * Returns name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Rectangle.label");
 }
 /*
  * Template method for drawing
  */
 protected Figure createFigure(Point a, Point b) {
   switch (settings.rumonFillType) {
     default:
     case ToolSettings.ftNone:
       return new RectangleFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
         a.x, a.y, b.x, b.y);
     case ToolSettings.ftSolid:
       return new SolidRectangleFigure(settings.rumonBackgroundColor, a.x, a.y, b.x, b.y);
     case ToolSettings.ftOutline: {
       ContainerFigure container = new ContainerFigure();
       container.add(new SolidRectangleFigure(settings.rumonBackgroundColor, a.x, a.y, b.x, b.y));
       container.add(new RectangleFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
         a.x, a.y, b.x, b.y));
       return container;
     }
   }
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Rectangle object
*/

class RectangleFigure extends Figure {

 private Color foregroundColor, backgroundColor;
 private int lineStyle, x1, y1, x2, y2;
 /**
  * Constructs a Rectangle
  * These objects are defined by any two diametrically opposing corners.
  * 
  * @param color the color for this object
  * @param lineStyle the line style for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  */
 public RectangleFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
   this.foregroundColor = foregroundColor;
   this.backgroundColor = backgroundColor;
   this.lineStyle = lineStyle;
   this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setForeground(foregroundColor);
   fdc.gc.setBackground(backgroundColor);
   fdc.gc.setLineStyle(lineStyle);
   fdc.gc.drawRectangle(r.x, r.y, r.width - 1, r.height - 1);
   fdc.gc.setLineStyle(SWT.LINE_SOLID);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A polyline drawing tool.
*/

class PolyLineTool extends SegmentedPaintSession implements PaintTool {

 private ToolSettings settings;
 /**
  * Constructs a PolyLineTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public PolyLineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 /**
  * Returns the name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.PolyLine.label");
 }
 /*
  * Template methods for drawing
  */
 protected Figure createFigure(Point[] points, int numPoints, boolean closed) {
   ContainerFigure container = new ContainerFigure();
   if (closed && settings.rumonFillType != ToolSettings.ftNone && numPoints >= 3) {
     container.add(new SolidPolygonFigure(settings.rumonBackgroundColor, points, numPoints));
   }
   if (! closed || settings.rumonFillType != ToolSettings.ftSolid || numPoints < 3) {
     for (int i = 0; i < numPoints - 1; ++i) {
       final Point a = points[i];
       final Point b = points[i + 1];
       container.add(new LineFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
         a.x, a.y, b.x, b.y));
     }
     if (closed) {
       final Point a = points[points.length - 1];
       final Point b = points[0];
       container.add(new LineFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
         a.x, a.y, b.x, b.y));
     }
   }
   return container;
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Point object
*/

class PointFigure extends Figure {

 private Color color;
 private int x, y;
 /**
  * Constructs a Point
  * 
  * @param color the color for this object
  * @param x the virtual X coordinate of the first end-point
  * @param y the virtual Y coordinate of the first end-point
  */
 public PointFigure(Color color, int x, int y) {
   this.color = color; this.x = x; this.y = y;
 }
 public void draw(FigureDrawContext fdc) {
   Point p = fdc.toClientPoint(x, y);
   fdc.gc.setBackground(color);
   fdc.gc.fillRectangle(p.x, p.y, 1, 1);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x, y, x, y));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A pencil tool.
*/

class PencilTool extends ContinuousPaintSession implements PaintTool {

 private ToolSettings settings;
 
 /**
  * Constructs a pencil tool.
  * 
  * @param toolSettings the new tool settings
  * @param getPaintSurface() the PaintSurface we will render on.
  */
 public PencilTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 /**
  * Returns the name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Pencil.label");
 }
 /*
  * Template method for drawing
  */
 public void render(final Point point) {
   final PaintSurface ps = getPaintSurface();
   ps.drawFigure(new PointFigure(settings.rumonForegroundColor, point.x, point.y));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

interface PaintTool extends PaintSession {

 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings);

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* Manages a simple drawing surface.
*/

class PaintSurface {

 private Point currentPosition = new Point(0, 0);
 private Canvas paintCanvas;
 private PaintSession paintSession;
 private Image image;
 private Image paintImage; // buffer for refresh blits
 private int   imageWidth, imageHeight;
 private int   visibleWidth, visibleHeight;
 private FigureDrawContext displayFDC = new FigureDrawContext();
 private FigureDrawContext imageFDC = new FigureDrawContext();
 private FigureDrawContext paintFDC = new FigureDrawContext();
 /* Rubberband */
 private ContainerFigure rubberband = new ContainerFigure();
   // the active rubberband selection
 private int rubberbandHiddenNestingCount = 0;
   // always >= 0, if > 0 rubberband has been hidden
 /* Status */
 private Text statusText;
 private String statusActionInfo, statusMessageInfo, statusCoordInfo;
 /**
  * Constructs a PaintSurface.
*

* paintCanvas must have SWT.NO_REDRAW_RESIZE and SWT.NO_BACKGROUND styles, * and may have SWT.V_SCROLL and/or SWT.H_SCROLL. *

  * @param paintCanvas the Canvas object in which to render
  * @param paintStatus the PaintStatus object to use for providing user feedback
  * @param fillColor the color to fill the canvas with initially
  */
 public PaintSurface(Canvas paintCanvas, Text statusText, Color fillColor) {
   this.paintCanvas = paintCanvas;
   this.statusText = statusText;
   clearStatus();
   /* Set up the drawing surface */
   Rectangle displayRect = paintCanvas.getDisplay().getClientArea();
   imageWidth = displayRect.width;
   imageHeight = displayRect.height;
   image = new Image(paintCanvas.getDisplay(), imageWidth, imageHeight);
   imageFDC.gc = new GC(image);
   imageFDC.gc.setBackground(fillColor);
   imageFDC.gc.fillRectangle(0, 0, imageWidth, imageHeight);
   displayFDC.gc = new GC(paintCanvas);
   /* Initialize the session */
   setPaintSession(null);
   /* Add our listeners */
   paintCanvas.addDisposeListener(new DisposeListener() {
     public void widgetDisposed(DisposeEvent e) {
       displayFDC.gc.dispose();
     }      
   });
   paintCanvas.addMouseListener(new MouseAdapter() {
     public void mouseDown(MouseEvent event) {
       processMouseEventCoordinates(event);
       if (paintSession != null) paintSession.mouseDown(event);
     }
     public void mouseUp(MouseEvent event) {
       processMouseEventCoordinates(event);
       if (paintSession != null) paintSession.mouseUp(event);
     }
     public void mouseDoubleClick(MouseEvent event) {
       processMouseEventCoordinates(event);
       if (paintSession != null) paintSession.mouseDoubleClick(event);
     }      
   });
   paintCanvas.addMouseMoveListener(new MouseMoveListener() {
     public void mouseMove(MouseEvent event) {
       processMouseEventCoordinates(event);
       if (paintSession != null) paintSession.mouseMove(event);
     }
   });
   paintCanvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent event) {
       if (rubberband.isEmpty()) {
         // Nothing to merge, so we just refresh
         event.gc.drawImage(image,
           displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height,
           event.x, event.y, event.width, event.height);
       } else {
         /*
          * Avoid flicker when merging overlayed objects by constructing the image on
          * a backbuffer first, then blitting it to the screen.
          */
         // Check that the backbuffer is large enough
         if (paintImage != null) {
           Rectangle rect = paintImage.getBounds();
           if ((event.width + event.x > rect.width) ||
             (event.height + event.y > rect.height)) {
             paintFDC.gc.dispose();
             paintImage.dispose();
             paintImage = null;
           }
         }
         if (paintImage == null) {
           Display display = getDisplay();
           Rectangle rect = display.getClientArea();
           paintImage = new Image(display,
             Math.max(rect.width, event.width + event.x),
             Math.max(rect.height, event.height + event.y));
           paintFDC.gc = new GC(paintImage);
         }
         // Setup clipping and the FDC
         Region clipRegion = new Region();
         event.gc.getClipping(clipRegion);          
         paintFDC.gc.setClipping(clipRegion);
         clipRegion.dispose();
         paintFDC.xOffset = displayFDC.xOffset;
         paintFDC.yOffset = displayFDC.yOffset;
         paintFDC.xScale = displayFDC.xScale;
         paintFDC.yScale = displayFDC.yScale;
         
         // Merge the overlayed objects into the image, then blit
         paintFDC.gc.drawImage(image,
           displayFDC.xOffset + event.x, displayFDC.yOffset + event.y, event.width, event.height,
           event.x, event.y, event.width, event.height);
         rubberband.draw(paintFDC);
         event.gc.drawImage(paintImage,
           event.x, event.y, event.width, event.height,
           event.x, event.y, event.width, event.height);
       }
     }
   });
   paintCanvas.addControlListener(new ControlAdapter() {
     public void controlResized(ControlEvent event) {
       handleResize();
     }      
   });
   /* Set up the paint canvas scroll bars */
   ScrollBar horizontal = paintCanvas.getHorizontalBar();
   horizontal.setVisible(true);
   horizontal.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent event) {
       scrollHorizontally((ScrollBar)event.widget);
     }
   });
   ScrollBar vertical = paintCanvas.getVerticalBar();
   vertical.setVisible(true);
   vertical.addSelectionListener(new SelectionAdapter() {
     public void widgetSelected(SelectionEvent event) {
       scrollVertically((ScrollBar)event.widget);
     }
   });
   handleResize();
 }
 
 /**
  * Disposes of the PaintSurface"s resources.
  */
 public void dispose() {
   imageFDC.gc.dispose();
   image.dispose();
   if (paintImage != null) {
     paintImage.dispose();
     paintFDC.gc.dispose();
   }
   currentPosition = null;
   paintCanvas = null;
   paintSession = null;
   image = null;
   paintImage = null;
   displayFDC = null;
   imageFDC = null;
   paintFDC = null;
   rubberband = null;
   statusText = null;
   statusActionInfo = null;
   statusMessageInfo = null;
   statusCoordInfo = null;
 }
 /**
  * Called when we must grab focus.
  */
 public void setFocus()  {
   paintCanvas.setFocus();
 }
 /**
  * Returns the Display on which the PaintSurface resides.
  * @return the Display
  */
 public Display getDisplay() {
   return paintCanvas.getDisplay();
 }
 /**
  * Returns the Shell in which the PaintSurface resides.
  * @return the Shell
  */
 public Shell getShell() {
   return paintCanvas.getShell();
 }
 /**
  * Sets the current paint session.
*

* If oldPaintSession != paintSession calls oldPaintSession.end() * and paintSession.begin() *

  * 
  * @param paintSession the paint session to activate; null to disable all sessions
  */
 public void setPaintSession(PaintSession paintSession) {
   if (this.paintSession != null) {
     if (this.paintSession == paintSession) return;
     this.paintSession.endSession();
   }
   this.paintSession = paintSession;
   clearStatus();
   if (paintSession != null) {
     setStatusAction(paintSession.getDisplayName());
     paintSession.beginSession();
   } else {
     setStatusAction(PaintExample.getResourceString("tool.Null.label"));
     setStatusMessage(PaintExample.getResourceString("session.Null.message"));
   }
 }
 /**
  * Returns the current paint session.
  * 
  * @return the current paint session, null if none is active
  */
 public PaintSession getPaintSession() {
   return paintSession;
 }
 /**
  * Returns the current paint tool.
  * 
  * @return the current paint tool, null if none is active (though some other session
  *         might be)
  */
 public PaintTool getPaintTool() {
   return (paintSession != null && paintSession instanceof PaintTool) ?
     (PaintTool)paintSession : null;
 }
 /**
  * Returns the current position in an interactive operation.
  *
  * @return the last known position of the pointer
  */
 public Point getCurrentPosition() {
   return currentPosition;
 }
 /**
  * Draws a Figure object to the screen and to the backing store permanently.
  * 
  * @param object the object to draw onscreen
  */
 public void drawFigure(Figure object) {
   object.draw(imageFDC);
   object.draw(displayFDC);
 }
 /**
  * Adds a Figure object to the active rubberband selection.
*

* This object will be drawn to the screen as a preview and refreshed appropriately * until the selection is either cleared or committed. *

  * 
  * @param object the object to add to the selection
  */
 public void addRubberbandSelection(Figure object) {
   rubberband.add(object);
   if (! isRubberbandHidden()) object.draw(displayFDC);
 }
 /**
  * Clears the active rubberband selection.
*

* Erases any rubberband objects on the screen then clears the selection. *

  */
 public void clearRubberbandSelection() {
   if (! isRubberbandHidden()) {
     Region region = new Region();
     rubberband.addDamagedRegion(displayFDC, region);
     Rectangle r = region.getBounds();
     paintCanvas.redraw(r.x, r.y, r.width, r.height, true);
     region.dispose();
   }
   rubberband.clear();
 }
 /**
  * Commits the active rubberband selection.
*

* Redraws any rubberband objects on the screen as permanent objects then clears the selection. *

  */
 public void commitRubberbandSelection() {
   rubberband.draw(imageFDC);
   if (isRubberbandHidden()) rubberband.draw(displayFDC);
   rubberband.clear();
 }
 
 /**
  * Hides the rubberband (but does not eliminate it).
*

* Increments by one the rubberband "hide" nesting count. The rubberband * is hidden from view (but remains active) if it wasn"t already hidden. *

  */
 public void hideRubberband() {
   if (rubberbandHiddenNestingCount++ <= 0) {
     Region region = new Region();
     rubberband.addDamagedRegion(displayFDC, region);
     Rectangle r = region.getBounds();
     paintCanvas.redraw(r.x, r.y, r.width, r.height, true);
     region.dispose();
   }
 }    
 /**
  * Shows (un-hides) the rubberband.
*

* Decrements by one the rubberband "hide" nesting count. The rubberband * is only made visible when showRubberband() has been called once for each * previous hideRubberband(). It is not permitted to call showRubberband() if * the rubber band is not presently hidden. *

  */
 public void showRubberband() {
   if (rubberbandHiddenNestingCount <= 0)
     throw new IllegalStateException("rubberbandHiddenNestingCount > 0");
   if (--rubberbandHiddenNestingCount == 0) {
     rubberband.draw(displayFDC);
   }
 }
 
 /**
  * Determines if the rubberband is hidden.
  * 
  * @return true iff the rubber is hidden
  */
 public boolean isRubberbandHidden() {
   return rubberbandHiddenNestingCount > 0;
 }
 /**
  * Handles a horizontal scroll event
  * 
  * @param scrollbar the horizontal scroll bar that posted this event
  */
 public void scrollHorizontally(ScrollBar scrollBar) {
   if (image == null) return;
   if (imageWidth > visibleWidth) {
     final int oldOffset = displayFDC.xOffset;
     final int newOffset = Math.min(scrollBar.getSelection(), imageWidth - visibleWidth);
     if (oldOffset != newOffset) {
       paintCanvas.update();
       displayFDC.xOffset = newOffset;
       paintCanvas.scroll(Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0), 0,
         visibleWidth, visibleHeight, false);
     }
   }
 }
 /**
  * Handles a vertical scroll event
  * 
  * @param scrollbar the vertical scroll bar that posted this event
  */
 public void scrollVertically(ScrollBar scrollBar) {
   if (image == null) return;
   if (imageHeight > visibleHeight) {
     final int oldOffset = displayFDC.yOffset;
     final int newOffset = Math.min(scrollBar.getSelection(), imageHeight - visibleHeight);
     if (oldOffset != newOffset) {
       paintCanvas.update();
       displayFDC.yOffset = newOffset;
       paintCanvas.scroll(0, Math.max(oldOffset - newOffset, 0), 0, Math.max(newOffset - oldOffset, 0),
         visibleWidth, visibleHeight, false);
     }
   }
 }
 
 /**
  * Handles resize events
  */
 private void handleResize() {
   paintCanvas.update();
   Rectangle visibleRect = paintCanvas.getClientArea();
   visibleWidth = visibleRect.width;
   visibleHeight = visibleRect.height;
   ScrollBar horizontal = paintCanvas.getHorizontalBar();
   if (horizontal != null) {
     displayFDC.xOffset = Math.min(horizontal.getSelection(), imageWidth - visibleWidth);
     if (imageWidth <= visibleWidth) {
       horizontal.setEnabled(false);
       horizontal.setSelection(0);
     } else {
       horizontal.setEnabled(true);
       horizontal.setValues(displayFDC.xOffset, 0, imageWidth, visibleWidth,
         8, visibleWidth);
     }
   }
   ScrollBar vertical = paintCanvas.getVerticalBar();
   if (vertical != null) {
     displayFDC.yOffset = Math.min(vertical.getSelection(), imageHeight - visibleHeight);
     if (imageHeight <= visibleHeight) {
       vertical.setEnabled(false);
       vertical.setSelection(0);
     } else {
       vertical.setEnabled(true);
       vertical.setValues(displayFDC.yOffset, 0, imageHeight, visibleHeight,
         8, visibleHeight);
     }
   }
 }
 /**
  * Virtualizes MouseEvent coordinates and stores the current position.
  */
 private void processMouseEventCoordinates(MouseEvent event) {
   currentPosition.x = event.x =
     Math.min(Math.max(event.x, 0), visibleWidth - 1) + displayFDC.xOffset;
   currentPosition.y = event.y =
     Math.min(Math.max(event.y, 0), visibleHeight - 1) + displayFDC.yOffset;
 }
 
 /**
  * Clears the status bar.
  */
 public void clearStatus() {
   statusActionInfo = "";
   statusMessageInfo = "";
   statusCoordInfo = "";
   updateStatus();
 }
 /**
  * Sets the status bar action text.
  *
  * @param action the action in progress, null to clear
  */
 public void setStatusAction(String action) {
   statusActionInfo = (action != null) ? action : "";
   updateStatus();
 }
 
 /**
  * Sets the status bar message text.
  * 
  * @param message the message to display, null to clear
  */
 public void setStatusMessage(String message) {
   statusMessageInfo = (message != null) ? message : "";
   updateStatus();
 }
 /**
  * Sets the coordinates in the status bar.
  * 
  * @param coord the coordinates to display, null to clear
  */
 public void setStatusCoord(Point coord) {
   statusCoordInfo = (coord != null) ? PaintExample.getResourceString("status.Coord.format", new Object[]
     { new Integer(coord.x), new Integer(coord.y)}) : "";
   updateStatus();
 }
 /**
  * Sets the coordinate range in the status bar.
  * 
  * @param a the "from" coordinate, must not be null
  * @param b the "to" coordinate, must not be null
  */
 public void setStatusCoordRange(Point a, Point b) {
   statusCoordInfo = PaintExample.getResourceString("status.CoordRange.format", new Object[]
     { new Integer(a.x), new Integer(a.y), new Integer(b.x), new Integer(b.y)});
   updateStatus();
 }
 /**
  * Updates the display.
  */
 private void updateStatus() {
   statusText.setText(
     PaintExample.getResourceString("status.Bar.format", new Object[]
     { statusActionInfo, statusMessageInfo, statusCoordInfo }));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* Manages an interactive paint session.
* Note that the coordinates received via the listener interfaces are virtualized to zero-origin
* relative to the painting surface.
*/ 

interface PaintSession extends MouseListener, MouseMoveListener {

 /**
  * Returns the paint surface associated with this paint session
  * 
  * @return the associated PaintSurface
  */
 public PaintSurface getPaintSurface();
 /**
  * Activates the session.
  * 
  * Note: When overriding this method, call super.beginSession() at method start.
  */
 public abstract void beginSession();
 
 /**
  * Deactivates the session.
    *
  * Note: When overriding this method, call super.endSession() at method exit.
    */
 public abstract void endSession();
 
 /**
  * Resets the session.
  * Aborts any operation in progress.
  * 
  * Note: When overriding this method, call super.resetSession() at method exit.
  */
 public abstract void resetSession();
 
 
 /**
  * Returns the name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName();

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A line drawing tool
*/

class LineTool extends DragPaintSession implements PaintTool {

 private ToolSettings settings;
 /**
  * Constructs a LineTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public LineTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 
 /**
  * Returns name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Line.label");
 }
 /*
  * Template methods for drawing
  */
 protected Figure createFigure(Point a, Point b) {
   return new LineFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
     a.x, a.y, b.x, b.y);
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Line object
*/

class LineFigure extends Figure {

 private Color foregroundColor, backgroundColor;
 private int lineStyle, x1, y1, x2, y2;
 /**
  * Constructs a Line
  * These objects are defined by their two end-points.
  * 
  * @param color the color for this object
  * @param lineStyle the line style for this object
  * @param x1 the virtual X coordinate of the first end-point
  * @param y1 the virtual Y coordinate of the first end-point
  * @param x2 the virtual X coordinate of the second end-point
  * @param y2 the virtual Y coordinate of the second end-point
  */
 public LineFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
   this.foregroundColor = foregroundColor;
   this.backgroundColor = backgroundColor;
   this.lineStyle = lineStyle;
   this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
 }
 public void draw(FigureDrawContext fdc) {
   Point p1 = fdc.toClientPoint(x1, y1);
   Point p2 = fdc.toClientPoint(x2, y2);
   fdc.gc.setForeground(foregroundColor);
   fdc.gc.setBackground(backgroundColor);
   fdc.gc.setLineStyle(lineStyle);
   fdc.gc.drawLine(p1.x, p1.y, p2.x, p2.y);
   fdc.gc.setLineStyle(SWT.LINE_SOLID);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

class FigureDrawContext {

 /*
*

* The GC must be set up as follows * (it will be returned to this state upon completion of drawing operations) *

    *
  • setXORMode(false) *
*

  */
 public GC gc = null;
 public int xOffset = 0, yOffset = 0; // substract to get GC coords
 public int xScale = 1, yScale = 1;
 
 public Rectangle toClientRectangle(int x1, int y1, int x2, int y2) {
   return new Rectangle(
     Math.min(x1, x2) * xScale - xOffset,
     Math.min(y1, y2) * yScale - yOffset,
     (Math.abs(x2 - x1) + 1) * xScale,
     (Math.abs(y2 - y1) + 1) * yScale);
 }
 public Point toClientPoint(int x, int y) {
   return new Point(x * xScale - xOffset, y * yScale - yOffset);
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* Superinterface for all drawing objects.
* All drawing objects know how to render themselved to the screen and can draw a
* temporary version of themselves for previewing the general appearance of the
* object onscreen before it gets committed.
*/

abstract class Figure {

 /**
  * Draws this object.
  * 
  * @param fdc a parameter block specifying drawing-related information
  */
 public abstract void draw(FigureDrawContext fdc);
 /**
  * Computes the damaged screen region caused by drawing this object (imprecise), then
  * appends it to the supplied region.
  * 
  * @param fdc a parameter block specifying drawing-related information
  * @param region a region to which additional damage areas will be added
  */
 public abstract void addDamagedRegion(FigureDrawContext fdc, Region region);

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* A drawing tool.
*/

class EllipseTool extends DragPaintSession implements PaintTool {

 private ToolSettings settings;
 /**
  * Constructs a EllipseTool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public EllipseTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   set(toolSettings);
 }
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   settings = toolSettings;
 }
 /**
  * Returns name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Ellipse.label");
 }
 /*
  * Template methods for drawing
  */
 protected Figure createFigure(Point a, Point b) {
   ContainerFigure container = new ContainerFigure();
   if (settings.rumonFillType != ToolSettings.ftNone)
     container.add(new SolidEllipseFigure(settings.rumonBackgroundColor, a.x, a.y, b.x, b.y));
   if (settings.rumonFillType != ToolSettings.ftSolid)
     container.add(new EllipseFigure(settings.rumonForegroundColor, settings.rumonBackgroundColor, settings.rumonLineStyle,
       a.x, a.y, b.x, b.y));
   return container;
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* 2D Ellipse object
*/

class EllipseFigure extends Figure {

 private Color foregroundColor, backgroundColor;
 private int lineStyle, x1, y1, x2, y2;
 /**
  * Constructs an Ellipse
  * These objects are defined by any two diametrically opposing corners of a box
  * bounding the ellipse.
  * 
  * @param color the color for this object
  * @param lineStyle the line style for this object
  * @param x1 the virtual X coordinate of the first corner
  * @param y1 the virtual Y coordinate of the first corner
  * @param x2 the virtual X coordinate of the second corner
  * @param y2 the virtual Y coordinate of the second corner
  */
 public EllipseFigure(Color foregroundColor, Color backgroundColor, int lineStyle, int x1, int y1, int x2, int y2) {
   this.foregroundColor = foregroundColor;
   this.backgroundColor = backgroundColor;
   this.lineStyle = lineStyle;
   this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2;
 }
 public void draw(FigureDrawContext fdc) {
   Rectangle r = fdc.toClientRectangle(x1, y1, x2, y2);
   fdc.gc.setForeground(foregroundColor);
   fdc.gc.setBackground(backgroundColor);
   fdc.gc.setLineStyle(lineStyle);
   fdc.gc.drawOval(r.x, r.y, r.width - 1, r.height - 1);
   fdc.gc.setLineStyle(SWT.LINE_SOLID);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   region.add(fdc.toClientRectangle(x1, y1, x2, y2));
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* The superclass for paint tools that use click-drag-release motions to
* draw objects.
*/

abstract class DragPaintSession extends BasicPaintSession {

 /**
  * True if a click-drag is in progress
  */
 private boolean dragInProgress = false;
 
 /**
  * The position of the first click in a click-drag
  */
 private Point anchorPosition = new Point(-1, -1);
 /**
  * A temporary point
  */
 private Point tempPosition = new Point(-1, -1);
 
 /**
  * Constructs a PaintSession.
  * 
  * @param getPaintSurface() the drawing surface to use
  */
 protected DragPaintSession(PaintSurface paintSurface) {
   super(paintSurface);
 }
 /**
  * Activates the tool.
  */
 public void beginSession() {
   getPaintSurface().
     setStatusMessage(PaintExample.getResourceString("session.DragInteractivePaint.message"));
   anchorPosition.x = -1;
   dragInProgress = false;
 }
 
 /**
  * Deactivates the tool.
    */
 public void endSession() {
 }
 
 /**
  * Resets the tool.
  * Aborts any operation in progress.
  */
 public void resetSession() {
   getPaintSurface().clearRubberbandSelection();
   anchorPosition.x = -1;
   dragInProgress = false;
 }
 /**
  * Handles a mouseDown event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDown(MouseEvent event) {
   if (event.button != 1) return;
   if (dragInProgress) return; // spurious event
   dragInProgress = true;
   
   anchorPosition.x = event.x;
   anchorPosition.y = event.y;
 }
 /**
  * Handles a mouseDoubleClick event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseDoubleClick(MouseEvent event) {
 }
 /**
  * Handles a mouseUp event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseUp(MouseEvent event) {
   if (event.button != 1) {
     resetSession(); // abort if right or middle mouse button pressed
     return;
   }
   if (! dragInProgress) return; // spurious event
   dragInProgress = false;
   if (anchorPosition.x == -1) return; // spurious event
   
   getPaintSurface().rumitRubberbandSelection();
 }
 
 /**
  * Handles a mouseMove event.
  * 
  * @param event the mouse event detail information
  */
 public void mouseMove(MouseEvent event) {
   final PaintSurface ps = getPaintSurface();
   if (! dragInProgress) {
     ps.setStatusCoord(ps.getCurrentPosition());
     return;
   }
   ps.setStatusCoordRange(anchorPosition, ps.getCurrentPosition());
   ps.clearRubberbandSelection();
   tempPosition.x = event.x;
   tempPosition.y = event.y;
   ps.addRubberbandSelection(createFigure(anchorPosition, tempPosition));
 }
 
 /**
  * Template Method: Creates a Figure for drawing rubberband entities and the final product
  * 
  * @param anchor the anchor point
  * @param cursor the point marking the current pointer location
  */
 protected abstract Figure createFigure(Point anchor, Point cursor);

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* The superclass for paint tools that draw continuously along the path
* traced by the mouse"s movement while the button is depressed
*/

abstract class ContinuousPaintSession extends BasicPaintSession {

 /**
  * True if a click-drag is in progress.
  */
 private boolean dragInProgress = false;
 
 /**
  * A cached Point array for drawing.
  */
 private Point[] points = new Point[] { new Point(-1, -1), new Point(-1, -1) };
 /**
  * The time to wait between retriggers in milliseconds.
  */
 private int retriggerInterval = 0;
 
 /**
  * The currently valid RetriggerHandler
  */
 protected Runnable retriggerHandler = null;
 /**
  * Constructs a ContinuousPaintSession.
  * 
  * @param paintSurface the drawing surface to use
  */
 protected ContinuousPaintSession(PaintSurface paintSurface) {
   super(paintSurface);
 }
 /**
  * Sets the retrigger timer.
*

* After the timer elapses, if the mouse is still hovering over the same point with the * drag button pressed, a new render order is issued and the timer is restarted. *

  * @param interval the time in milliseconds to wait between retriggers, 0 to disable
  */
 public void setRetriggerTimer(int interval) {
   retriggerInterval = interval;
 }
 /**
  * Activates the tool.
  */
 public void beginSession() {
   getPaintSurface().
     setStatusMessage(PaintExample.getResourceString("session.ContinuousPaint.message"));
   dragInProgress = false;
 }
 
 /**
  * Deactivates the tool.
    */
 public void endSession() {
   abortRetrigger();
 }
 
 /**
  * Aborts the current operation.
  */
 public void resetSession() {
   abortRetrigger();
 }
 /**
  * Handles a mouseDown event.
  * 
  * @param event the mouse event detail information
  */
 public final void mouseDown(MouseEvent event) {
   if (event.button != 1) return;
   if (dragInProgress) return; // spurious event
   dragInProgress = true;
   points[0].x = event.x;
   points[0].y = event.y;
   render(points[0]);
   prepareRetrigger();
 }
 /**
  * Handles a mouseDoubleClick event.
  * 
  * @param event the mouse event detail information
  */
 public final void mouseDoubleClick(MouseEvent event) {
 }
 /**
  * Handles a mouseUp event.
  * 
  * @param event the mouse event detail information
  */
 public final void mouseUp(MouseEvent event) {
   if (event.button != 1) return;
   if (! dragInProgress) return; // spurious event
   abortRetrigger();
   mouseSegmentFinished(event);
   dragInProgress = false;
 }
 
 /**
  * Handles a mouseMove event.
  * 
  * @param event the mouse event detail information
  */
 public final void mouseMove(MouseEvent event) {
   final PaintSurface ps = getPaintSurface();
   ps.setStatusCoord(ps.getCurrentPosition());
   if (! dragInProgress) return;
   mouseSegmentFinished(event);
   prepareRetrigger();
 }
 
 /**
  * Handle a rendering segment
  * 
  * @param event the mouse event detail information
  */
 private final void mouseSegmentFinished(MouseEvent event) {
   if (points[0].x == -1) return; // spurious event
   if (points[0].x != event.x || points[0].y != event.y) {
     // draw new segment
     points[1].x = event.x;
     points[1].y = event.y;
     renderContinuousSegment();
   }
 }
 /**
  * Draws a continuous segment from points[0] to points[1].
  * Assumes points[0] has been drawn already.
  * 
  * @post points[0] will refer to the same point as points[1]
  */
 protected void renderContinuousSegment() {
   /* A lazy but effective line drawing algorithm */
   final int dX = points[1].x - points[0].x;
   final int dY = points[1].y - points[0].y;
   int absdX = Math.abs(dX);
   int absdY = Math.abs(dY);
   if ((dX == 0) && (dY == 0)) return;
   
   if (absdY > absdX) {
     final int incfpX = (dX << 16) / absdY;
     final int incY = (dY > 0) ? 1 : -1;
     int fpX = points[0].x << 16; // X in fixedpoint format
     while (--absdY >= 0) {
       points[0].y += incY;
       points[0].x = (fpX += incfpX) >> 16;
       render(points[0]);
     }
     if (points[0].x == points[1].x) return;
     points[0].x = points[1].x;
   } else {
     final int incfpY = (dY << 16) / absdX;
     final int incX = (dX > 0) ? 1 : -1;
     int fpY = points[0].y << 16; // Y in fixedpoint format
     while (--absdX >= 0) {
       points[0].x += incX;
       points[0].y = (fpY += incfpY) >> 16;
       render(points[0]);
     }
     if (points[0].y == points[1].y) return;
     points[0].y = points[1].y;
   }
   render(points[0]);
 }    
 /**
  * Prepare the retrigger timer
  */
 private final void prepareRetrigger() {
   if (retriggerInterval > 0) {
     /*
      * timerExec() provides a lightweight mechanism for running code at intervals from within
      * the event loop when timing accuracy is not important.
      *
      * Since it is not possible to cancel a timerExec(), we remember the Runnable that is
      * active in order to distinguish the valid one from the stale ones.  In practice,
      * if the interval is 1/100th of a second, then creating a few hundred new RetriggerHandlers
      * each second will not cause a significant performance hit.
      */
     Display display = getPaintSurface().getDisplay();
     retriggerHandler = new Runnable() {
       public void run() {
         if (retriggerHandler == this) {
           render(points[0]);
           prepareRetrigger();
         }
       }
     };      
     display.timerExec(retriggerInterval, retriggerHandler);
   }
 }
 /**
  * Aborts the retrigger timer
  */
 private final void abortRetrigger() {
   retriggerHandler = null;
 }
 
 /**
  * Template method: Renders a point.
  * @param point, the point to render
  */
 protected abstract void render(Point point);

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* Container for Figure objects with stacking preview mechanism.
*/

class ContainerFigure extends Figure {

 private static final int INITIAL_ARRAY_SIZE = 16;
 
 Figure[]   objectStack = null;
 int      nextIndex = 0;
 /**
  * Constructs an empty Container
  */
 public ContainerFigure() {
 }
 /**
  * Adds an object to the container for later drawing.
  * 
  * @param object the object to add to the drawing list
  */
 public void add(Figure object) {
   if (objectStack == null) {
     objectStack = new Figure[INITIAL_ARRAY_SIZE];
   } else if (objectStack.length <= nextIndex) {
     Figure[] newObjectStack = new Figure[objectStack.length * 2];
     System.arraycopy(objectStack, 0, newObjectStack, 0, objectStack.length);
     objectStack = newObjectStack;
   }
   objectStack[nextIndex] = object;
   ++nextIndex;
 }
 /**
  * Determines if the container is empty.
  * @return true if the container is empty
  */
 public boolean isEmpty() {
   return nextIndex == 0;
 }
 /**
  * Adds an object to the container and draws its preview then updates the supplied preview state.
  * 
  * @param object the object to add to the drawing list
  * @param gc the GC to draw on
  * @param offset the offset to add to virtual coordinates to get display coordinates
  * @param rememberedState the state returned by a previous drawPreview() or addAndPreview()
  *        using this Container, may be null if there was no such previous call
  * @return object state that must be passed to erasePreview() later to erase this object
  */

// public Object addAndPreview(Figure object, GC gc, Point offset, Object rememberedState) { // Object[] stateStack = (Object[]) rememberedState; // if (stateStack == null) { // stateStack = new Object[INITIAL_ARRAY_SIZE]; // } else if (stateStack.length <= nextIndex) { // Object[] newStateStack = new Object[stateStack.length * 2]; // System.arraycopy(stateStack, 0, newStateStack, 0, stateStack.length); // stateStack = newStateStack; // } // add(object); // stateStack[nextIndex - 1] = object.drawPreview(gc, offset); // return stateStack; // }

 /**
  * Clears the container.
*

* Note that erasePreview() cannot be called after this point to erase any previous * drawPreview()"s. *

  */
 public void clear() {
   while (--nextIndex > 0) objectStack[nextIndex] = null;
   nextIndex = 0;
 }
 public void draw(FigureDrawContext fdc) {
   for (int i = 0; i < nextIndex; ++i) objectStack[i].draw(fdc);
 }
 public void addDamagedRegion(FigureDrawContext fdc, Region region) {
   for (int i = 0; i < nextIndex; ++i) objectStack[i].addDamagedRegion(fdc, region);
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

abstract class BasicPaintSession implements PaintSession {

 /**
  * The paint surface
  */
 private PaintSurface paintSurface;
 /**
  * Constructs a PaintSession.
  * 
  * @param paintSurface the drawing surface to use
  */
 protected BasicPaintSession(PaintSurface paintSurface) {
   this.paintSurface = paintSurface;
 }
 /**
  * Returns the paint surface associated with this paint session.
  * 
  * @return the associated PaintSurface
  */
 public PaintSurface getPaintSurface() {
   return paintSurface;
 }

}

/*******************************************************************************

* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*     IBM Corporation - initial API and implementation
*******************************************************************************/

/**

* An airbrush tool.
*/

class AirbrushTool extends ContinuousPaintSession implements PaintTool {

 private ToolSettings settings;
 private Random random;
 private int cachedRadiusSquared;
 private int cachedNumPoints;
 
 /**
  * Constructs a Tool.
  * 
  * @param toolSettings the new tool settings
  * @param paintSurface the PaintSurface we will render on.
  */
 public AirbrushTool(ToolSettings toolSettings, PaintSurface paintSurface) {
   super(paintSurface);
   random = new Random();
   setRetriggerTimer(10);
   set(toolSettings);
 }
 
 /**
  * Sets the tool"s settings.
  * 
  * @param toolSettings the new tool settings
  */
 public void set(ToolSettings toolSettings) {
   // compute things we need to know for drawing
   settings = toolSettings;
   cachedRadiusSquared = settings.airbrushRadius * settings.airbrushRadius;
   cachedNumPoints = 314 * settings.airbrushIntensity * cachedRadiusSquared / 250000;
   if (cachedNumPoints == 0 && settings.airbrushIntensity != 0)
     cachedNumPoints = 1;
 }
 /**
  * Returns the name associated with this tool.
  * 
  * @return the localized name of this tool
  */
 public String getDisplayName() {
   return PaintExample.getResourceString("tool.Airbrush.label");
 }
 /*
  * Template method for drawing
  */
 protected void render(Point point) {
   // Draws a bunch (cachedNumPoints) of random pixels within a specified circle (cachedRadiusSquared).
   ContainerFigure cfig = new ContainerFigure();
   for (int i = 0; i < cachedNumPoints; ++i) {
     int randX, randY;
     do {
       randX = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
       randY = (int) ((random.nextDouble() - 0.5) * settings.airbrushRadius * 2.0);
     } while (randX * randX + randY * randY > cachedRadiusSquared);
     cfig.add(new PointFigure(settings.rumonForegroundColor, point.x + randX, point.y + randY));
   }
   getPaintSurface().drawFigure(cfig);
 }

}


 </source>
   
  
 
  



SWT useful utilities

   <source lang="java">

/*

* (c) Copyright 2004 by Heng Yuan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* ITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/

package cookxml.cookswt.util; import java.util.HashMap; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.*; /**

* SWT useful utilities.
*
* @since CookSwt 1.0
* @author Heng Yuan
*/

public class SwtUtils {

 /**
  * automatically dispose Color resource
  */
 public static boolean autoDisposeColor = true;
 /**
  * automatically dispose Font resource
  */
 public static boolean autoDisposeFont = true;
 /**
  * automatically dispose Image resource
  */
 public static boolean autoDisposeImage = true;
 /**
  * automatically dispose Image resource
  */
 public static boolean autoDisposeCursor = true;
 /**
  * This is a table of system colors that cannot be disposed.
  */
 private static HashMap s_systemColorTable;
 /**
  * This is a table of system cursors that cannot be disposed.
  */
 private static HashMap s_systemCursorTable;
 /**
  * This is a table of system images that cannot be disposed.
  */
 private static HashMap s_systemImageTable;
 /**
  * Setup the system color table for the given device.
  *
  * @param  device the display device.
  */
 private static void setupSystemColorTable (Device device)
 {
   HashMap colorTable = new HashMap ();
   for (int i = 0; i <= 35; ++i)
   {
     Color c = device.getSystemColor (i);
     colorTable.put (c, c);
   }
   s_systemColorTable = colorTable;
 }
 /**
  * Setup the system cursor table for the given device.
  *
  * @param  display the display device.
  */
 private static void setupSystemCursorTable (Display display)
 {
   HashMap cursorTable = new HashMap ();
   for (int i = 0; i <= 21; ++i)
   {
     Cursor c = display.getSystemCursor (i);
     cursorTable.put (c, c);
   }
   s_systemCursorTable = cursorTable;
 }
 /**
  * Setup the system cursor table for the given device.
  *
  * @param  display the display device.
  */
 private static void setupSystemImageTable (Display display)
 {
   HashMap imageTable = new HashMap ();
   Image image;
   image = display.getSystemImage (SWT.ICON_ERROR);
   imageTable.put (image, image);
   image = display.getSystemImage (SWT.ICON_INFORMATION);
   imageTable.put (image, image);
   image = display.getSystemImage (SWT.ICON_QUESTION);
   imageTable.put (image, image);
   image = display.getSystemImage (SWT.ICON_WARNING);
   imageTable.put (image, image);
   image = display.getSystemImage (SWT.ICON_WORKING);
   imageTable.put (image, image);
   s_systemImageTable = imageTable;
 }
 /**
  * Check if a color is a system color.  A system color cannot be disposed.
  *
  * @param  color The color to be disposed.
  * @param  device The device that contains the color.
  */
 public static boolean isSystemColor (Color color, Device device)
 {
   if (s_systemColorTable == null)
     setupSystemColorTable (device);
   return s_systemColorTable.get (color) == color;
 }
 /**
  * Check if a color is a system color.  A system color cannot be disposed.
  *
  * @param  cursor The cursor to be disposed.
  * @param  display The display device.
  */
 public static boolean isSystemCursor (Cursor cursor, Display display)
 {
   if (s_systemCursorTable == null)
     setupSystemCursorTable (display);
   return s_systemCursorTable.get (cursor) == cursor;
 }
 /**
  * Check if a color is a system color.  A system color cannot be disposed.
  *
  * @param  image The image to be disposed.
  * @param  display The display device.
  */
 public static boolean isSystemImage (Image image, Display display)
 {
   if (s_systemImageTable == null)
     setupSystemImageTable (display);
   return s_systemImageTable.get (image) == image;
 }
 /**
  * Check if a color is a system color.  A system color cannot be disposed.
  *
  * @param  font The font to be disposed.
  * @param  device The display device.
  */
 public static boolean isSystemFont (Font font, Device device)
 {
   return device.getSystemFont () == font;
 }
 /**
  * Dispose a color if it is not a system color.
  *
  * @param  color The color to be disposed.
  * @param  device The device that contains the color.
  */
 public static void disposeColor (Color color, Device device)
 {
   if (color.isDisposed ())
     return;
   if (!isSystemColor (color, device))
   {
     assert disposeDebug ("Dispose color: " + color);
     color.dispose ();
   }
 }
 /**
  * Dispose a color if it is not a system color.
  *
  * @param  image The image to be disposed.
  * @param  device The device that contains the color.
  */
 public static void disposeImage (Image image, Display device)
 {
   if (image.isDisposed ())
     return;
   if (!isSystemImage (image, device))
   {
     assert disposeDebug ("Dispose image: " + image);
     image.dispose ();
   }
 }
 /**
  * Attach a DisposeListener that dispose the resource when the widget
  * object is disposed.
  *
  * @param  widget the widget to listen to.
  * @param  color the resource to be disposed.
  */
 public static void attachColorDisposeListener (Widget widget, Color color)
 {
   if (autoDisposeColor &&
     !isSystemColor (color, widget.getDisplay ()))
     widget.addDisposeListener (new ColorDisposeListener (color));
 }
 /**
  * Attach a DisposeListener that dispose the resource when the widget
  * object is disposed.
  *
  * @param  widget the widget to listen to.
  * @param  cursor the resource to be disposed.
  */
 public static void attachCursorDisposeListener (Widget widget, Cursor cursor)
 {
   if (autoDisposeCursor &&
     !isSystemCursor (cursor, widget.getDisplay ()))
     widget.addDisposeListener (new CursorDisposeListener (cursor));
 }
 /**
  * Attach a DisposeListener that dispose the resource when the widget
  * object is disposed.
  *
  * @param  widget the widget to listen to.
  * @param  font the resource to be disposed.
  */
 public static void attachFontDisposeListener (Widget widget, Font font)
 {
   if (autoDisposeFont &&
     !isSystemFont (font, widget.getDisplay ()))
     widget.addDisposeListener (new FontDisposeListener (font));
 }
 /**
  * Attach a DisposeListener that dispose the resource when the widget
  * object is disposed.
  *
  * @param  widget the widget to listen to.
  * @param  image the resource to be disposed.
  */
 public static void attachImageDisposeListener (Widget widget, Image image)
 {
   if (autoDisposeImage &&
      !isSystemImage (image, widget.getDisplay ()))
     widget.addDisposeListener (new ImageDisposeListener (image));
 }
 /**
  * Attach a dropdown menu to a drop down ToolItem.  The drop down menu will be
  * automatically positioned and displayed at under the ToolItem.
  *
  * @param  item the drop down tool item
  * @param  menu the drop down menu
  */
 public static void attachToolItemDropDownMenu (ToolItem item, Menu menu)
 {
   item.addSelectionListener (new DropDownListener (menu));
 }
 /**
  * Open all the shells inside the Display object and dispose the Display
  * after all shells are disposed.
  *
  * @param display the Display object.
  */
 public static void showDisplay (Display display)
 {
   // open shells for display
   Shell[] shells = display.getShells ();
   for (int i = 0; i < shells.length; ++i)
   {
     if (!shells[i].isDisposed () && !shells[i].isVisible ())
       shells[i].open ();
   }
   // exit after all shells are disposed
   while (!display.isDisposed ())
   {
     shells = display.getShells ();
     boolean canExit = true;
     for (int i = 0; i < shells.length; ++i)
     {
       if (!shells[i].isDisposed ())
       {
         canExit = false;
         break;
       }
     }
     if (canExit)
       break;
     if (!display.readAndDispatch ())
       display.sleep ();
   }
   if (!display.isDisposed ())
     display.dispose ();
 }
 /**
  * This function is supposed to work in conjunction with assert to generate
  * a debug message but does not really throw an Exception
  *
  * @param  msg the message to be printed.
  * @return  true
  */
 public static boolean disposeDebug (String msg)
 {
   System.out.println (msg);
   return true;
 }

}

 </source>
   
  
 
  



Transparency

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-21 21:49:01 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class Transparency {

 Display display = new Display();
 Shell shell = new Shell(display);
 public Transparency() {
   shell.setLayout(new FillLayout());
   
   ImageData imageData = new ImageData("jexp.gif");
   
   final Image image = new Image(display, imageData);
   RGB white = new RGB(255, 255, 255);
   for(int i=0; i<imageData.width; i++) {
     for(int j=0; j<imageData.height; j++) {
       RGB rgb = imageData.palette.getRGB(imageData.getPixel(i, j));
       int threshold = 220;
       if(rgb.red > threshold && rgb.green > threshold && rgb.blue > threshold)
         imageData.setPixel(i, j, imageData.palette.getPixel(white));
     }
   }
   
   imageData.transparentPixel = imageData.palette.getPixel(new RGB(255, 255, 255));
   
   final Image image2 = new Image(display, imageData);
   
   final Canvas canvas = new Canvas(shell, SWT.NULL);
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       e.gc.drawImage(image, 10, 20);
       e.gc.drawImage(image2, 200, 20);
     }
   });
   shell.setSize(400, 140);
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new Transparency();
 }

}


 </source>
   
  
 
  



Use of Java2D on SWT or Draw2D graphical context

   <source lang="java">

/*

* -----------------------------------------------------------------------------
* (c) Copyright IBM Corp. 2004 All rights reserved.
* 
* The sample program(s) is/are owned by International Business Machines
* Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and
* licensed, not sold.
* 
* You may copy, modify, and distribute this/these sample program(s) in any form
* without payment to IBM, for any purpose including developing, using,
* marketing or distributing programs that include or are derivative works of
* the sample program(s).
* 
* The sample program(s) is/are provided to you on an "AS IS" basis, without
* warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do
* not allow for the exclusion or limitation of implied warranties, so the above
* limitations or exclusions may not apply to you. IBM shall not be liable for
* any damages you suffer as a result of using, modifying or distributing the
* sample program(s) or its/their derivatives.
* 
* Each copy of any portion of this/these sample program(s) or any derivative
* work, must include the above copyright notice and disclaimer of warranty.
* 
* -----------------------------------------------------------------------------
*/

import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class SWTTest {

 public static void main(String[] args) {
   Display display = new Display();
   Shell shell = new Shell(display);
   shell.setSize(350, 350);
   shell.setLayout(new GridLayout());
   Canvas canvas = new Canvas(shell, SWT.NO_BACKGROUND);
   GridData data = new GridData(GridData.FILL_BOTH);
   canvas.setLayoutData(data);
   final Graphics2DRenderer renderer = new Graphics2DRenderer();
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       Point controlSize = ((Control) e.getSource()).getSize();
       GC gc = e.gc; // gets the SWT graphics context from the event
       renderer.prepareRendering(gc); // prepares the Graphics2D
       // renderer
       // gets the Graphics2D context and switch on the antialiasing
       Graphics2D g2d = renderer.getGraphics2D();
       g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
           RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
       // paints the background with a color gradient
       g2d.setPaint(new GradientPaint(0.0f, 0.0f,
           java.awt.Color.yellow, (float) controlSize.x,
           (float) controlSize.y, java.awt.Color.white));
       g2d.fillRect(0, 0, controlSize.x, controlSize.y);
       // draws rotated text
       g2d.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD,
           16));
       g2d.setColor(java.awt.Color.blue);
       g2d.translate(controlSize.x / 2, controlSize.y / 2);
       int nbOfSlices = 18;
       for (int i = 0; i < nbOfSlices; i++) {
         g2d.drawString("Angle = " + (i * 360 / nbOfSlices)
             + "\u00B0", 30, 0);
         g2d.rotate(-2 * Math.PI / nbOfSlices);
       }
       // now that we are done with Java2D, renders Graphics2D
       // operation
       // on the SWT graphics context
       renderer.render(gc);
       // now we can continue with pure SWT paint operations
       gc.drawOval(0, 0, controlSize.x, controlSize.y);
     }
   });
   shell.open();
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch())
       display.sleep();
   }
   display.dispose();
   renderer.dispose();
   System.exit(0);
 }

} /*

* -----------------------------------------------------------------------------
* (c) Copyright IBM Corp. 2004 All rights reserved.
* 
* The sample program(s) is/are owned by International Business Machines
* Corporation or one of its subsidiaries ("IBM") and is/are copyrighted and
* licensed, not sold.
* 
* You may copy, modify, and distribute this/these sample program(s) in any form
* without payment to IBM, for any purpose including developing, using,
* marketing or distributing programs that include or are derivative works of
* the sample program(s).
* 
* The sample program(s) is/are provided to you on an "AS IS" basis, without
* warranty of any kind. IBM HEREBY EXPRESSLY DISCLAIMS ALL WARRANTIES, EITHER
* EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Some jurisdictions do
* not allow for the exclusion or limitation of implied warranties, so the above
* limitations or exclusions may not apply to you. IBM shall not be liable for
* any damages you suffer as a result of using, modifying or distributing the
* sample program(s) or its/their derivatives.
* 
* Each copy of any portion of this/these sample program(s) or any derivative
* work, must include the above copyright notice and disclaimer of warranty.
* 
* -----------------------------------------------------------------------------
*/

/**

* Helper class allowing the use of Java2D on SWT or Draw2D graphical context.
* 
* @author Yannick Saillet
*/

class Graphics2DRenderer {

 private static final PaletteData PALETTE_DATA = new PaletteData(0xFF0000,
     0xFF00, 0xFF);
 private BufferedImage awtImage;
 private Image swtImage;
 private ImageData swtImageData;
 private int[] awtPixels;
 /** RGB value to use as transparent color */
 private static final int TRANSPARENT_COLOR = 0x123456;
 /**
  * Prepare to render on a SWT graphics context.
  */
 public void prepareRendering(GC gc) {
   org.eclipse.swt.graphics.Rectangle clip = gc.getClipping();
   prepareRendering(clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Prepare to render on a Draw2D graphics context.
  */
 public void prepareRendering(org.eclipse.draw2d.Graphics graphics) {
   org.eclipse.draw2d.geometry.Rectangle clip = graphics
       .getClip(new org.eclipse.draw2d.geometry.Rectangle());
   prepareRendering(clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Prepare the AWT offscreen image for the rendering of the rectangular
  * region given as parameter.
  */
 private void prepareRendering(int clipX, int clipY, int clipW, int clipH) {
   // check that the offscreen images are initialized and large enough
   checkOffScreenImages(clipW, clipH);
   // fill the region in the AWT image with the transparent color
   java.awt.Graphics awtGraphics = awtImage.getGraphics();
   awtGraphics.setColor(new java.awt.Color(TRANSPARENT_COLOR));
   awtGraphics.fillRect(clipX, clipY, clipW, clipH);
 }
 /**
  * Returns the Graphics2D context to use.
  */
 public Graphics2D getGraphics2D() {
   if (awtImage == null)
     return null;
   return (Graphics2D) awtImage.getGraphics();
 }
 /**
  * Complete the rendering by flushing the 2D renderer on a SWT graphical
  * context.
  */
 public void render(GC gc) {
   if (awtImage == null)
     return;
   org.eclipse.swt.graphics.Rectangle clip = gc.getClipping();
   transferPixels(clip.x, clip.y, clip.width, clip.height);
   gc.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height, clip.x,
       clip.y, clip.width, clip.height);
 }
 /**
  * Complete the rendering by flushing the 2D renderer on a Draw2D graphical
  * context.
  */
 public void render(org.eclipse.draw2d.Graphics graphics) {
   if (awtImage == null)
     return;
   org.eclipse.draw2d.geometry.Rectangle clip = graphics
       .getClip(new org.eclipse.draw2d.geometry.Rectangle());
   transferPixels(clip.x, clip.y, clip.width, clip.height);
   graphics.drawImage(swtImage, clip.x, clip.y, clip.width, clip.height,
       clip.x, clip.y, clip.width, clip.height);
 }
 /**
  * Transfer a rectangular region from the AWT image to the SWT image.
  */
 private void transferPixels(int clipX, int clipY, int clipW, int clipH) {
   int step = swtImageData.depth / 8;
   byte[] data = swtImageData.data;
   awtImage.getRGB(clipX, clipY, clipW, clipH, awtPixels, 0, clipW);
   for (int i = 0; i < clipH; i++) {
     int idx = (clipY + i) * swtImageData.bytesPerLine + clipX * step;
     for (int j = 0; j < clipW; j++) {
       int rgb = awtPixels[j + i * clipW];
       for (int k = swtImageData.depth - 8; k >= 0; k -= 8) {
         data[idx++] = (byte) ((rgb >> k) & 0xFF);
       }
     }
   }
   if (swtImage != null)
     swtImage.dispose();
   swtImage = new Image(Display.getDefault(), swtImageData);
 }
 /**
  * Dispose the resources attached to this 2D renderer.
  */
 public void dispose() {
   if (awtImage != null)
     awtImage.flush();
   if (swtImage != null)
     swtImage.dispose();
   awtImage = null;
   swtImageData = null;
   awtPixels = null;
 }
 /**
  * Ensure that the offscreen images are initialized and are at least as
  * large as the size given as parameter.
  */
 private void checkOffScreenImages(int width, int height) {
   int currentImageWidth = 0;
   int currentImageHeight = 0;
   if (swtImage != null) {
     currentImageWidth = swtImage.getImageData().width;
     currentImageHeight = swtImage.getImageData().height;
   }
   // if the offscreen images are too small, recreate them
   if (width > currentImageWidth || height > currentImageHeight) {
     dispose();
     width = Math.max(width, currentImageWidth);
     height = Math.max(height, currentImageHeight);
     awtImage = new BufferedImage(width, height,
         BufferedImage.TYPE_INT_ARGB);
     swtImageData = new ImageData(width, height, 24, PALETTE_DATA);
     swtImageData.transparentPixel = TRANSPARENT_COLOR;
     awtPixels = new int[width * height];
   }
 }

}


 </source>
   
  
 
  



Utility methods for drawing graphics

   <source lang="java">

//Send questions, comments, bug reports, etc. to the authors: //Rob Warner (rwarner@interspatial.ru) //Robert Harris (rbrt_harris@yahoo.ru) import org.eclipse.swt.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.Display; /**

* This class contains utility methods for drawing graphics
*/

public class GraphicsUtils {

 /**
  * Draws text vertically (rotates plus or minus 90 degrees). Uses the current
  * font, color, and background.
*
*
Styles:
*
UP, DOWN
*
  * 
  * @param string the text to draw
  * @param x the x coordinate of the top left corner of the drawing rectangle
  * @param y the y coordinate of the top left corner of the drawing rectangle
  * @param gc the GC on which to draw the text
  * @param style the style (SWT.UP or SWT.DOWN)
*

* Note: Only one of the style UP or DOWN may be specified. *

  */
 public static void drawVerticalText(String string, int x, int y, GC gc,
     int style) {
   // Get the current display
   Display display = Display.getCurrent();
   if (display == null) SWT.error(SWT.ERROR_THREAD_INVALID_ACCESS);
   // Determine string"s dimensions
   FontMetrics fm = gc.getFontMetrics();
   Point pt = gc.textExtent(string);
   // Create an image the same size as the string
   Image stringImage = new Image(display, pt.x, pt.y);
   // Create a GC so we can draw the image
   GC stringGc = new GC(stringImage);
   // Set attributes from the original GC to the new GC
   stringGc.setForeground(gc.getForeground());
   stringGc.setBackground(gc.getBackground());
   stringGc.setFont(gc.getFont());
   // Draw the text onto the image
   stringGc.drawText(string, 0, 0);
   // Draw the image vertically onto the original GC
   drawVerticalImage(stringImage, x, y, gc, style);
   // Dispose the new GC
   stringGc.dispose();
   // Dispose the image
   stringImage.dispose();
 }
 /**
  * Draws an image vertically (rotates plus or minus 90 degrees)
*
*
Styles:
*
UP, DOWN
*
  * 
  * @param image the image to draw
  * @param x the x coordinate of the top left corner of the drawing rectangle
  * @param y the y coordinate of the top left corner of the drawing rectangle
  * @param gc the GC on which to draw the image
  * @param style the style (SWT.UP or SWT.DOWN)
*

* Note: Only one of the style UP or DOWN may be specified. *

  */
 public static void drawVerticalImage(Image image, int x, int y, GC gc, int style) {
   // Get the current display
   Display display = Display.getCurrent();
   if (display == null) SWT.error(SWT.ERROR_THREAD_INVALID_ACCESS);
   // Use the image"s data to create a rotated image"s data
   ImageData sd = image.getImageData();
   ImageData dd = new ImageData(sd.height, sd.width, sd.depth, sd.palette);
   // Determine which way to rotate, depending on up or down
   boolean up = (style & SWT.UP) == SWT.UP;
   // Run through the horizontal pixels
   for (int sx = 0; sx < sd.width; sx++) {
     // Run through the vertical pixels
     for (int sy = 0; sy < sd.height; sy++) {
       // Determine where to move pixel to in destination image data
       int dx = up ? sy : sd.height - sy - 1;
       int dy = up ? sd.width - sx - 1 : sx;
       // Swap the x, y source data to y, x in the destination
       dd.setPixel(dx, dy, sd.getPixel(sx, sy));
     }
   }
   // Create the vertical image
   Image vertical = new Image(display, dd);
   // Draw the vertical image onto the original GC
   gc.drawImage(vertical, x, y);
   // Dispose the vertical image
   vertical.dispose();
 }
 /**
  * Creates an image containing the specified text, rotated either plus or minus
  * 90 degrees.
*
*
Styles:
*
UP, DOWN
*
  * 
  * @param text the text to rotate
  * @param font the font to use
  * @param foreground the color for the text
  * @param background the background color
  * @param style direction to rotate (up or down)
  * @return Image
*

* Note: Only one of the style UP or DOWN may be specified. *

  */
 public static Image createRotatedText(String text, Font font, Color foreground,
     Color background, int style) {
   // Get the current display
   Display display = Display.getCurrent();
   if (display == null) SWT.error(SWT.ERROR_THREAD_INVALID_ACCESS);
   // Create a GC to calculate font"s dimensions
   GC gc = new GC(display);
   gc.setFont(font);
   // Determine string"s dimensions
   FontMetrics fm = gc.getFontMetrics();
   Point pt = gc.textExtent(text);
   // Dispose that gc
   gc.dispose();
   // Create an image the same size as the string
   Image stringImage = new Image(display, pt.x, pt.y);
   // Create a gc for the image
   gc = new GC(stringImage);
   gc.setFont(font);
   gc.setForeground(foreground);
   gc.setBackground(background);
   // Draw the text onto the image
   gc.drawText(text, 0, 0);
   // Draw the image vertically onto the original GC
   Image image = createRotatedImage(stringImage, style);
   // Dispose the new GC
   gc.dispose();
   // Dispose the horizontal image
   stringImage.dispose();
   // Return the rotated image
   return image;
 }
 /**
  * Creates a rotated image (plus or minus 90 degrees)
*
*
Styles:
*
UP, DOWN
*
  * 
  * @param image the image to rotate
  * @param style direction to rotate (up or down)
  * @return Image
*

* Note: Only one of the style UP or DOWN may be specified. *

  */
 public static Image createRotatedImage(Image image, int style) {
   // Get the current display
   Display display = Display.getCurrent();
   if (display == null) SWT.error(SWT.ERROR_THREAD_INVALID_ACCESS);
   // Use the image"s data to create a rotated image"s data
   ImageData sd = image.getImageData();
   ImageData dd = new ImageData(sd.height, sd.width, sd.depth, sd.palette);
   // Determine which way to rotate, depending on up or down
   boolean up = (style & SWT.UP) == SWT.UP;
   // Run through the horizontal pixels
   for (int sx = 0; sx < sd.width; sx++) {
     // Run through the vertical pixels
     for (int sy = 0; sy < sd.height; sy++) {
       // Determine where to move pixel to in destination image data
       int dx = up ? sy : sd.height - sy - 1;
       int dy = up ? sd.width - sx - 1 : sx;
       // Swap the x, y source data to y, x in the destination
       dd.setPixel(dx, dy, sd.getPixel(sx, sy));
     }
   }
   // Create the vertical image
   return new Image(display, dd);
 }

}


 </source>
   
  
 
  



XOR

   <source lang="java">

/******************************************************************************

* All Right Reserved. 
* Copyright (c) 1998, 2004 Jackwind Li Guojie
* 
* Created on 2004-4-19 15:31:18 by JACK
* $Id$
* 
*****************************************************************************/

import org.eclipse.swt.SWT; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; public class XOR {

 Display display = new Display();
 Shell shell = new Shell(display);
 public XOR() {
   shell.setLayout(new FillLayout());
   final Canvas canvas = new Canvas(shell, SWT.NULL);
   canvas.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
   
   canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
       e.gc.setXORMode(true);
       
       e.gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
       e.gc.fillOval(60, 10, 100, 100); // Top 
       
       e.gc.setBackground(display.getSystemColor(SWT.COLOR_RED));
       e.gc.fillOval(10, 60, 120, 120); // left bottom    
       
       e.gc.setBackground(display.getSystemColor(SWT.COLOR_BLUE));
       e.gc.fillOval(110, 60, 100, 100); // right bottom    
       
     }
   });
   
   shell.setSize(300, 220);
   shell.open();
   //textUser.forceFocus();
   // Set up the event loop.
   while (!shell.isDisposed()) {
     if (!display.readAndDispatch()) {
       // If no more entries in event queue
       display.sleep();
     }
   }
   display.dispose();
 }
 private void init() {
 }
 public static void main(String[] args) {
   new XOR();
 }

}


 </source>