Clearing Buffered Canvas

Hi,
I've searched in google, on this forum and on JavaRanch Big Moose Saloon for the answer to this question but as of yet I can't find an answer.
I'm attempting to clear a JPanel canvas. Repaint() simply doesn't work so I've tried this,
public void clearImage()
Rectangle d = canvas.getBounds();                               //get canvas dimension
BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);  //create new buffered image of canvas
Graphics2D g = bi.createGraphics();  //get canvas objects
g.setColor(Color.white);  //set colour to white
g.drawRect(10, 160, 210, 70);   //draw rectangle over buffered image.
}Although the code compiles fine, when I run this method, nothing happens. There are no errors throw. Simply nothing happens. I've also attempted the following code;
public void clearImage()
g = jPanel1.getGraphics();
g.setColor(Color.white);
g.fillRect(10, 160, 210, 70);
}which although it does cover the canvas with a white rectangle, once I click in the rectangle again, it removes it, and shows what was previously drawn in it.
If i try g = canvas.getGraphics(); on the top line, nothing happens again.
Any step in the right direction or an explanation of why the top method wont work would be appreciated greatly.
Thanks
N

Thankyou very much for the replies, they have helped out in understanding why the methods won't work.
However, I am still stuck on this. I thought that g.drawImage(bi, 0, 0, this); would draw the buffered image, yet nothing happens again.
At this point I'm getting really confused with images and graphics g and buffered images.
Here is my code so you can see how wrong I am going....
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class DrawPad extends JFrame implements ActionListener {
   private OutputScreen canvas;
   private javax.swing.JTextField barcode;
   private javax.swing.JButton exit;
   private javax.swing.JButton clearBarcode;
   private javax.swing.JButton clearCanvas;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JLabel jLabel2;
   private javax.swing.JLabel jLabel3;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JButton save;
   public DrawPad() {
     jPanel1 = new javax.swing.JPanel();
        barcode = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        exit = new javax.swing.JButton();
     canvas = new OutputScreen(Color.black);
     clearCanvas = new javax.swing.JButton();
     clearCanvas.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent e)
            clearImage();
     clearBarcode = new javax.swing.JButton();
     clearBarcode.addActionListener(new java.awt.event.ActionListener()
        public void actionPerformed(java.awt.event.ActionEvent e)
             barcode.setText("");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
     jPanel1.setLayout(null);
     getContentPane().add(jPanel1);
     canvas.setLayout(null);
     canvas.setBackground(new java.awt.Color(255, 255, 255));
        canvas.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
        jPanel1.add(canvas);
        canvas.setBounds(10, 160, 210, 70);
        jPanel1.add(barcode);
        barcode.setBounds(20, 70, 180, 50);
        jLabel1.setText("Scan Package");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 40, 180, 20);
        jLabel2.setText("Sign Here Please");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(10, 140, 210, 20);
        save.setText("Save");
        jPanel1.add(save);
        save.setBounds(70, 240, 59, 25);
            exit.setIcon(new javax.swing.ImageIcon("windows\\start menu\\programs\\CrE-ME\\images\\redbutton.gif"));
        exit.setBorder(null);
        exit.setOpaque(false);
        jPanel1.add(exit);
        exit.setBounds(160, 10, 25, 25);
     clearBarcode.setText("Clear");
     jPanel1.add(clearBarcode);
     clearBarcode.setBounds(160, 120, 59, 25);
     clearCanvas.setText("Clear");
     jPanel1.add(clearCanvas);
     clearCanvas.setBounds(150, 230, 59, 25);
        //jPanel1.add(jLabel3);
        //jLabel3.setBounds(0, -5, 240, 280);
        getContentPane().add(jPanel1);
        jPanel1.setBounds(0, 0, 277, 344);
     addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                //exitForm(evt);
     this.setSize(new Dimension(240, 300));
     setVisible(true);
   ///////Method I am having problems with ////////////////////////////////////
   public void clearImage()
               Rectangle d = canvas.getBounds();                              
               BufferedImage bi = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB); 
               Graphics g = bi.createGraphics();
               g.setColor(Color.white); 
               g.drawRect(10, 160, 210, 70); 
               g.drawImage(bi, 0, 0, this);
     public void actionPerformed(ActionEvent e) {
      String s = e.getActionCommand();
   public static void main(String[] args) {
      new DrawPad().setVisible(true);
class OutputScreen extends JPanel {
   private BufferedImage buf;
   private Color currentColor;
   private Graphics2D g2;
   private Point lastPoint;
   public OutputScreen(Color initialColor) {
      setPreferredSize(new Dimension(240, 300));
      buf = new BufferedImage(240, 300, BufferedImage.TYPE_INT_RGB);
      g2 = buf.createGraphics();
      g2.setColor(Color.white);
      g2.fillRect(0, 0, 240, 300);
      g2.setColor(initialColor); 
      addMouseListener(new MouseAdapter()
public void mousePressed(MouseEvent e) {
            moveto(e.getPoint());  // Move to click position
            requestFocus();        // Take keyboard focus
      addMouseMotionListener(new MouseMotionAdapter() {
         public void mouseDragged(MouseEvent e) {
            Point p = e.getPoint();
            lineto(p); // Draw to mouse position
            moveto(p);
   public void setColor(Color c){
      g2.setColor(c);
   public void paintComponent(Graphics g){
      super.paintComponent(g);
      g.drawImage(buf, 0, 0,this);
   private void moveto(Point pt){
      lastPoint = pt;
   private void lineto(Point pt){
      g2.drawLine(lastPoint.x, lastPoint.y, pt.x, pt.y);
      repaint();
}Again thankyou for the replies you have already given, I really appreciate them.
Wishing everyone a Happy New Year!
N

Similar Messages

  • Alternative to Double-Buffered Canvas

    I am working on a program in which I use a double-buffered Canvas inside a JScrollPane. The problem is that the Canvas draws over the scrollbars. I have tried extending JComponent, JPanel, JApplet, and Component instead of Canvas, and none of them are double buffered. Here is the code I used to debug this problem:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Test implements  Runnable
         JFrame f;
         JScrollPane scroller;
         JPanel panel;
         TestCanvas canvas;
         Thread runner;
         BufferStrategy strategy;
         public static void main (String[] args) {
              Test app = new Test();
              app.init();
         public void init() {
              f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              panel = new JPanel();
              canvas = new TestCanvas();
              panel.add(canvas);
              scroller = new JScrollPane(panel);
              scroller.setWheelScrollingEnabled(true);
              f.getContentPane().add(scroller);
              f.pack();
              f.setSize(300,300);
              f.setVisible(true);
              canvas.createBufferStrategy(2);
              strategy = canvas.getBufferStrategy();
              runner = new Thread(this);
              runner.run();
         public void run() {
              int x = 0;
              while(x != 65536) {
                   Graphics2D g = (Graphics2D)strategy.getDrawGraphics().create();
                   g.setColor(new Color(x%256,0,0));
                   g.fill(new Ellipse2D.Double(0,0,600,600));
                   strategy.show();
                   x++;
    }Any suggestions?

    The main culprit is that you are mixing AWT components with Swing ones.
    In addition, your are doing so many of useless things and wrong things in your code.
    Swing components are defaulted for using double-buffering.
    See: http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    Try and study this code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Fox1229{
      JFrame f;
      JScrollPane scroller;
      TestCanvas canvas;
      int x;
      Timer t;
      public static void main (String[] args) {
        Fox1229 app = new Fox1229();
        app.init();
      public void init() {
        x = 0;
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new TestCanvas();
        scroller = new JScrollPane(canvas);
        scroller.setWheelScrollingEnabled(true);
        f.getContentPane().add(scroller, BorderLayout.CENTER);
        f.setSize(300, 300);
        f.setVisible(true);
        t = new Timer(50, new ActionListener(){
          public void actionPerformed(ActionEvent e){
            canvas.setOc(new Color(x % 256, 0, 0));
            canvas.repaint();
            if (++x == 1024){
              t.stop();
        t.start();
    class TestCanvas extends JPanel{
      Color oc;
      public TestCanvas (){
        oc = new Color(0, 0, 0);
      public void setOc(Color c){
        oc = c;
      public Dimension getPreferredSize(){
        return new Dimension(600, 600);
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle(0, 0, 600, 600));
        g2d.setColor(oc);
        g2d.fill(new Ellipse2D.Double(0, 0, 600, 600));
    }

  • Clear buffers before calling BAPI 'BAPI_CUSTOMERQUOTATION_CHANGE'

    When i am calling BAPI_CUSTOMERQUOTATION_CHANGE in a program in which table buffers are used then it is giving me error  'Enter the document number'. But when the same BAPI with same data is run in a test program it runs successfully. I think some of the buffers are not cleared which are giving problem in BAPI. is there any FM to clear all buffers before calling a BAPI.

    Write/Enter  the Transaction
    /$sync
    it will reset the Buffers.
    Kanagaraja L

  • FCP 7, viewer clear, but canvas and export blurry

    Started with screen recordings provided to me that made using quicktime 10
    took quicktime 10 screen recordings and converted them to prores422 HQ in compressor (settings from compressor below)
    imported into FCP 7.
    They look great in viewer, reasonably sharp and crisp, but them very blurry in canvas and when I export to quicktime movie (not using quicktime conversion). Been using FCP 7 a couple years but my knowledge in many aspects is sub professional.
    Tried creating a new sequence to get the sequence to match the settings of the quicktime prores422 screen capture movies but to no avail. The settings of the sequence are not the same as the screen capture movies...I even tried to change the sequence settings but no luck (then exited FCP without saving so as not to screw anything up).
    Im probably breaking basic rules here...any help is greatly appreciated.
    Thank you!!!
    Compressor settings for file conversion above:
    Name: Apple ProRes 422 for Interlaced material (High Quality)
    Description: Apple ProRes 422 10-bit video with audio pass-through. Settings based off the source resolution and frame-rate.
    File Extension: mov
    Estimated size: 412.09 MB
    Audio: multi-track passthrough
    Video Encoder
    Format: QT
    Width: (100% of source)
    Height: (100% of source)
    Selected: 1440 x 900
    Pixel aspect ratio: Square
    Crop: None
    Padding: None
    Frame rate: (100% of source)
    Selected: 15.002
    Frame Controls: Automatically selected: Off
    Codec Type: Apple ProRes 422 (HQ)
    Multi-pass: Off, frame reorder: Off
    Automatic gamma correction
    Progressive
    Pixel depth: 24
    Spatial quality: 50
    Min. Spatial quality: 0
    Temporal quality: 0
    Min. temporal quality: 0

    Here is additional information on the problem.
    My sequence includes mostly screen captures, but also some other video (settings below) and some JPEGs.  The other video and the JPEGs look fine...both in canvas and when I export sequence to quicktime.  The screen captures look terrible...text is very blurry.  Same screen captures look fine in my viewer, just goes awry when in canvas and export.
    Format of screen capture clips (quicktime 10 screen capture > compressor prores 422 HQ):
    1440x900, apprle prores 422 HQ, data rate 5.6 MB/S, pixel aspect square, field dominance none, composite normal.  Started with 4 files of the screen capture from compressor, then edited them into many little pieces in FCP...the size of those files post compressor are around 2GB each.
    The sequence (by default) had settings of:
    frame size: 720x480 NTSC DV 3:2
    pixel aspect ratio: NTSC - CCIR 601 / DV 720x480
    field dominance lower(even)
    quicktime compressor settings: apple prores 422 LT
    Vast majority of clips are the same as screen capture clips.  But just in case its part of the problem, I have also have a couple video clips of that have settings:
    frame size:  720x480
    compressor:  DV/DVCPRO - NTSC
    data rate 3.6mb/s
    pixel aspect: NTSC - CCIR 601
    field dominance: Lower/even
    also have a couple JPEGs, their settings are:
    frame size 2500x2084
    compressor: photo-jpeg
    field dominance: none
    Thank you!!!  I've been using final cut a while, but don't think I would have gotten anywhere without the help and generosity of people that are way beyond my knowledge and skills.  I am happy to provide any more info.  I really appreciate it.

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • Change origin of canvas

    hey, i have a canvas that positions itself in the middle of the screen with two lines (x and y axis). the problem is that i want to be able to move the origin, which then draws the axis again.
    thanks
    Pedge
    // GCanvas.java
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This class extends the canvas class to include the input and drawing of a polygon
    * @author Geoff Hobson
    * @version 1.1 (24 Nov 99)
    class GCanvas extends Canvas
    * the polygon object associated with this canvas.
    private GPolygon polygon;
    * indicates whether currently in process of colecting the vertices of a polygon.
    private boolean building = false;
    * the size of one pixel in the logical coordinates of the polygon - the scaling factor.
    float pixelSize;
    * the screen x coordinate of the logical origin - screen x position of y-axis.
    int centerX;
    * the screen y coordinate of the logical origin - screen y position of x-axis.
    int centerY;
    * the radius of the circle around the start point,
    * a mouse press anywhere in this circle will be treated as selecting the centre point.
    private int circleSize = 3;
    * Constructs a GCanvas and associates it with the given Polygon poly.
    * @param poly the polygon object which is to be drawn and manipulated
    GCanvas(GPolygon poly)
    polygon = poly;
    addMouseListener
    (new MouseAdapter()
    { public void mousePressed(MouseEvent evt)
    pointSelected(evt.getX(), evt.getY());
    ); // end of new MouseAdapter
    setBackground(Color.gray);
    private int cX, cY;
    * clears the canvas and sets it ready for the input of a new polygon.
    public void newPoly()
    building = true;
    setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
    repaint();
    * The action to be performed when a point is selected by a mouse press.
    * @param x the x coordinate of the selected point
    * @param y the y coordinate of the selected point
    private void pointSelected(int x, int y)
    if (building)
    addVertex(x, y);
    * Add a new vertex to the polygon object
    * @param x the x coordinate of the new vertex
    * @param y the y coordinate of the new vertex
    private void addVertex(int x, int y)
    if (polygon.size() == 0)
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add first vertex to a polygon
    else
    Point2D v0 = polygon.getVertex(0);
    int dx = x - iX(v0.x), dy = y - iY(v0.y);
    if (dx * dx + dy * dy < circleSize * circleSize)
    {    // mouse in circle around first vertex
    polygon.closePolygon(); // the polygon has been closed
    building = false;
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    else
    polygon.addVertex(new Point2D(fX(x), fY(y))); // add an other vertex to polygon
    repaint();
    * Converts logical to screen x coordinate
    * @param x the logical x coordinate
    * @return the screen x coordinate
    int iX(float x)
    return Math.round(centerX + x/pixelSize);
    * Converts logical to screen y coordinate
    * @param x the logical y coordinate
    * @return the screen y coordinate
    int iY(float y)
    return Math.round(centerY - y/pixelSize);
    * Converts screen to logical x coordinate
    * @param x the screen x coordinate
    * @return the logical x coordinate
    float fX(int x)
    return (x - centerX) * pixelSize;
    * Converts screen to logical y coordinate
    * @param x the screen y coordinate
    * @return the logical y coordinate
    float fY(int y)
    return (centerY - y) * pixelSize;
    * Paints the canvas with current state of polygon
    * @param g the graphic context for the paint method
    public void paint(Graphics g)
    // initialise a blank canvas and draw axes etc
    int maxX = getSize().width - 1; // get size of screen
    int maxY = getSize().height - 1;
    float rWidth = polygon.logicalWidth(); // get logical size of polygon
    float rHeight = polygon.logicalHeight();
    pixelSize = Math.max(rWidth/maxX, rHeight/maxY); // calculate scaling factor
    centerX = maxX/2; // calculate position of axes
    centerY = maxY/2;
    int left = iX(-rWidth/2); // calculate edges of logical polygon
    int right = iX(rWidth/2);
    int bottom = iY(-rHeight/2);
    int top = iY(rHeight/2);
    // draw white rectangle for logical polygon
    g.setColor(Color.white);
    g.fillRect(left, top, right - left+1, bottom - top+1);
    // draw frame around logical polygon rectangle
    g.setColor(Color.darkGray);
    g.drawRect(left, top, right - left, bottom - top);
    g.setColor(Color.lightGray);
    g.drawLine(left,centerY, right,centerY); // draw x axis
    g.drawLine(centerX,top, centerX,bottom); // draw y-axis
    // draw current state of the polygon
    int n = polygon.size();
    if (n == 0) return; // if there are no vertices
    Point2D A, B;
    A = (polygon.getVertex(0));
    // Show tiny circle around first vertex:
    g.setColor(Color.red);
    if (!polygon.isClosed())
    g.drawOval(iX(A.x)-circleSize, iY(A.y)-circleSize, circleSize*2, circleSize*2);
    // draw the polygon
    g.setColor(Color.blue);
    for (int i=1; i<n; i++)
    B = (polygon.getVertex(i));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    A = B;
    if (polygon.isClosed()) // draw side from last to first vertex
    B = (polygon.getVertex(0));
    g.drawLine(iX(A.x), iY(A.y), iX(B.x), iY(B.y));
    } // end of paint
    } // end of class GCanvas

    How about declaring changing centerx and centery in the constructor?

  • Clear BPS variables values

    I wrote an ABAP program to clear BPS variables values defined for the user.
          DATA:
          lr_variable TYPE REF TO cl_sem_variable.
    * Get variable instance
          CALL METHOD cl_sem_variable=>get_instance
            EXPORTING
              i_area       = I_AREA
              i_variable   = 'ZPVDEP' "z_v_var
            RECEIVING
              rr_variable  = lr_variable
            EXCEPTIONS
              not_existing = 1
              OTHERS     = 2.
          IF sy-subrc <> 0.
    * do s.th., eg send a message
            EXIT.
          ENDIF.
    * delete the restrictions
          CALL METHOD lr_variable->set_user_restriction
            EXPORTING
              i_user   = sy-uname
              i_delete = 'X'
            EXCEPTIONS
              failed   = 1
              OTHERS   = 2.
    In BPS0:
    1. i restrict the variable with some values
    2. execute planning function to clear the variable values
        But the restriction remains.
    3. When i do /nBPS0 the variable restriction clears
    As far as i understand the problem is in buffer. How can i clear buffered values of the variable in ABAP program?
    i tried to call  method CL_SEM_VARIABLE=>RESET_BUFFER.
    but it doesn't work.
    Thanks

    Also i try such an ABAP code
          SELECT *
          FROM upc_var_cha_sel
          INTO CORRESPONDING FIELDS OF TABLE it_var_cha_sel
          WHERE    area    = I_AREA
               AND var     = ls_exitp-CHAVL
               AND varuser = sy-uname.
          IF sy-subrc = 0.
            DELETE upc_var_cha_sel FROM TABLE it_var_cha_sel.
            CALL FUNCTION 'DB_COMMIT'.
          ENDIF.
          REFRESH it_var_cha_sel.
          SELECT *
          FROM upc_var_cha_act
          INTO CORRESPONDING FIELDS OF TABLE it_var_cha_sel
          WHERE    area    = I_AREA
               AND var     = ls_exitp-CHAVL
               AND varuser = sy-uname.
          IF sy-subrc = 0.
            DELETE upc_var_cha_act FROM TABLE it_var_cha_sel.
            CALL FUNCTION 'DB_COMMIT'.
          ENDIF.
    But the problem is the same
    In BPS0:
    1. i restrict the variable with some values
    2. execute planning function to clear the variable values
    But the restriction remains.
    3. When i do /nBPS0 the variable restriction clears
    Thanks

  • Conversion from awt to Swing, colored list widget, and awt update() method

    Now that my Interactive Color Wheel program/applet is in Swing, I guess I should continue my previous thread in here from the AWT forum ("list widget with different colors for each list item?"):
    * list widget with different colors for each list item?
    My current issue involves two canvas (well, JPanel) refresh issues likely linked to double buffering. You can see them by running the following file with "java -jar SIHwheel.jar":
    * http://r0k.us/rock/Junk/SIHwheel.jar
    [edit add]
    (Heh, I just noticed Firefox and Chrome under Windows 7 will allow you to run thie .jar directly from the link. Cool.)
    [edit]
    If you don't trust me and would rather run it as an applet, use:
    * http://r0k.us/rock/Junk/SIHwheel.html
    (For some reason the first issue doesn't manifest when running as applet.)
    1) The canvas goes "wonky-white" when the user first clicks on the wheel. What is supposed to happen is simply the user sees another dot on the wheel for his new selected color. Forcing a complete redraw via any of the GUI buttons at the bottom sets things right. The canvas behaves itself from then on, at least until minimized or resized, at which point one needs to click a GUI button again. I'll be disabling resizing, but minimizing will still be allowed.
    2) A button image, and sometimes toolTip text, from an entirely different JPanel will appear in the ULC (0,0) of my canvas.
    Upon first running the new Swing version, I had thought everything was perfect. I soon realized though that my old AWT update() method was never getting called. The desired case when the user clicks somewhere on the wheel is that a new dot appears on his selected color. This usually allows them to see what colors have been viewed before. The old paint(), and now paintComponent(), clear the canvas, erasing all the previous dots.
    I soon learned that Swing does not call update(). I had been using it to intercept refresh events where only one of the components on my canvas needing updating. Most usefully, don't redraw the wheel (and forget the dots) when you don't need to. The way I chose to handle this is to slightly modify the update() to a boolean method. I renamed it partialOnly() and call it
    at the beginning of paintComponent(). If it returns true, paintComponent() itself returns, and no clearing of the canvas occurs.
    Since I first posted about these two issues, I've kludged-in a fix to #1. (The linked .jar file does not contain this kludge, so you can see the issue.) The kludge is included in the following code snippet:
        public void paintComponent(Graphics g)
            Rectangle ulc;
         if (font == null)  defineFont(g);
         // handle partial repaints of specific items
         if (partialOnly(g))  return;
            ...  // follow with the normal, full-canvas refresh
        private boolean partialOnly(Graphics g)
         boolean     imDone = true;
         if (resized > 0)  // this "if { }" clause is my kludge
         {   // should enter on 1 or 2
             imDone = false;
             resized += 1;     // clock thru two forced-full paints
             if (resized > 2)  resized = 0;
            if (wedgeOnly)
             putDotOnWheel(g);
                paintWedge(g);
             drawSnake(g);
             drawSatSnake(g);
             updateLumaBars(g);
                wedgeOnly = false;
              else if (wheelOnly)
                wheelOnly = false;
              else
                imDone = false;  // was paint() when method was update() in the AWT version
            return(imDone);
        }Forcing two initial full paintComponent()s does whatever magic the double-buffering infrastructure needs to avoid the "wonky-white" problem. This also happens on a minimize; I've disabled resizing other than minimization. Even though it works, I consider it a kludge.
    The second issue is not solved. All I can figure is that the double buffers are shared between the two JPanels, and the artifact buttons and toolTips at (0,0) are the result. I tried simply clearing the top twenty lines of the canvas when partialOnly() returns true, but for some reason that causes other canvas artifacting further down. And that was just a second kludge anyway.
    Sorry for being so long-winded. What is the right way to avoid these problems?
    -- Rich
    Edited by: RichF on Oct 15, 2010 8:43 PM

    Darryl, I'm not doing any custom double buffering. My goal was to simply replicate the functionality of awt's update() method. And yes, I have started with the Swing tutorial. I believe it was there that I learned update() is not part of the Swing infrastructure.
    Problem 1: I don't see the effect you describe (or I just don't understand the description)Piet, were you viewing the program (via the .jar) or the applet (via the .html)? For whatever reason, problem 1 does not manifest itself as an applet, only a program. FTR I'm running JDK/JRE 1.6 under Windows 7. As a program, just click anywhere in the wheel. The whole canvas goes wonky-white, and the wheel doesn't even show. If it happens, you'll understand. ;)
    Are you aware that repaint() can have a rectangle argument? And are you aware that the Graphics object has a clip depicting the area that will be affected by painting? You might use these for your partial painting.Yes and yes. Here is an enumeration of most of the update regions:
    enum AoI    // areas of interest
        LUMA_SNAKE, GREY_SNAKE, HUEBORHOOD, BULB_LABEL, LUMA_WEDGE,
        LAST_COLOR, BRIGHTNESS_BOX, INFO_BOX, VERSION,
        COLOR_NAME, EXACT_COLOR, LUMA_BUTTON, LUMA_BARS, GUI_INTENSITY,
        QUANTIZATION_ERROR
    }That list doesn't even include the large color intensity wedge to the right, nor the color wheel itself. I have a method that will return a Rectangle for any of the AoI's. One problem is that the wheel is a circle, and a containing rectangle will overlap with some of the other AoI's. I could build an infrastructure to handle this mess one clip region at a time, but I think it would add a lot of unnecessary complexity.
    I think the bigger picture is that, though it is now updated to Swing, some of the original 1998 design decisions are no longer relevant. Back then I was running Windows 98 on a single-core processor clocked at significantly less than 1 GHz. You could actually watch the canvas update itself. The color wheel alone fills over 1000 arcs, and the color intensity wedge has over 75 update regions of its own. While kind of interesting to watch, it's not 1998 any more. My multi-core processor runs at over 2 GHz, and my graphic card is way, way beyond anything that existed last century. Full canvas updates probably take less than 0.1 sec, and that is with double-buffering!
    So, I think you're right. Let the silly paintComponent() do it's thing unhindered. If I want to track old dots on the wheel, keep an array of Points, remembering maybe the last 10. As a final step in the repainting process, decide how many of those old dots to display, and do it.
    Thanks, guys, for being a sounding board.
    Oh, I'm moving forward on implementing the color list widget. I've already added a 3rd JPanel, which is a column to the left of the main paint canvas. It will contain 3 GUI items:
    1) the color list widget itself, initially sorted by name
    2) 3 radio buttons allowing user to resort the list by name, hue, or hex
    3) a hex-entry JTextField (which is all that is there at this very moment), allowing exact color request
    The color list widget will fill most of the column from the top, followed by the radio buttons, with hex-entry at bottom.
    For weeks I had in mind that I wanted a pop-up color list widget. Then you shared your ColorList class, and it was so obvious the list should just be there all the time. :)
    -- Rich

  • How can I use one motion controller to control two robotic independently?

    the help document says :
    Note  Configuring and clearing buffers is a processor-intensive operation on the motion controller that requires the allocation and deallocation of memory. You should configure and clear buffers only when motors are not moving and onboard programs are not running. For example, if you wish to execute three simultaneous contouring operations on axis 1, axis 2, and vector space 1 (with axes 3 and 4), you should first configure all three buffers before starting any of the operations. You can start the contour operations independently, and at different times, but should wait until all operations are complete before clearing any of the buffers.
    and i tried to conduct two contouring operation on two vector space. and tried to clear or configuring buffer for one vector when another one is still moving. so that i can start or end the movement at any time i want,and  it is ok.no error. but when i tried add a buffer  breakpoint output along with each vector movement. the bp doesn't work if the other vector is running . is there anyway to solve this problem.

    I think you've misunderstood what the dns attribute is for. The dns attribute returns the hostname of the client accessing your website, not the hostname of the website that linked to your website.
    For example, when someone using the Comcast ISP goes to a malicious website at example.com that loads images from your website at www.amigoo.net, the dns attribute will be something like "c-1-2-3-4.ca.comcast.net", not "example.com". ACLs are used for authentication and authorization of clients (not the websites those clients chose to visit), and they don't provide the functionality you're looking for.
    If I understand correctly, you want to prevent websites other than amigoo.net from linking to files in your d:/webserver/imat/pics_upload directory. You can achieve this adding the following lines to your obj.conf configuration file:
    <Object ppath="d:/webserver/imat/pics_upload/*">
    <Client referer="*~*amigoo.net">
    PathCheck fn="deny-existence"
    </Client>
    </Object>

  • How do I convert this Applet to launch from a JFrame instead??

       A simple program where the user can sketch curves and shapes in a
       variety of colors on a variety of background colors.  The user selects
       a drawing color form a pop-up menu at the top of the
       applet.  If the user clicks "Set Background", the background
       color is set to the current drawing color and the drawing
       area is filled with that color.  If the user clicks "Clear",
       the drawing area is just filled with the current background color.
       The user selects the shape to draw from another pop-up menu at the
       top of the applet.  The user can draw free-hand curves, straight
       lines, and one of six different types of shapes.
       The user's drawing is saved in an off-screen image, which is
       used to refresh the screen when repainting.  The picture is
       lost if the applet changes size, however.
       This file defines two classes, SimplePaint3,class, and
       class, SimplePaint3$Display.class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SimplePaint3 extends JApplet {
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
       public Insets getInsets() {
              // Specify how wide a border to leave around the edges of the applet.
          return new Insets(3,3,3,3);
       private class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display
    } // end class SimplePaint3

    Im quite the novice, how exactly do I go about doing that. What I did was to put both in diff files but I got errors saying that they cant find colorChoice, figureChoice in the Display class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Simple extends JFrame implements Display{
            // The main applet class simply sets up the applet.  Most of the
            // work is done in the Display class.
       JComboBox colorChoice, figureChoice;  // Pop-up menus, defined as instance
                                             // variables so that the Display
                                             // class can see them.
       public void init() {
          setBackground(Color.gray);
          getContentPane().setBackground(Color.gray);
          Display canvas = new Display();  // The drawing area.
          getContentPane().add(canvas,BorderLayout.CENTER);
          JPanel buttonBar = new JPanel();       // A panel to hold the buttons.
          buttonBar.setBackground(Color.gray);
          getContentPane().add(buttonBar, BorderLayout.SOUTH);
          JPanel choiceBar = new JPanel();       // A panel to hole the pop-up menus
          choiceBar.setBackground(Color.gray);
          getContentPane().add(choiceBar, BorderLayout.NORTH);
          JButton fill = new JButton("Set Background");  // The first button.
          fill.addActionListener(canvas);
          buttonBar.add(fill);
          JButton clear = new JButton("Clear");   // The second button.
          clear.addActionListener(canvas);
          buttonBar.add(clear);
          colorChoice = new JComboBox();  // The pop-up menu of colors.
          colorChoice.addItem("Black");
          colorChoice.addItem("Red");
          colorChoice.addItem("Green");
          colorChoice.addItem("Blue");
          colorChoice.addItem("Cyan");
          colorChoice.addItem("Magenta");
          colorChoice.addItem("Yellow");
          colorChoice.addItem("White");
          colorChoice.setBackground(Color.white);
          choiceBar.add(colorChoice);
          figureChoice = new JComboBox();  // The pop-up menu of shapes.
          figureChoice.addItem("Curve");
          figureChoice.addItem("Straight Line");
          figureChoice.addItem("Rectangle");
          figureChoice.addItem("Oval");
          figureChoice.addItem("RoundRect");
          figureChoice.addItem("Filled Rectangle");
          figureChoice.addItem("Filled Oval");
          figureChoice.addItem("Filled RoundRect");
          figureChoice.setBackground(Color.white);
          choiceBar.add(figureChoice);
       }  // end init()
    } // end class SimplePaint3
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Display extends JPanel
                  implements MouseListener, MouseMotionListener, ActionListener {
               // Nested class Display represents the drawing surface of the
               // applet.  It lets the user use the mouse to draw colored curves
               // and shapes.  The current color is specified by the pop-up menu
               // colorChoice.  The current shape is specified by another pop-up menu,
               // figureChoice.  (These are instance variables in the main class.)
               // The panel also listens for action events from buttons
               // named "Clear" and "Set Background".  The "Clear" button fills
               // the panel with the current background color.  The "Set Background"
               // button sets the background color to the current drawing color and
               // then clears.  These buttons are set up in the main class.
          private final static int
                      BLACK = 0,
                      RED = 1,            // Some constants to make
                      GREEN = 2,          // the code more readable.
                      BLUE = 3,           // These numbers code for
                      CYAN = 4,           // the different drawing colors.
                      MAGENTA = 5,
                      YELLOW = 6,
                      WHITE = 7;
          private final static int
                     CURVE = 0,
                     LINE = 1,
                     RECT = 2,               // Some constants that code
                     OVAL = 3,               // for the different types of
                     ROUNDRECT = 4,          // figure the program can draw.
                     FILLED_RECT = 5,
                     FILLED_OVAL = 6,
                     FILLED_ROUNDRECT = 7;
          /* Some variables used for backing up the contents of the panel. */
          Image OSI;  // The off-screen image (created in checkOSI()).
          int widthOfOSI, heightOfOSI;  // Current width and height of OSI.  These
                                        // are checked against the size of the applet,
                                        // to detect any change in the panel's size.
                                        // If the size has changed, a new OSI is created.
                                        // The picture in the off-screen image is lost
                                        // when that happens.
          /* The following variables are used when the user is sketching a
             curve while dragging a mouse. */
          private int mouseX, mouseY;   // The location of the mouse.
          private int prevX, prevY;     // The previous location of the mouse.
          private int startX, startY;   // The starting position of the mouse.
                                        // (Not used for drawing curves.)
          private boolean dragging;     // This is set to true when the user is drawing.
          private int figure;    // What type of figure is being drawn.  This is
                                 //    specified by the figureChoice menu.
          private Graphics dragGraphics;  // A graphics context for the off-screen image,
                                          // to be used while a drag is in progress.
          private Color dragColor;  // The color that is used for the figure that is
                                    // being drawn.
          Display() {
                 // Constructor.  When this component is first created, it is set to
                 // listen for mouse events and mouse motion events from
                 // itself.  The initial background color is white.
             addMouseListener(this);
             addMouseMotionListener(this);
             setBackground(Color.white);
          private void drawFigure(Graphics g, int shape, int x1, int y1, int x2, int y2) {
                // This method is called to do ALL drawing in this applet!
                // Draws a shape in the graphics context g.
                // The shape paramter tells what kind of shape to draw.  This
                // can be LINE, RECT, OVAL, ROUNTRECT, FILLED_RECT,
                // FILLED_OVAL, or FILLED_ROUNDRECT.  (Note that a CURVE is
                // drawn by drawing multiple LINES, so the shape parameter is
                // never equal to CURVE.)  For a LINE, a line is drawn from
                // the point (x1,y1) to (x2,y2).  For other shapes,  the
                // points (x1,y1) and (x2,y2) give two corners of the shape
                // (or of a rectangle that contains the shape).
             if (shape == LINE) {
                   // For a line, just draw the line between the two points.
                g.drawLine(x1,y1,x2,y2);
                return;
             int x, y;  // Top left corner of rectangle that contains the figure.
             int w, h;  // Width and height of rectangle that contains the figure.
             if (x1 >= x2) {  // x2 is left edge
                x = x2;
                w = x1 - x2;
             else {          // x1 is left edge
                x = x1;
                w = x2 - x1;
             if (y1 >= y2) {  // y2 is top edge
                y = y2;
                h = y1 - y2;
             else {          // y1 is top edge.
                y = y1;
                h = y2 - y1;
             switch (shape) {   // Draw the appropriate figure.
                case RECT:
                   g.drawRect(x, y, w, h);
                   break;
                case OVAL:
                   g.drawOval(x, y, w, h);
                   break;
                case ROUNDRECT:
                   g.drawRoundRect(x, y, w, h, 20, 20);
                   break;
                case FILLED_RECT:
                   g.fillRect(x, y, w, h);
                   break;
                case FILLED_OVAL:
                   g.fillOval(x, y, w, h);
                   break;
                case FILLED_ROUNDRECT:
                   g.fillRoundRect(x, y, w, h, 20, 20);
                   break;
          private void repaintRect(int x1, int y1, int x2, int y2) {
                // Call repaint on a rectangle that contains the points (x1,y1)
                // and (x2,y2).  (Add a 1-pixel border along right and bottom
                // edges to allow for the pen overhang when drawing a line.)
             int x, y;  // top left corner of rectangle that contains the figure
             int w, h;  // width and height of rectangle that contains the figure
             if (x2 >= x1) {  // x1 is left edge
                x = x1;
                w = x2 - x1;
             else {          // x2 is left edge
                x = x2;
                w = x1 - x2;
             if (y2 >= y1) {  // y1 is top edge
                y = y1;
                h = y2 - y1;
             else {          // y2 is top edge.
                y = y2;
                h = y1 - y2;
             repaint(x,y,w+1,h+1);
          private void checkOSI() {
               // This method is responsible for creating the off-screen image.
               // It should be called before using the OSI.  It will make a new OSI if
               // the size of the panel changes.
             if (OSI == null || widthOfOSI != getSize().width || heightOfOSI != getSize().height) {
                    // Create the OSI, or make a new one if panel size has changed.
                OSI = null;  // (If OSI already exists, this frees up the memory.)
                OSI = createImage(getSize().width, getSize().height);
                widthOfOSI = getSize().width;
                heightOfOSI = getSize().height;
                Graphics OSG = OSI.getGraphics();  // Graphics context for drawing to OSI.
                OSG.setColor(getBackground());
                OSG.fillRect(0, 0, widthOfOSI, heightOfOSI);
                OSG.dispose();
          public void paintComponent(Graphics g) {
               // Copy the off-screen image to the screen,
               // after checking to make sure it exists.  Then,
               // if a shape other than CURVE is being drawn,
               // draw it on top of the image from the OSI.
             checkOSI();
             g.drawImage(OSI, 0, 0, this);
             if (dragging && figure != CURVE) {
                g.setColor(dragColor);
                drawFigure(g,figure,startX,startY,mouseX,mouseY);
          public void actionPerformed(ActionEvent evt) {
                  // Respond when the user clicks on a button.  The
                  // command must be either "Clear" or "Set Background".
             String command = evt.getActionCommand();
             checkOSI();
             if (command.equals("Set Background")) {
                    // Set background color before clearing.
                    // Change the selected color so it is different
                    // from the background color.
                setBackground(getCurrentColor());
                if (colorChoice.getSelectedIndex() == BLACK)
                   colorChoice.setSelectedIndex(WHITE);
                else
                   colorChoice.setSelectedIndex(BLACK);
             Graphics g = OSI.getGraphics();
             g.setColor(getBackground());
             g.fillRect(0,0,getSize().width,getSize().height);
             g.dispose();
             repaint();
          private Color getCurrentColor() {
                   // Check the colorChoice menu to find the currently
                   // selected color, and return the appropriate color
                   // object.
             int currentColor = colorChoice.getSelectedIndex();
             switch (currentColor) {
                case BLACK:
                   return Color.black;
                case RED:
                   return Color.red;
                case GREEN:
                   return Color.green;
                case BLUE:
                   return Color.blue;
                case CYAN:
                   return Color.cyan;
                case MAGENTA:
                   return Color.magenta;
                case YELLOW:
                   return Color.yellow;
                default:
                   return Color.white;
          public void mousePressed(MouseEvent evt) {
                  // This is called when the user presses the mouse on the
                  // panel.  This begins a draw operation in which the user
                  // sketches a curve or draws a shape.  (Note that curves
                  // are handled differently from other shapes.  For CURVE,
                  // a new segment of the curve is drawn each time the user
                  // moves the mouse.  For the other shapes, a "rubber band
                  // cursor" is used.  That is, the figure is drawn between
                  // the starting point and the current mouse location.)
             if (dragging == true)  // Ignore mouse presses that occur
                 return;            //    when user is already drawing a curve.
                                    //    (This can happen if the user presses
                                    //    two mouse buttons at the same time.)
             prevX = startX = evt.getX();  // Save mouse coordinates.
             prevY = startY = evt.getY();
             figure = figureChoice.getSelectedIndex();
             dragColor = getCurrentColor();        
             dragGraphics = OSI.getGraphics();
             dragGraphics.setColor(dragColor);
             dragging = true;  // Start drawing.
          } // end mousePressed()
          public void mouseReleased(MouseEvent evt) {
                  // Called whenever the user releases the mouse button.
                  // If the user was drawing a shape, we make the shape
                  // permanent by drawing it to the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              dragging = false;
              mouseX = evt.getX();
              mouseY = evt.getY();
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs
                  drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                  repaintRect(prevX,prevY,mouseX,mouseY);
              else if (figure == LINE) {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX || mouseY != startY) {
                       // Draw the line only if it has non-zero length.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              else {
                 repaintRect(startX,startY,prevX,prevY);
                 if (mouseX != startX && mouseY != startY) {
                       // Draw the shape only if both its height
                       // and width are both non-zero.
                    drawFigure(dragGraphics,figure,startX,startY,mouseX,mouseY);
                    repaintRect(startX,startY,mouseX,mouseY);
              dragGraphics.dispose();
              dragGraphics = null;
          public void mouseDragged(MouseEvent evt) {
                   // Called whenever the user moves the mouse while a mouse button
                   // is down.  If the user is drawing a curve, draw a segment of
                   // the curve on the off-screen image, and repaint the part
                   // of the panel that contains the new line segment.  Otherwise,
                   // just call repaint and let paintComponent() draw the shape on
                   // top of the picture in the off-screen image.
              if (dragging == false)
                 return;  // Nothing to do because the user isn't drawing.
              mouseX = evt.getX();   // x-coordinate of mouse.
              mouseY = evt.getY();   // y=coordinate of mouse.
              if (figure == CURVE) {
                     // A CURVE is drawn as a series of LINEs.
                 drawFigure(dragGraphics,LINE,prevX,prevY,mouseX,mouseY);
                 repaintRect(prevX,prevY,mouseX,mouseY);
              else {
                    // Repaint two rectangles:  The one that contains the previous
                    // version of the figure, and the one that will contain the
                    // new version.  The first repaint is necessary to restore
                    // the picture from the off-screen image in that rectangle.
                 repaintRect(startX,startY,prevX,prevY);
                 repaintRect(startX,startY,mouseX,mouseY);
              prevX = mouseX;  // Save coords for the next call to mouseDragged or mouseReleased.
              prevY = mouseY;
          } // end mouseDragged.
          public void mouseEntered(MouseEvent evt) { }   // Some empty routines.
          public void mouseExited(MouseEvent evt) { }    //    (Required by the MouseListener
          public void mouseClicked(MouseEvent evt) { }   //    and MouseMotionListener
          public void mouseMoved(MouseEvent evt) { }     //    interfaces).
       } // end nested class Display

  • The application does not use the  screen and run in the background

    Hi
    I have downloaded a package of j2me Midlet
    from [link] here [link]
    and try to reuse the code
    but I get the following error when running the code:-
    The application does not use the screen and run in the background
    I think the error into one of these two classes
    package main;
    import javax.microedition.midlet.*;
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    import java.io.IOException;
    import java.io.InputStream;
    public class MainMidlet extends MIDlet implements CommandListener {
        private SSGameCanvas gameCanvas ;
        private Command exitCommand ;
        private Player player = null;
        public void startApp() {
      try {
           //   create new game thread
              gameCanvas = new SSGameCanvas();
              gameCanvas.start(); // start game thread
              exitCommand = new Command("Exit",Command.EXIT,1);
              gameCanvas.addCommand(exitCommand);
              gameCanvas.setCommandListener(this);
                Display.getDisplay(this).setCurrent(gameCanvas);
       catch (java.io.IOException e)
                e.printStackTrace();
            try {
                // start sounds
                InputStream in = getClass().getResourceAsStream("/resource/startfly.wav");
                player = Manager.createPlayer(in,"audio/x-wav");
                player.setLoopCount(1);
                player.start();
            catch (MediaException ex)
                ex.printStackTrace();
             catch (IOException ex)
                ex.printStackTrace();
        public void pauseApp() {
        public void destroyApp(boolean unconditional) {
            if (player != null) {
                player.close();
            System.gc();
      public void commandAction(Command command, Displayable displayable) {
           if (command == exitCommand)
                 destroyApp(true);
                 notifyDestroyed();
    package main;
    import java.io.IOException;
    import javax.microedition.lcdui.*;
    import javax.microedition.lcdui.game.*;
    public class SSGameCanvas extends GameCanvas implements Runnable {
        protected GameManager gameManager;
        protected boolean running;
        private int tick=0;
        private static int WIDTH;
        private static int HEIGHT;
        private int mDelay = 20;
        Form mainForm;
        Display display;
        //private int MaxTime;
        public SSGameCanvas() throws IOException{
            super(true);
            gameManager = new GameManager(5,5,getHeight()-10,getWidth()-10,this);
        public void start() {
                this.running = true;
                Thread t = new Thread(this);
                t.start();
        public void stop() {
            running = false;
        public void render(Graphics g) {
            WIDTH = getWidth();
            HEIGHT = getHeight();
            // Clear the Canvas.
            g.setColor(0, 0, 50);
            g.fillRect(0,0,WIDTH-1,HEIGHT-1);
            // draw border
            g.setColor(200,0,0);
            g.drawRect(0,0,WIDTH-1,HEIGHT-1);
            // draw game canvas
            gameManager.paint(g);
        public void run() {
            while (running) {
                // draw graphics
                render(getGraphics());
                // advance to next graphics
                advance(tick++);
                // display
                flushGraphics();
                try { Thread.sleep(mDelay); }
                catch (InterruptedException ie) {}
        public void advance(int ticks) {
            // advance to next game canvas
            gameManager.advance(ticks);
            this.paint(getGraphics());
    }Edited by: VANPERSIE on Jul 10, 2012 12:26 PM

    Hi Andi,
    Thanks for your reply.
    Yes, I have waited for a while and the result doesn't change.
    The Porblem here is the application is seen started in visual administrator.Only restart brings up the page back.
    Can you please suggest anything.
    Thanks and regards
    Nagaraj

  • Storing Shape Information IN a Table-Like Structure

    Hi All,
    I have a Program which displays shape (rectangle,oval,etc) in the panel which is enclosed in a frame.. shape can be dragged and dropped anywhere on panel... also one can delete shape... Now I Want To Store All The Exiting Shapes (as they are added on panel ) in some structure say a table, and alongwith it, i also want to store additional information about shape, say its location currently on panel, its present color, etc so that i can use this information later in the program... how do i do implement this ?? Plz Help Me.. It would be great if you include the changes in the source code itself...
    thanks
    Here is the source code :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class ShapeDrawFrame extends javax.swing.JFrame {
        JCheckBoxMenuItem addLargeShapes;    
       JCheckBoxMenuItem addBorderedShapes; 
       JRadioButtonMenuItem red, green, blue,      
                            cyan, magenta, yellow, 
                            black, gray, white;  
       JPopupMenu popup;
        public ShapeDrawFrame() {
            super("Shape Draw");
            //initComponents();        
          ShapeCanvas canvas = new ShapeCanvas();
          setContentPane(canvas);
          /* Create the menu bar and the menus */
          JMenuBar menubar = new JMenuBar();
          setJMenuBar(menubar);
          JMenu addShapeMenu = new JMenu("Add");
          addShapeMenu.setMnemonic('A');
          menubar.add(addShapeMenu);
          JMenu shapeColorMenu = new JMenu("Color");
          shapeColorMenu.setMnemonic('C');
          menubar.add(shapeColorMenu);
          JMenu optionsMenu = new JMenu("Options");
          optionsMenu.setMnemonic('O');
          menubar.add(optionsMenu);
          /* Create menu items for adding shapes to the canvas,
             and add them to the "Add" menu.  The canvas serves
             as ActionListener for these menu items. */     
          JMenuItem rect = new JMenuItem("Rectangle");
          rect.setAccelerator( KeyStroke.getKeyStroke("ctrl R") );
          addShapeMenu.add(rect);
          rect.addActionListener(canvas);
          JMenuItem oval = new JMenuItem("Oval");
          oval.setAccelerator( KeyStroke.getKeyStroke("ctrl O") );
          addShapeMenu.add(oval);
          oval.addActionListener(canvas);
          JMenuItem roundrect = new JMenuItem("Round Rect");
          roundrect.setAccelerator( KeyStroke.getKeyStroke("ctrl D") );
          addShapeMenu.add(roundrect);
          roundrect.addActionListener(canvas);
          /* Create the JRadioButtonMenuItems that control the color
             of a newly added shape, and add them to the "Color"
             menu.  There is no ActionListener for these menu items.
             The canvas checks for the currently selected color when
             it adds a shape to the canvas.  A ButtonGroup is used
             to make sure that only one color is selected. */
          ButtonGroup colorGroup = new ButtonGroup();
          red = new JRadioButtonMenuItem("Red");
          shapeColorMenu.add(red);
          colorGroup.add(red);
          red.setSelected(true);
          green = new JRadioButtonMenuItem("Green");
          shapeColorMenu.add(green);
          colorGroup.add(green);
          blue = new JRadioButtonMenuItem("Blue");
          shapeColorMenu.add(blue);
          colorGroup.add(blue);
          cyan = new JRadioButtonMenuItem("Cyan");
          shapeColorMenu.add(cyan);
          colorGroup.add(cyan);
          magenta = new JRadioButtonMenuItem("Magenta");
          shapeColorMenu.add(magenta);
          colorGroup.add(magenta);
          yellow = new JRadioButtonMenuItem("Yellow");
          shapeColorMenu.add(yellow);
          colorGroup.add(yellow);
          black = new JRadioButtonMenuItem("Black");
          shapeColorMenu.add(black);
          colorGroup.add(black);
          gray = new JRadioButtonMenuItem("Gray");
          shapeColorMenu.add(gray);
          colorGroup.add(gray);
          white = new JRadioButtonMenuItem("White");
          shapeColorMenu.add(white);
          colorGroup.add(white);
          /* Create the "Clear" menu item, and add it to the
             "Options" menu.  The canvas will listen for events
             from this menu item. */
          JMenuItem clear = new JMenuItem("Clear");
          clear.setAccelerator( KeyStroke.getKeyStroke("ctrl C") );
          clear.addActionListener(canvas);
          optionsMenu.add(clear);
          optionsMenu.addSeparator();  // Add a separating line to the menu.
          /* Create the JCheckBoxMenuItems and add them to the Options
             menu.  There is no ActionListener for these items because
             the canvas class will check their state when it adds a
             new shape. */
          addLargeShapes = new JCheckBoxMenuItem("Add Large Shapes");
          addLargeShapes.setSelected(true);
          optionsMenu.add(addLargeShapes);
          addBorderedShapes = new JCheckBoxMenuItem("Add Shapes with Border");
          addBorderedShapes.setSelected(true);
          optionsMenu.add(addBorderedShapes);
          optionsMenu.addSeparator();
          /* Create a menu for background colors, and add it to the
             "Options" menu.  It will show up as a hierarchical sub-menu. */
          JMenu background = new JMenu("Background Color");
          optionsMenu.add(background);
          background.add("Red").addActionListener(canvas);
          background.add("Green").addActionListener(canvas);
          background.add("Blue").addActionListener(canvas);
          background.add("Cyan").addActionListener(canvas);
          background.add("Magenta").addActionListener(canvas);
          background.add("Yellow").addActionListener(canvas);
          background.add("Black").addActionListener(canvas);
          background.add("Gray").addActionListener(canvas);
          background.add("White").addActionListener(canvas);
          /* Create the pop-up menu and add commands for editing a
             shape.  This menu is not used until the user performs
             the pop-up trigger mouse gesture on a shape. */
          popup = new JPopupMenu();
          popup.add("Delete Shape").addActionListener(canvas);
          popup.add("Bring to Front").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Make Large").addActionListener(canvas);
          popup.add("Make Small").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Add Black Border").addActionListener(canvas);
          popup.add("Remove Black Border").addActionListener(canvas);
          popup.addSeparator();
          popup.add("Set Color to Red").addActionListener(canvas);
          popup.add("Set Color to Green").addActionListener(canvas);
          popup.add("Set Color to Blue").addActionListener(canvas);
          popup.add("Set Color to Cyan").addActionListener(canvas);
          popup.add("Set Color to Magenta").addActionListener(canvas);
          popup.add("Set Color to Yellow").addActionListener(canvas);
          popup.add("Set Color to Black").addActionListener(canvas);
          popup.add("Set Color to Gray").addActionListener(canvas);
          popup.add("Set Color to White").addActionListener(canvas);
          /* Set the "DefaultCloseOperation" for the frame.  This determines
             what happens when the user clicks the close box of the frame.
             It is set here so that System.exit() will be called to end
             the program when the user closes the window. */
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          /* Set the size and location of the frame, and make it visible. */
          setLocation(20,50);
          setSize(550,420);
          show();       
       class ShapeCanvas extends JPanel
                         implements ActionListener, MouseListener, MouseMotionListener {
             // This class represents a "canvas" that can display colored shapes and
             // let the user drag them around.  It uses an off-screen images to
             // make the dragging look as smooth as possible.
          ArrayList shapes = new ArrayList();
               // holds a list of the shapes that are displayed on the canvas
          ShapeCanvas() {
               // Constructor: set background color to white
               // set up listeners to respond to mouse actions
             setBackground(Color.white);
             addMouseListener(this);
             addMouseMotionListener(this);
          public void paintComponent(Graphics g) {
               // In the paint method, all the shapes in ArrayList are
               // copied onto the canvas.
             super.paintComponent(g);  // First, fill with background color.
             int top = shapes.size();
             for (int i = 0; i < top; i++) {
                Shape s = (Shape)shapes.get(i);
                s.draw(g);
          public void actionPerformed(ActionEvent evt) {
                 // Called to respond to action events from the
                 // menus or pop-up menu.
             String command = evt.getActionCommand();
             if (command.equals("Clear")) {
                shapes.clear(); // Remove all items from the ArrayList
                repaint();
             else if (command.equals("Rectangle"))
                addShape(new RectShape());
             else if (command.equals("Oval"))
                addShape(new OvalShape());
             else if (command.equals("Round Rect"))
                addShape(new RoundRectShape());
             else if (command.equals("Red"))
                setBackground(Color.red);
             else if (command.equals("Green"))
                setBackground(Color.green);
             else if (command.equals("Blue"))
                setBackground(Color.blue);
             else if (command.equals("Cyan"))
                setBackground(Color.cyan);
             else if (command.equals("Magenta"))
                setBackground(Color.magenta);
             else if (command.equals("Yellow"))
                setBackground(Color.yellow);
             else if (command.equals("Black"))
                setBackground(Color.black);
             else if (command.equals("Gray"))
                setBackground(Color.gray);
             else if (command.equals("White"))
                setBackground(Color.white);
             else if (clickedShape != null) {
                    // Process a command from the pop-up menu.
                if (command.equals("Delete Shape"))
                   shapes.remove(clickedShape);
                else if (command.equals("Bring to Front")) {
                   shapes.remove(clickedShape);
                   shapes.add(clickedShape); 
                else if (command.equals("Make Large"))
                   clickedShape.setSize(100,60);
                else if (command.equals("Make Small"))
                   clickedShape.setSize(50,30);
                else if (command.equals("Add Black Border"))
                   clickedShape.setDrawOutline(true);
                else if (command.equals("Remove Black Border"))
                   clickedShape.setDrawOutline(false);
                else if (command.equals("Set Color to Red"))
                   clickedShape.setColor(Color.red);
                else if (command.equals("Set Color to Green"))
                   clickedShape.setColor(Color.green);
                else if (command.equals("Set Color to Blue"))
                   clickedShape.setColor(Color.blue);
                else if (command.equals("Set Color to Cyan"))
                   clickedShape.setColor(Color.cyan);
                else if (command.equals("Set Color to Magenta"))
                   clickedShape.setColor(Color.magenta);
                else if (command.equals("Set Color to Yellow"))
                   clickedShape.setColor(Color.yellow);
                else if (command.equals("Set Color to Black"))
                   clickedShape.setColor(Color.black);
                else if (command.equals("Set Color to Gray"))
                   clickedShape.setColor(Color.gray);
                else if (command.equals("Set Color to White"))
                   clickedShape.setColor(Color.white);
                repaint();
          } // end actionPerformed()
          void addShape(Shape shape) {
                 // Add the shape to the canvas, and set its size, color
                 // and whether or not it should have a black border.  These
                 // properties are determined by looking at the states of
                 // various menu items.  The shape is added at the top-left
                 // corner of the canvas.
             if (red.isSelected())
                shape.setColor(Color.red);
             else if (blue.isSelected())
                shape.setColor(Color.blue);
             else if (green.isSelected())
                shape.setColor(Color.green);
             else if (cyan.isSelected())
                shape.setColor(Color.cyan);
             else if (magenta.isSelected())
                shape.setColor(Color.magenta);
             else if (yellow.isSelected())
                shape.setColor(Color.yellow);
             else if (black.isSelected())
                shape.setColor(Color.black);
             else if (white.isSelected())
                shape.setColor(Color.white);
             else
                shape.setColor(Color.gray);
             shape.setDrawOutline( addBorderedShapes.isSelected() );
             if (addLargeShapes.isSelected())
                shape.reshape(3,3,100,60);
             else
                shape.reshape(3,3,50,30);
             shapes.add(shape);
             repaint();
          } // end addShape()
          // -------------------- This rest of this class implements dragging ----------------------
          Shape clickedShape = null;  // This is the shape that the user clicks on.
                                      // It becomes the draggedShape is the user is
                                      // dragging, unless the user is invoking a
                                      // pop-up menu.  This variable is used in
                                      // actionPerformed() when a command from the
                                      // pop-up menu is processed.
          Shape draggedShape = null;  // This is null unless a shape is being dragged.
                                      // A non-null value is used as a signal that dragging
                                      // is in progress, as well as indicating which shape
                                      // is being dragged.
          int prevDragX;  // During dragging, these record the x and y coordinates of the
          int prevDragY;  //    previous position of the mouse.
          public void mousePressed(MouseEvent evt) {
                // User has pressed the mouse.  Find the shape that the user has clicked on, if
                // any.  If there is no shape at the position when the mouse was clicked, then
                // ignore this event.  If there is then one of three things will happen:
                // If the event is a pop-up trigger, then the pop-up menu is displayed, and
                // the user can select from the pop-up menu to edit the shape.  If the user was
                // holding down the shift key, then bring the clicked shape to the front, in
                // front of all the other shapes.  Otherwise, start dragging the shape.
             if (draggedShape != null) {
                  // A drag operation is already in progress, so ignore this click.
                  // This might happen if the user clicks a second mouse button before
                  // releasing the first one(?).
                return;
             int x = evt.getX();  // x-coordinate of point where mouse was clicked
             int y = evt.getY();  // y-coordinate of point
             clickedShape = null;  // This will be set to the clicked shape, if any.
             for ( int i = shapes.size() - 1; i >= 0; i-- ) { 
                    // Check shapes from front to back.
                Shape s = (Shape)shapes.get(i);
                if (s.containsPoint(x,y)) {
                   clickedShape = s;
                   break;
             if (clickedShape == null) {
                   // The user did not click on a shape.
                return;
             else if (evt.isPopupTrigger()) {
                  // The user wants to see the pop-up menu
                popup.show(this,x-10,y-2);
             else if (evt.isShiftDown()) {
                  // Bring the clicked shape to the front
                shapes.remove(clickedShape);
                shapes.add(clickedShape);
                repaint();
             else {
                  // Start dragging the shape.
                draggedShape = clickedShape;
                prevDragX = x;
                prevDragY = y;
          public void mouseDragged(MouseEvent evt) {
                 // User has moved the mouse.  Move the dragged shape by the same amount.
             if (draggedShape == null) {
                    // User did not click a shape.  There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             draggedShape.moveBy(x - prevDragX, y - prevDragY);
             prevDragX = x;
             prevDragY = y;
             repaint();      // redraw canvas to show shape in new position
          public void mouseReleased(MouseEvent evt) {
                 // User has released the mouse.  Move the dragged shape, and set
                 // draggedShape to null to indicate that dragging is over.
                 // If the shape lies completely outside the canvas, remove it
                 // from the list of shapes (since there is no way to ever move
                 // it back on screen).  However, if the event is a popup trigger
                 // event, then show the popup menu instead.
             if (draggedShape == null) {
                   // User did not click on a shape. There is nothing to do.
                return;
             int x = evt.getX();
             int y = evt.getY();
             if (evt.isPopupTrigger()) {
                   // Check whether the user is trying to pop up a menu.
                   // (This should be checked in both the mousePressed() and
                   // mouseReleased() methods.)
                popup.show(this,x-10,y-2);
             else {
                draggedShape.moveBy(x - prevDragX, y - prevDragY);
                if ( draggedShape.left >= getSize().width || draggedShape.top >= getSize().height ||
                        draggedShape.left + draggedShape.width < 0 ||
                        draggedShape.top + draggedShape.height < 0 ) {  // shape is off-screen
                   shapes.remove(draggedShape);  // remove shape from list of shapes
                repaint();
             draggedShape = null;  // Dragging is finished.
          public void mouseEntered(MouseEvent evt) { }   // Other methods required for MouseListener and
          public void mouseExited(MouseEvent evt) { }    //              MouseMotionListener interfaces.
          public void mouseMoved(MouseEvent evt) { }
          public void mouseClicked(MouseEvent evt) { }
       }  // end class ShapeCanvas
       // ------- Nested class definitions for the abstract Shape class and three -----
       // -------------------- concrete subclasses of Shape. --------------------------
       static abstract class Shape {
             // A class representing shapes that can be displayed on a ShapeCanvas.
             // The subclasses of this class represent particular types of shapes.
             // When a shape is first constructed, it has height and width zero
             // and a default color of white.
          int left, top;      // Position of top left corner of rectangle that bounds this shape.
          int width, height;  // Size of the bounding rectangle.
          Color color = Color.white;  // Color of this shape.
          boolean drawOutline;  // If true, a black border is drawn on the shape
          void reshape(int left, int top, int width, int height) {
                // Set the position and size of this shape.
             this.left = left;
             this.top = top;
             this.width = width;
             this.height = height;
          void setSize(int width, int height) {
                // Set the size of this shape
             this.width = width;
             this.height = height;
          void moveBy(int dx, int dy) {
                 // Move the shape by dx pixels horizontally and dy pixels vertically
                 // (by changing the position of the top-left corner of the shape).
             left += dx;
             top += dy;
          void setColor(Color color) {
                 // Set the color of this shape
             this.color = color;
          void setDrawOutline(boolean draw) {
                 // If true, a black outline is drawn around this shape.
             drawOutline = draw;
          boolean containsPoint(int x, int y) {
                // Check whether the shape contains the point (x,y).
                // By default, this just checks whether (x,y) is inside the
                // rectangle that bounds the shape.  This method should be
                // overridden by a subclass if the default behavior is not
                // appropriate for the subclass.
             if (x >= left && x < left+width && y >= top && y < top+height)
                return true;
             else
                return false;
          abstract void draw(Graphics g); 
                // Draw the shape in the graphics context g.
                // This must be overridden in any concrete subclass.
       }  // end of class Shape
       static class RectShape extends Shape {
             // This class represents rectangle shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRect(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRect(left,top,width,height);
       static class OvalShape extends Shape {
              // This class represents oval shapes.
          void draw(Graphics g) {
             g.setColor(color);
             g.fillOval(left,top,width,height);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawOval(left,top,width,height);
          boolean containsPoint(int x, int y) {
                // Check whether (x,y) is inside this oval, using the
                // mathematical equation of an ellipse.
             double rx = width/2.0;   // horizontal radius of ellipse
             double ry = height/2.0;  // vertical radius of ellipse
             double cx = left + rx;   // x-coord of center of ellipse
             double cy = top + ry;    // y-coord of center of ellipse
             if ( (ry*(x-cx))*(ry*(x-cx)) + (rx*(y-cy))*(rx*(y-cy)) <= rx*rx*ry*ry )
                return true;
             else
               return false;
       static class RoundRectShape extends Shape {
              // This class represents rectangle shapes with rounded corners.
              // (Note that it uses the inherited version of the
              // containsPoint(x,y) method, even though that is not perfectly
              // accurate when (x,y) is near one of the corners.)
          void draw(Graphics g) {
             g.setColor(color);
             g.fillRoundRect(left,top,width,height,width/3,height/3);
             if (drawOutline) {
                g.setColor(Color.black);
                g.drawRoundRect(left,top,width,height,width/3,height/3);
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 400, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 300, Short.MAX_VALUE)
            pack();
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShapeDrawFrame().setVisible(true);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }

    Sure. In your original post, you had a sort of a design. The general idea was right. And then you asked us to implement it. Well, that's the wrong approach. You need to make the sort-of-a-design into a real design. Don't implement anything until you know what you are going to implement.

  • A litle help please...  drawing app.

    Hi all,
    I'm trying to adapt a file I downloaded (legally) and I'm having some trouble as I'm still stuck in the days of AS2 and this has
    been built in AS3. As you will see it's a drawing app that allows a few options for brush size, blur etc.,
    What I'd like to do is to duplicate the brush_tool_mc  with settings for full brush size and full blur to use as a spray can tool.
    All my attempts so far have ended in disaster and multiple output errors !  : (
    Any help / pointers / guidance much appreciated.
    Best wishes
    Tony
    Source and example is here:
    http://www.nocircleno.com/graffiti/examples/2.x/graffiti_advanced_demo.html
    CODE:  (Main.as)
    *      Example Application built with the Graffiti Library
    *      www.nocircleno.com/graffiti/
    *     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    *     EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    *     OF MERCHANTABILITY, FITNESS 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 {
        import flash.display.Bitmap;
        import flash.display.BitmapData
        import flash.display.MovieClip;
        import flash.display.SimpleButton;
        import flash.display.Sprite;
        import flash.display.LineScaleMode;
        import flash.display.CapsStyle;
        import flash.display.JointStyle;
        import flash.text.TextField;
        import flash.geom.Point;
        import flash.text.TextFormat;
        import flash.ui.Keyboard;
        import flash.events.Event;
        import flash.events.MouseEvent;
        import flash.events.KeyboardEvent;
        import flash.display.BlendMode;
        import flash.net.navigateToURL;
        import flash.net.FileReference;
        import flash.net.URLRequest;
        import flash.net.URLRequestMethod;
        import flash.net.URLRequestHeader;
        import flash.text.Font;
        import flash.utils.ByteArray;
        import fl.controls.CheckBox;
        import fl.controls.ColorPicker;
        import fl.controls.Slider;
        import fl.controls.ComboBox;
        import fl.events.ColorPickerEvent;
        import fl.events.SliderEvent;
        import fl.data.DataProvider;
        import com.nocircleno.graffiti.GraffitiCanvas;
        import com.nocircleno.graffiti.display.Text;
        import com.nocircleno.graffiti.display.GraffitiObject;
        import com.nocircleno.graffiti.events.CanvasEvent;
        import com.nocircleno.graffiti.events.GraffitiObjectEvent;
        import com.nocircleno.graffiti.tools.BrushTool;
        import com.nocircleno.graffiti.tools.BrushType;
        import com.nocircleno.graffiti.tools.LineTool;
        import com.nocircleno.graffiti.tools.LineType;
        import com.nocircleno.graffiti.tools.ShapeTool;
        import com.nocircleno.graffiti.tools.ShapeType;
        import com.nocircleno.graffiti.tools.ToolMode;
        import com.nocircleno.graffiti.tools.ITool;
        import com.nocircleno.graffiti.tools.BitmapTool;
        import com.nocircleno.graffiti.tools.FillBucketTool;
        import com.nocircleno.graffiti.tools.SelectionTool;
        import com.nocircleno.graffiti.tools.TextSettings;
        import com.nocircleno.graffiti.tools.TextTool;
        import com.nocircleno.graffiti.managers.GraffitiObjectManager;
        import com.adobe.images.PNGEncoder;
        public class Main extends MovieClip {
            public var click_message_txt:TextField;
            // ui
            public var brush_tool_mc:ItemButton;
            public var eraser_tool_mc:ItemButton;
            public var line_tool_mc:ItemButton;
            public var rectangle_tool_mc:ItemButton;
            public var fillbucket_tool_mc:ItemButton;
            public var selection_tool_mc:ItemButton;
            public var text_tool_mc:ItemButton;
            public var oval_tool_mc:ItemButton;
            public var clear_btn:SimpleButton;
            public var save_btn:SimpleButton;
            public var undo_btn:SimpleButton;
            public var redo_btn:SimpleButton;
            public var slider_label_txt:TextField;
            public var slider_2_label_txt:TextField;
            public var slider_3_label_txt:TextField;
            public var combo_label_txt:TextField;
            public var stroke_color_mc:ColorPicker;
            public var fill_color_mc:ColorPicker;
            public var slider_mc:Slider;
            public var slider_2_mc:Slider;
            public var slider_3_mc:Slider;
            public var zoom_slider_mc:Slider;
            public var combo_list:ComboBox;
            public var overlay_cb:CheckBox;
            public var overlay_mc:MovieClip;
            public var canvas:GraffitiCanvas;
            public var border:Sprite;
            // tools
            private var _brush:BrushTool;
            private var _eraser:BrushTool;
            private var _line:LineTool;
            private var _shape:ShapeTool;
            private var _selectionTool:SelectionTool;
            private var _textTool:TextTool;
            private var _fillBucketTool:FillBucketTool;
            // props
            private var _brushSize:Number = 2;
            private var _strokeColor:uint = 0x00FF00;
            private var _fillColor:uint = 0xFF0000;
            private var _strokeAlpha:Number = 1;
            private var _fillAlpha:Number = 1;
            private var _brushBlur:Number = 0;
            private var _fontColor:uint = 0x00FF00;
            private var _fontSize:uint = 14;
            private var _brushShapeIndex:int;
            private var _lineStyleIndex:int;
            private var _fontIndex:uint = 0;
            private var _fontList:DataProvider;
            private var _brushShapes:DataProvider;
            private var _lineStyles:DataProvider;
            private var _fileRef:FileReference;
            private var _objectManager:GraffitiObjectManager;
            private var _orginalComboBoxItemsPos = new Object();
            public function Main() {
                // hide message
                click_message_txt.alpha = 0;
                // create canvas
                canvas = new GraffitiCanvas(840, 470, 10);
                canvas.x = 0;
                canvas.y = 120;
                canvas.addEventListener(MouseEvent.MOUSE_WHEEL, scrollHandler);
                canvas.addEventListener(GraffitiCanvas.HISTORY_LENGTH_CHANGE, historyLengthChangeHandler);
                canvas.addEventListener(GraffitiObjectEvent.SELECT, objectEventHandler);
                canvas.addEventListener(GraffitiObjectEvent.ENTER_EDIT, objectEventHandler);
                addChild(canvas);
                // add image over canvas
                overlay_mc = new OverlayImage();
                canvas.overlay = overlay_mc;
                // get instance of graffiti object manager
                _objectManager = GraffitiObjectManager.getInstance();
                // add listeners for keyboard shortcuts
                stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
                stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
                // add event listeners for tool buttons
                selection_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                text_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                fillbucket_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                brush_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                eraser_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                line_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                rectangle_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                oval_tool_mc.addEventListener(MouseEvent.CLICK, toolHandler);
                // setup data providers
                _brushShapes = new DataProvider();
                _brushShapes.addItem({label:"Round", data: BrushType.ROUND});
                _brushShapes.addItem({label:"Square", data: BrushType.SQUARE});
                _brushShapes.addItem({label:"Diamond", data: BrushType.DIAMOND});
                _brushShapes.addItem({label:"Vertical", data: BrushType.VERTICAL_LINE});
                _brushShapes.addItem({label:"Horizontal", data: BrushType.HORIZONTAL_LINE});
                _brushShapes.addItem({label:"Forward", data: BrushType.FORWARD_LINE});
                _brushShapes.addItem({label:"Backward", data: BrushType.BACKWARD_LINE});
                _lineStyles = new DataProvider();
                _lineStyles.addItem({label:"Solid", data: LineType.SOLID});
                _lineStyles.addItem({label:"Dotted", data: LineType.DOTTED});
                _lineStyles.addItem( { label:"Dashed", data: LineType.DASHED } );
                // Setup Font List
                _fontList = new DataProvider();
                var embeddedFonts:Array = Font.enumerateFonts(true);
                embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
                for (var i:int = 0; i < embeddedFonts.length; i++) {
                    _fontList.addItem( {label: embeddedFonts[i].fontName, data: embeddedFonts[i] } );
                // create tool instances
                _brush = new BrushTool(_brushSize, _fillColor, _fillAlpha, _brushBlur, BrushType.ROUND);
                _eraser = new BrushTool(_brushSize, _fillColor, 1, _brushBlur, BrushType.ROUND, ToolMode.ERASE);
                _line = new LineTool(2, _strokeColor, _strokeAlpha, LineType.SOLID);
                _shape = new ShapeTool(2, _strokeColor, _fillColor, _strokeAlpha, _fillAlpha, ShapeType.RECTANGLE);
                _fillBucketTool = new FillBucketTool(_fillColor, true);
                _selectionTool = new SelectionTool();
                _textTool = new TextTool(new TextSettings(Font(_fontList.getItemAt(0).data), new TextFormat(null, _fontSize, _fontColor)));
                // setup color pickers
                stroke_color_mc.focusEnabled = false;
                stroke_color_mc.selectedColor = _strokeColor;
                stroke_color_mc.addEventListener(ColorPickerEvent.CHANGE, colorPickerHandler);
                stroke_color_mc.enabled = false;
                fill_color_mc.focusEnabled = false;
                fill_color_mc.selectedColor = _fillColor;
                fill_color_mc.addEventListener(ColorPickerEvent.CHANGE, colorPickerHandler);
                slider_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
                slider_2_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
                slider_3_mc.addEventListener(SliderEvent.CHANGE, sliderHandler);
                overlay_cb.addEventListener(Event.CHANGE, overlayHandler);
                overlay_cb.focusEnabled = false;
                // config combo list
                combo_list.addEventListener(Event.CHANGE, comboEventHandler);
                combo_list.dataProvider = _brushShapes;
                combo_list.focusEnabled = false;
                // store positions
                _orginalComboBoxItemsPos.comboBox = new Point(combo_list.x, combo_list.y);
                _orginalComboBoxItemsPos.comboBoxLabel = new Point(combo_label_txt.x, combo_label_txt.y);
                // disable undo and redo buttons
                undo_btn.mouseEnabled = false;
                undo_btn.alpha = .5;
                redo_btn.mouseEnabled = false;
                redo_btn.alpha = .5;
                // add event listeners
                undo_btn.addEventListener(MouseEvent.CLICK, historyHandler);
                redo_btn.addEventListener(MouseEvent.CLICK, historyHandler);
                clear_btn.addEventListener(MouseEvent.CLICK, clearCanvasHandler);
                save_btn.addEventListener(MouseEvent.CLICK, saveHandler);
                zoom_slider_mc.maximum = canvas.maxZoom;
                zoom_slider_mc.addEventListener(SliderEvent.CHANGE, zoomHandler);
                // assign the brush tool as the default tool
                canvas.activeTool = _brush;
                // set brush tool
                brush_tool_mc.selected = true;
                setSelectedBrushShape(BrushType.ROUND);
                Method    : objectEventHandler()
                Purpose    : This method handles GraffitiObjectEvents.  We use this
                          to know when an object is selected or enters edit mode.
                Params    : e -- GraffitiObjectEvent object.
            private function objectEventHandler(e:GraffitiObjectEvent):void {
                var font:Font;
                var fmt:TextFormat;
                var i:int;
                if (e.type == GraffitiObjectEvent.SELECT) {
                    // get font and text format of selected object
                    font = Text(e.graffitiObject).textSetting.font;
                    fmt = Text(e.graffitiObject).textSetting.textFormat;
                    _fontSize = Number(fmt.size);
                    var fontFromList:Font;
                    var numberFonts:uint = _fontList.length;
                    // find select text font in font list
                    for (i = 0; i < numberFonts; i++) {
                        fontFromList = Font(_fontList.getItemAt(i).data);
                        if (fontFromList.fontName == font.fontName && fontFromList.fontStyle == font.fontStyle) {
                            _fontIndex = i;
                            break;
                    // if text tool is active tool, then update it.
                    if (canvas.activeTool is TextTool) {   
                        TextTool(canvas.activeTool).textSettings = new TextSettings(font, fmt);
                    } else {
                        _textTool.textSettings.textFormat.size = Number(fmt.size);
                    // update ui for objects
                    combo_list.selectedIndex = _fontIndex;
                    slider_mc.value = Number(fmt.size);   
                    fill_color_mc.selectedColor = uint(fmt.color);
                } else if (e.type == GraffitiObjectEvent.ENTER_EDIT) {
                    // if we enter edit mode on an text object, make sure the tool is set to the text tool.
                    if (e.graffitiObject is Text && !(canvas.activeTool is TextTool)) {
                        setActiveTool(text_tool_mc);
                Method    : overlayHandler()
                Purpose    : This method toggles the overlay on and off.
                Params    : e -- Event object.
            private function overlayHandler(e:Event):void {
                if(e.currentTarget.selected) {
                    canvas.overlay = overlay_mc;
                } else {
                    canvas.overlay = null;
                Method    : historyHandler()
                Purpose    : This method undo or redo the drawing depending on the button
                          clicked by the user.
                Params    : e -- MouseEvent object.
            private function historyHandler(e:MouseEvent):void {
                if(e.currentTarget == undo_btn) {
                    canvas.prevHistory();
                    if(canvas.historyPosition == 0) {
                        undo_btn.mouseEnabled = false;
                        undo_btn.alpha = .5;
                    redo_btn.mouseEnabled = true;
                    redo_btn.alpha = 1;
                } else if(e.currentTarget == redo_btn) {
                    canvas.nextHistory();
                    if(canvas.historyPosition == (canvas.historyLength - 1)) {
                        redo_btn.mouseEnabled = false;
                        redo_btn.alpha = .5;
                    undo_btn.mouseEnabled = true;
                    undo_btn.alpha = 1;
                Method    : clearCanvasHandler()
                Purpose    : This method will clear the canvas.
                Params    : e -- MouseEvent object.
            private function clearCanvasHandler(e:MouseEvent):void {
                canvas.clearCanvas();
                Method    : saveHandler()
                Purpose    : This method will save the drawing as a PNG image.
                Params    : e -- MouseEvent object.
            private function saveHandler(e:MouseEvent):void {
                // get drawing as bitmapdata from the Graffiti Canvas instance.
                var canvasBmp:BitmapData = canvas.drawing();
                // create new jpg encoder object and convert bitmapdata to jpg
                var pngEncoder:PNGEncoder = new PNGEncoder();
                var pngStream:ByteArray = PNGEncoder.encode(canvasBmp);
                // make sure you dispose of the bitmapdata object when finished.
                canvasBmp.dispose();
                _fileRef = new FileReference();
                _fileRef.save(pngStream, "graffiti_example_image.png");
                Method    : historyLengthChangeHandler()
                Purpose    : This method will handle the change in the number of stored
                          history items.  This is used to toggle the redo and undo
                          buttons.
                Params    : e -- Event object.
            private function historyLengthChangeHandler(e:Event):void {
                if(canvas.historyLength > 0 && canvas.historyPosition != 0) {
                    undo_btn.mouseEnabled = true;
                    undo_btn.alpha = 1;
                } else {
                    undo_btn.mouseEnabled = false;
                    undo_btn.alpha = .5;
                if(canvas.historyLength > 0 && canvas.historyPosition != canvas.historyLength - 1) {
                    redo_btn.mouseEnabled = true;
                    redo_btn.alpha = 1;
                } else {
                    redo_btn.mouseEnabled = false;
                    redo_btn.alpha = .5;
                Method    : zoomHandler()
                Purpose    : This method will handle the zoom slider event and set the
                          canvas to the new zoom level.
                Params    : e -- SliderEvent object.
            private function zoomHandler(e:SliderEvent):void {
                // set zoom of canvas
                canvas.zoom = e.value;
                // if canvas is zoomed in then display message about dragging canvas with mouse.
                if(canvas.zoom  > 1) {
                    click_message_txt.alpha = 1;
                } else {
                    click_message_txt.alpha = 0;
                Method    : colorPickerHandler()
                Purpose    : This method will handle the color picker event.
                Params    : e -- ColorPickerEvent object.
            private function colorPickerHandler(e:ColorPickerEvent):void {
                var font:Font;
                var fmt:TextFormat;
                var ts:TextSettings;
                if(canvas.activeTool is BrushTool) {
                    _fillColor = e.color;
                    BrushTool(canvas.activeTool).color = _fillColor;
                } else if(canvas.activeTool is LineTool) {
                    _strokeColor = e.color;
                    LineTool(canvas.activeTool).color = _strokeColor;
                } else if(canvas.activeTool is ShapeTool) {
                    if(e.currentTarget == stroke_color_mc) {
                        _strokeColor = e.color;
                        ShapeTool(canvas.activeTool).strokeColor = _strokeColor;
                    } else if (e.currentTarget == fill_color_mc) {
                        _fillColor = e.color;
                        ShapeTool(canvas.activeTool).fillColor = _fillColor;
                } else if (canvas.activeTool is TextTool) {
                    // update color of textformat object
                    fmt = TextTool(canvas.activeTool).textSettings.textFormat;
                    fmt.color = fill_color_mc.selectedColor;
                    // update text tool
                    TextTool(canvas.activeTool).textSettings.textFormat = fmt;
                    // update any selected text with new color
                    if (_objectManager.areObjectsSelected()) {
                        font = Font(combo_list.selectedItem.data);
                        fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                        ts = new TextSettings(font, fmt);
                        _objectManager.changeSettingsForSelectedObjects(ts);
                } else if (canvas.activeTool is SelectionTool) {
                    font = Font(combo_list.selectedItem.data);
                    fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                    ts = new TextSettings(font, fmt);
                    // update text tool
                    _textTool.textSettings = ts;
                    if (_objectManager.areObjectsSelected()) {
                        // change settings for selected text
                        _objectManager.changeSettingsForSelectedObjects(ts);
                } else if (canvas.activeTool is FillBucketTool) {
                    FillBucketTool(canvas.activeTool).fillColor = fill_color_mc.selectedColor;
                Method    : sliderHandler()
                Purpose    : This method will handle the slider change.
                Params    : e -- SliderEvent object.
            private function sliderHandler(e:SliderEvent):void {
                var font:Font;
                var fmt:TextFormat;
                var ts:TextSettings;
                if(e.currentTarget == slider_mc) {
                    if(canvas.activeTool == _brush || canvas.activeTool == _eraser) {
                        _brushSize = e.value;
                        BrushTool(canvas.activeTool).size = _brushSize;
                    } else if(canvas.activeTool == _line) {
                        LineTool(canvas.activeTool).lineWidth = e.value;
                    } else if(canvas.activeTool == _shape) {
                        ShapeTool(canvas.activeTool).strokeWidth = e.value;
                    } else if (canvas.activeTool is TextTool) {
                        _fontSize = slider_mc.value;
                        fmt = TextTool(canvas.activeTool).textSettings.textFormat;
                        fmt.size = slider_mc.value;
                        TextTool(canvas.activeTool).textSettings.textFormat = fmt;
                        if (_objectManager.areObjectsSelected()) {
                            font = Font(combo_list.selectedItem.data);
                            fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                            ts = new TextSettings(font, fmt);
                            _objectManager.changeSettingsForSelectedObjects(ts);
                    } else if (canvas.activeTool == _selectionTool) {
                        _fontSize = slider_mc.value;
                        font = Font(combo_list.selectedItem.data);
                        fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                        ts = new TextSettings(font, fmt);
                        // update text tool
                        _textTool.textSettings = ts;
                        if (_objectManager.areObjectsSelected()) {
                            _objectManager.changeSettingsForSelectedObjects(ts);
                } else if(e.currentTarget == slider_2_mc) {
                    if(canvas.activeTool is BrushTool) {
                        _fillAlpha = e.value;
                        BrushTool(canvas.activeTool).alpha = e.value;
                    } else if (canvas.activeTool is LineTool) {
                        _strokeAlpha = e.value;
                        LineTool(canvas.activeTool).alpha = e.value;
                    } else if (canvas.activeTool is ShapeTool) {
                        _strokeAlpha = e.value;
                        ShapeTool(canvas.activeTool).strokeAlpha = e.value;
                } else if(e.currentTarget == slider_3_mc) {
                    if(canvas.activeTool is BrushTool) {
                        _brushBlur = e.value;
                        BrushTool(canvas.activeTool).blur = e.value;
                    } else if(canvas.activeTool is ShapeTool) {
                        _fillAlpha = e.value;
                        ShapeTool(canvas.activeTool).fillAlpha = e.value;
                Method    : setActiveTool()
                Purpose    : This method sets the program to use a new tool.
                Params    : toolButton -- One of the Tool Buttons.
            private function setActiveTool(toolButton:ItemButton):void {
                // deselect all button to start
                brush_tool_mc.selected = false;
                eraser_tool_mc.selected = false;
                line_tool_mc.selected = false;
                rectangle_tool_mc.selected = false;
                oval_tool_mc.selected = false;
                selection_tool_mc.selected = false;
                fillbucket_tool_mc.selected = false;
                text_tool_mc.selected = false;
                // show combo box
                combo_label_txt.visible = true;
                combo_list.visible = true;
                combo_list.x = _orginalComboBoxItemsPos.comboBox.x;
                combo_list.y = _orginalComboBoxItemsPos.comboBox.y;
                combo_label_txt.x = _orginalComboBoxItemsPos.comboBoxLabel.x;
                combo_label_txt.y = _orginalComboBoxItemsPos.comboBoxLabel.y;
                // set slider
                slider_mc.minimum = 2;
                slider_mc.maximum = 40;
                // enable all slider ui
                slider_mc.visible = true;
                slider_label_txt.visible = true;
                slider_2_label_txt.visible = true;
                slider_2_mc.visible = true;
                slider_3_label_txt.visible = true;
                slider_3_mc.visible = true;
                slider_2_label_txt.alpha = 1;
                // make sure both color pickers are enabled at this point.
                // let each tool block decide to turn them off.
                fill_color_mc.enabled = true;
                stroke_color_mc.enabled = true;
                // brush tool selected
                if(toolButton == brush_tool_mc) {
                    // set selected tool state
                    brush_tool_mc.selected = true;
                    // config color pickers
                    stroke_color_mc.enabled = false;
                    // set brush shape list
                    combo_label_txt.text = "Brush Shapes";
                    combo_list.dataProvider = _brushShapes;
                    combo_list.selectedIndex = _brushShapeIndex;
                    // config and set brush tool as active tool
                    _brush.color = fill_color_mc.selectedColor;
                    _brush.alpha = _fillAlpha;
                    _brush.blur = _brushBlur;
                    _brush.size = _brushSize;
                    _brush.type = combo_list.selectedItem.data;
                    canvas.activeTool = _brush;
                    // update slider
                    slider_label_txt.text = "Brush Size";
                    slider_mc.value = _brush.size;
                    slider_2_label_txt.text = "Brush Alpha";
                    slider_2_label_txt.alpha = 1;
                    slider_2_mc.enabled = true;
                    slider_2_mc.snapInterval = .1;
                    slider_2_mc.value = _brush.alpha;
                    slider_3_label_txt.text = "Brush Blur";
                    slider_3_label_txt.visible = true;
                    slider_3_label_txt.alpha = 1;
                    slider_3_mc.visible = true;
                    slider_3_mc.snapInterval = 1;
                    slider_3_mc.enabled = true;
                    slider_3_mc.minimum = 0;
                    slider_3_mc.maximum = 20;
                    slider_3_mc.value = _brush.blur;
                // eraser tool selected
                } else if(toolButton == eraser_tool_mc) {
                    // set selected tool state
                    eraser_tool_mc.selected = true;
                    // config color picker
                    fill_color_mc.enabled = false;
                    stroke_color_mc.enabled = false;
                    // set brush shape list
                    combo_label_txt.text = "Brush Shapes";
                    combo_list.dataProvider = _brushShapes;
                    combo_list.selectedIndex = _brushShapeIndex;
                    // config and set eraser tool as active tool
                    _eraser.color = fill_color_mc.selectedColor;
                    _brush.alpha = 1;
                    _brush.blur = _brushBlur;
                    _eraser.size = _brushSize;
                    _eraser.type = combo_list.selectedItem.data;
                    canvas.activeTool = _eraser;
                    // update slider
                    slider_label_txt.text = "Brush Size";
                    slider_mc.value = _eraser.size;
                    slider_2_label_txt.text = "Brush Alpha";
                    slider_2_label_txt.alpha = .5;
                    slider_2_mc.enabled = false;
                    slider_2_mc.snapInterval = .1;
                    slider_2_mc.value = _eraser.alpha;
                    slider_3_label_txt.text = "Brush Blur";
                    slider_3_label_txt.visible = true;
                    slider_3_label_txt.alpha = .5;
                    slider_3_mc.visible = true;
                    slider_3_mc.minimum = 0;
                    slider_3_mc.maximum = 20;
                    slider_3_mc.enabled = false;
                    slider_3_mc.value = _eraser.blur;
                // line tool
                } else if(toolButton == line_tool_mc) {
                    // set selected tool state
                    line_tool_mc.selected = true;
                    // config color picker
                    fill_color_mc.enabled = false;
                    // set line style list
                    combo_label_txt.text = "Line Style";
                    combo_list.dataProvider = _lineStyles;
                    combo_list.selectedIndex = _lineStyleIndex;
                    combo_label_txt.x = slider_3_label_txt.x + 8;
                    combo_list.x = slider_3_mc.x;
                    // config and set line tool as active tool
                    _line.color = stroke_color_mc.selectedColor;
                    _line.alpha = _strokeAlpha;
                    _line.type = combo_list.selectedItem.data;
                    canvas.activeTool = _line;
                    // update slider
                    slider_label_txt.text = "Stroke Size";
                    slider_mc.value = _line.lineWidth;
                    slider_2_label_txt.text = "Line Alpha";
                    slider_2_mc.enabled = true;
                    slider_2_mc.snapInterval = .1;
                    slider_2_mc.value = _line.alpha;
                    slider_3_label_txt.visible = false;
                    slider_3_mc.visible = false;
                // rectangle tool
                } else if(toolButton == rectangle_tool_mc) {
                    // set selected tool state
                    rectangle_tool_mc.selected = true;
                    // config and set shape tool as active tool
                    _shape.strokeColor = stroke_color_mc.selectedColor;
                    _shape.fillColor = fill_color_mc.selectedColor;
                    _shape.strokeAlpha = _strokeAlpha;
                    _shape.fillAlpha = _fillAlpha;
                    _shape.type = ShapeType.RECTANGLE;
                    canvas.activeTool = _shape;
                    // set slide value
                    slider_label_txt.text = "Stroke Size";
                    slider_mc.value = _shape.strokeWidth;
                    slider_2_label_txt.text = "Stroke Alpha";
                    slider_2_label_txt.alpha = 1;
                    slider_2_mc.enabled = true;
                    slider_2_mc.snapInterval = .1;
                    slider_2_mc.value = _shape.strokeAlpha;
                    slider_3_label_txt.text = "Fill Alpha";
                    slider_3_label_txt.visible = true;
                    slider_3_label_txt.alpha = 1;
                    slider_3_mc.visible = true;
                    slider_3_mc.enabled = true;
                    slider_3_mc.minimum = 0;
                    slider_3_mc.maximum = 1;
                    slider_3_mc.snapInterval = .1;
                    slider_3_mc.value = _shape.fillAlpha;
                    // hide combo box
                    combo_label_txt.visible = false;
                    combo_list.visible = false;
                // oval tool
                } else if(toolButton == oval_tool_mc) {
                    // set selected tool state
                    oval_tool_mc.selected = true;
                    // config and set shape tool as active tool
                    _shape.strokeColor = stroke_color_mc.selectedColor;
                    _shape.fillColor = fill_color_mc.selectedColor;
                    _shape.strokeAlpha = _strokeAlpha;
                    _shape.fillAlpha = _fillAlpha;
                    _shape.type = ShapeType.OVAL;
                    canvas.activeTool = _shape;
                    // update slider
                    slider_label_txt.text = "Stroke Size";
                    slider_mc.value = _shape.strokeWidth;
                    slider_2_label_txt.text = "Stroke Alpha";
                    slider_2_label_txt.alpha = 1;
                    slider_2_mc.enabled = true;
                    slider_2_mc.snapInterval = .1;
                    slider_2_mc.value = _shape.strokeAlpha;
                    slider_3_label_txt.text = "Fill Alpha";
                    slider_3_label_txt.visible = true;
                    slider_3_label_txt.alpha = 1;
                    slider_3_mc.visible = true;
                    slider_3_mc.enabled = true;
                    slider_3_mc.minimum = 0;
                    slider_3_mc.maximum = 1;
                    slider_3_mc.snapInterval = .1;
                    slider_3_mc.value = _shape.fillAlpha;
                    // hide combo box
                    combo_label_txt.visible = false;
                    combo_list.visible = false;
                // text tool selected
                } else if (toolButton == text_tool_mc || toolButton == selection_tool_mc) {
                    // disable stroke color picker
                    stroke_color_mc.enabled = false;
                    // ui for text
                    slider_label_txt.text = "Text Size";
                    // set font style list
                    combo_label_txt.text = "Font";
                    combo_list.dataProvider = _fontList;
                    combo_list.selectedIndex = _fontIndex;
                    // turn off ui not needed for text tool
                    slider_2_label_txt.visible = false;
                    slider_2_mc.visible = false;
                    slider_3_label_txt.visible = false;
                    slider_3_mc.visible = false;
                    combo_label_txt.x = slider_2_label_txt.x + 8;
                    combo_list.x = slider_2_mc.x;
                    slider_mc.minimum = 10;
                    slider_mc.maximum = 44;
                    slider_mc.value = Number(_textTool.textSettings.textFormat.size);
                    if (toolButton == selection_tool_mc) {
                        selection_tool_mc.selected = true;
                        // set active tool
                        canvas.activeTool = _selectionTool;
                    } else {
                        text_tool_mc.selected = true;
                        var font:Font = Font(combo_list.selectedItem.data);
                        var fmt:TextFormat = new TextFormat();
                        fmt.size = slider_mc.value;
                        fmt.color = fill_color_mc.selectedColor;
                        _textTool.textSettings = new TextSettings(font, fmt);
                        // set active tool
                        canvas.activeTool = _textTool;
                // fill bucket tool selected
                } else if (toolButton == fillbucket_tool_mc) {
                    // turn off ui not needed for fill bucket tool
                    slider_mc.visible = false;
                    slider_label_txt.visible = false;
                    slider_2_label_txt.visible = false;
                    slider_2_mc.visible = false;
                    slider_3_label_txt.visible = false;
                    slider_3_mc.visible = false;
                    combo_label_txt.visible = false;
                    combo_list.visible = false;
                    // turn off stroke color picker
                    this.stroke_color_mc.enabled = false;
                    this._fillBucketTool.fillColor = fill_color_mc.selectedColor;
                    fillbucket_tool_mc.selected = true;
                    // set active tool
                    canvas.activeTool = _fillBucketTool;
                Method    : toolHandler()
                Purpose    : This method will handle switching between brush and eraser
                          tools.  The two tool buttons call this method on click.
                Params    : e -- Mouse Event object.
            private function toolHandler(e:MouseEvent):void {
                setActiveTool(ItemButton(e.currentTarget));
                Method    : comboEventHandler()
                Purpose    : This method will handle the button events for the different
                          Combo box in the UI.
                Params    : e -- Mouse Event object.
            private function comboEventHandler(e:Event):void {
                var font:Font;
                var fmt:TextFormat;
                var ts:TextSettings;
                if(canvas.activeTool is BrushTool) {
                    // store brush shape index
                    _brushShapeIndex = ComboBox(e.currentTarget).selectedIndex;
                    setSelectedBrushShape(ComboBox(e.currentTarget).selectedItem.data);
                } else if(canvas.activeTool is LineTool) {
                    // store line style index
                    _lineStyleIndex = ComboBox(e.currentTarget).selectedIndex;
                    setSelectedLineStyle(ComboBox(e.currentTarget).selectedItem.data);
                } else if (canvas.activeTool is TextTool) {
                    // update font for text tool
                    font = Font(combo_list.selectedItem.data);
                    TextTool(canvas.activeTool).textSettings.font = font;
                    // update font index
                    _fontIndex = combo_list.selectedIndex;
                    // update font for any selected text
                    if (_objectManager.areObjectsSelected()) {
                        fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                        ts = new TextSettings(font, fmt);
                        _objectManager.changeSettingsForSelectedObjects(ts);
                } else if (canvas.activeTool is SelectionTool) {
                    font = Font(combo_list.selectedItem.data);
                    fmt = new TextFormat(null, slider_mc.value, fill_color_mc.selectedColor);
                    ts = new TextSettings(font, fmt);
                    // update font index
                    _fontIndex = combo_list.selectedIndex;
                    // update text tool
                    _textTool.textSettings = ts;
                    // update font for any selected text
                    if (_objectManager.areObjectsSelected()) {
                        _objectManager.changeSettingsForSelectedObjects(ts);
                Method    : setSelectedLineStyle()
                Purpose    : This method will update the active line with a new line
                          type.
                Params    : localType -- Type of Line.
            private function setSelectedLineStyle(localType:String):void {
                // update the Brush object if different type
                if(BitmapTool(canvas.activeTool).type != localType) {
                    BitmapTool(canvas.activeTool).type = localType;       
                Method    : setSelectedBrushShape()
                Purpose    : This method will update the active brush with a new brush
                          type.
                Params    : localType -- Type of Brush.
            private function setSelectedBrushShape(localType:String):void {
                // update the Brush object if different type
                if(BitmapTool(canvas.activeTool).type != localType) {
                    BitmapTool(canvas.activeTool).type = localType;
                Method    : scrollHandler()
                Purpose    : This method handles the event from the mouse scroll wheel.
                Params    : e -- MouseEvent object
            public function scrollHandler(e:MouseEvent):void {
                // calculate and set zoom of canvas
                canvas.zoom += (e.delta/3) * 1;
                // sync slider to new zoom value.
                zoom_slider_mc.value = canvas.zoom;
                // if canvas is zoomed in then display message about dragging canvas around.
                if(canvas.zoom  > 1) {
                    click_message_txt.alpha = 1;
                } else {
                    click_message_txt.alpha = 0;
                Method    : keyHandler()
                Purpose    : This method handle the keyboard shortcut to drag allow
                          the user to drag the canvas with their mouse.
                Params    : e -- KeyboardEvent object
            public function keyHandler(e:KeyboardEvent):void {
                if(!_objectManager.areObjectsSelected()) {
                    if(e.keyCode == Keyboard.SPACE) {
                        if(e.type == KeyboardEvent.KEY_UP) {
                            canvas.mouseDrag = false;
                        } else if(e.type == KeyboardEvent.KEY_DOWN) {
                            canvas.mouseDrag = true;
      

    This might be outdated since the discount is applied to the access portion and accessories only now.
    Verizon Corporate Discount List - HowardForums Wiki
    Verizon Employee Discount List for 2015

  • How can i have the date and time show up on my canon vixia hf m50

    Cannot get the date and time to show up onscreen in ANY videos on my new vixia HF M50. Can somebody help me on this?

    Hello Jerrysulew, 
    You can show the date and time using the Captions option.  The process is described below.
    Add a new level of enjoyment to your scenes by decorating them. You can add animated graphics, stamps and even your own freehand drawings. The supplied stylus pen will be especially useful for decorating scenes.
    You can decorate scenes as they are being recorded.
    IMPORTANT
    The screens and settings that appear may differ depending on the model you are using.
    NOTE
    You can open the decoration screen when the LCD panel is stowed with the LCD screen facing away from the camcorder. In such case, make sure [Autostart Decoration] is set to [On].
    Decorating Scenes while Recording
    1. Touch [ 
    2. Touch [Decoration].
    3. The decoration mode screen appears.
    On the decoration screen, there is a canvas where you can draw freely, and a toolbar with tools lined up for creating your drawings.
    Select the tool you want to use from the toolbar, and make drawings on the canvas.
    Icon
    Tool name
    Function
    Pens and Stamps
    Select the type of pen or stamp and its color. You can also save a canvas or load a previously saved canvas.
    Animated Stamps
    Select animated stamps to add to your decoration.
    Captions
    Add the date, date and time, story title* or story theme* as a caption that will be included in the recording.
    Image Mix**
    Choose one of 27 different frames to add onto the canvas. Image mix can be used in combination with the pens, stamps and animated stamps.
    Freeze screen**
    In recording mode: pause the live video. Touch [ 
     again to restore the live video. You can add decorations to and record the frozen image.
    In playback mode: pause the playback. Touch [ 
     ] to resume playing back the scene.
    Minimize toolbar
    Minimize the toolbar to the top of the screen to view almost all of the canvas. Touch [ 
     ] to restore the toolbar.
    * Not available in 
     mode.
    **Not available in 
     mode and for MP4 movies.
    4. Use a tool from the toolbar as explained in the following procedures.
    5. PressYou can add decorations even while recording a scene.
    6. Touch [ 
     ] to exit the decoration screen.
    NOTE
    For AVCHD movies, decorations will appear in the thumbnails of scenes in the [ AVCHD Movies] index screen and gallery. For MP4 movies, decorations will not appear in thumbnails.
    To use [Pens and Stamps]
    1. Touch [ 
    The [Pens and Stamps] screen will appear.
    2. Select the desired pen or stamp from [Tools].
    Select Colors.
    Touch [ 
    Select white or black from [Colors].
    Alternatively, you can touch [ 
     ] and select a color from the displayed colors.
    3. Draw freely on the canvas.
    Touch [ 
     ] > [Clear] > [Yes] to clear the canvas and start again.
    NOTE
    The canvas with decorations can be deleted, saved, and loaded.
    You can save the decorated canvas right after a decorating action.
    If the memory that contains the canvas is initialized, the canvas will be deleted.
    To use [Animated Stamps]
    1. Touch [ 
    2. Touch one of the control buttons.
    3. Touch anywhere on the canvas to place the selected animated stamp. You can also drag some animated stamps to a different location.
    NOTE
    When the [Animated Stamps] tool is used, the date/time will not be displayed or recorded.
    To use [Captions]
    1. Touch [ 
    2. Touch [Date] or [Time].
    When recording a scene using Story Creator, you can also select [Title]
    (the story&&&&&&&&&s title) or [Story Scene] (the story scene category).
    3. Select the desired text settings and touch [ 
    Touch [ 
     ] (white text on dark background), [ 
     ] (white text) or [ 
     ] (black text).
    Touch the caption and drag it to the desired location.
    To use image mix
    1. Touch [ 
     ] to open the [Select Image] screen.
    2. Touch [ON].
    3. Touch [+] or [-] to select a different image mix frame.
    You can touch one of the memory icons at the bottom of the screen to read image mix frames saved on a different memory (When recording on or playing back scenes from a memory card).
    Touch [ 
     ] to mix the selected frame with the live video.
    NOTE
    When [Rec Media for Movies] is set to [ 
     ] (the built-in memory), you will not be able to select image mix frames saved on a memory card (For camcorders that have internal memory only).
    For AVCHD movies, image mix cannot be selected during playback or while converting a scene to standard definition (For camcorders that have internal memory only). Select the image mix during playback pause or before starting the conversion.
    To use freeze screen
    1. Touch [ 
    The control button will change to [ 
     ] and the picture will be frozen.
    Decorate the screen using the other tools in the palette.
    2. Press the
    The decorations created will be recorded with recording scenes that are on pause.
    Press the
    Touch [ 
     ]. The screen will return to normal.
    Did this answer your question? Please click the Accept as Solution button so that others may find the answer as well.

  • Problem with mutiple BAPI calls during the commit

    Hi all,
    I am trying to create accounts for a given partner i the transaction F9K1 using the BAPI BAPI_BKK_ACCNT_CREATE. After calling the BAPI I am committing it too.
    The problem is if I try to create multiple accounts like RCA, ACA, MCA, IOE and so on, the first time the BAPI is called to create RCA account it is successful an it is even committing. When I call the BAPI to create the the ACA account the return table from the BAPI shows success message but the commit fails. If I restart the program and try creation of accounts now the RCA will throw a error msg saying account already exist, ACA account will be created and then the MCA account creation fails in the same manner explained above.
    I see the issue is with multiple BAPI calls and I tried using all sort of methods like clearing buffers, start new task in local and wait command and all.  But none of them seems to be working for me.
    Can anyone please guide me on how I can overcome this problem.
    Thanks.

    BAPI :
    BAPI BAPI_BKK_ACCNT_CREATE
    Functionality
    Use this method to create an account in Bank Customer Accounts. This method returns the following values:
    Identification details for the newly created account such as the internal and the external account number, and the bank area details
    A table containing error messages
    To create an account by using this method, you must specify values for the import parameters Bank Area (BANKAREA) and Product (PRODUCTNAME).
    Note: You must also specify a value in the External Account Number (EXTERNALACCOUNTNR) parameter if you have defined an external number range for the bank .
    REgards,
    Jayan.

Maybe you are looking for