Link to home
Start Free TrialLog in
Avatar of angielim
angielim

asked on

cut and paste a portion of image using region of interest in Java

Dear all,

as an assignment for my school, I have already created an  Image editor application,
but i have difficulties to add a new option to do Copy and Cut a part of image and Paste it in the new page using region of interest,

I really appreciate if anyone can help me out,
Avatar of shah1d1698
shah1d1698

Avatar of angielim

ASKER

Dear shah,

Thanks alot for the help, but I am still a beginner and I am running out of time, I have to submit this assignment soon, would you please help me out with the code since I have no idea how to use ROI.by the way how to calculate the max and min the region of interest.
your kind assistance will be very much appreciated,
How are u loading the images? Image or BufferedImage??

If you have created the images using Toolkit.getDefaultToolkit().getImage("filename") then use:

image = createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x, y, w, h)));

OR, if u don't want to apply the above method, then convert the image object into BufferedImage using following link:

http://www.javaalmanac.com/egs/java.awt.image/Image2Buf.html

then apply   bufferedImage = bufferedImage.getSubimage(x, y, w, h);

Following example shows how to get the image width and height.....U can simply compile and run the code:

import java.awt.*;
import java.awt.image.*;
import java.awt.Image;
import javax.swing.*;

class ABC extends JFrame
{
   Image image1 = null;
     
   public ABC()
   {
      Cantainer con = getContainer();
      image1 = Toolkit.getDefaultToolkit().getImage("C:/image.jpeg");
//make sure the name & path of the image is correct
//if image file is not found, it will draw a black screen
      int width = image1.getWidth(this);
      int height = image1.getHeight(this);
         
      this.setSize(width+50, height+50);
      this.setVisible(true);

   }
     
    public void paint(Graphics g)
    {
     g.drawImage(image1,0, 0, this);
    }

    public static void main(String aaa[])
   {
        ABC abc = new ABC();
        abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}//end of class
<not ....Cantainer con = getContainer();>
Container for sure...
Container = getContentPane(); // correct this line of code
Here is the corrected version...


import java.awt.*;
import java.awt.image.*;
import java.awt.Image;
import javax.swing.*;

class ABC extends JFrame
{
   Image image1 = null;

   public ABC() throws Exception
   {
      Container con = this.getContentPane();
      MediaTracker tracker = new MediaTracker (this);

      image1 = Toolkit.getDefaultToolkit().getImage("image.jpg");
//make sure the name & path of the image
//if image file is not found, it may draw a black screen
      tracker.addImage (image1, 0);
      tracker.waitForAll();
     
      int width = image1.getWidth(this);
      int height = image1.getHeight(this);
      //image1.
      System.out.println("Width : "+width+" Height : "+height);
      this.setSize(width+50, height+50);
      this.setVisible(true);

   }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(image1,0, 0, this);
    }

    public static void main(String aaa[]) throws Exception
   {
        ABC abc = new ABC();
        abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}//end of class

Dear Shah,

thanks alot, but I want to select a portion of image by dragging the mouse,
something like microsoft paint or photoshop, after selecting a part of image , then cut or copy it in order to paste it in new page,, this is my problem,,

i really appreciate if you can help me for this,,

Here is how u should crop image...(the same example with only one line added)...


import java.awt.*;
import java.awt.image.*;
import java.awt.Image;
import javax.swing.*;

class ABC extends JFrame
{
   Image image1 = null;

   public ABC() throws Exception
   {
      Container con = this.getContentPane();
      MediaTracker tracker = new MediaTracker (this);

      image1 = Toolkit.getDefaultToolkit().getImage("image.jpg");

      image1 = createImage(new FilteredImageSource(image1.getSource(), new CropImageFilter(300, 150, 200, 100)));

//the above line is added..be careful to set the parameters of CropImageFilter(int x, int y, int width, int height)

      tracker.addImage (image1, 0);
      tracker.waitForAll();
     
      int width = image1.getWidth(this);
      int height = image1.getHeight(this);
      //image1.
      System.out.println("Width : "+width+" Height : "+height);
      this.setSize(width+50, height+50);
      this.setVisible(true);

   }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(image1,0, 0, this);
    }

    public static void main(String aaa[]) throws Exception
   {
        ABC abc = new ABC();
        abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}//end of class

>> but I want to select a portion of image by dragging the mouse

In that case u need to use mouse event listener and/or adapter. There u will get methods for getting co-ordinates between mouse press and release...
Dear Shah,

Thanks alot, actually in my program, I did all this function,, I mean I do copy the specified portion of image and paste it also,, but my problem is how to select any part of image by dragging the mouse,,i don want to select the specified part,, as I mentioend I want to do something like photoshop, I wana able to select by dragging the mouse as much as I want,,

the following is the code that I did in my program... the 2 function for copy and paste the specified part of image:

//Copy Region (X,Y,W,H) of the image into clipboard
public void copyImage(int x, int y, int w, int h)
{
      BufferedImage image = canvasPanel.GetImage();
      
      if (image != null)
      {
            BufferedImage copyImage = image.getSubimage(x,y,w,h);
            
            ImageSelection imgSel = new ImageSelection(copyImage);

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            cb.setContents(imgSel, null);

            
      }
      
      
}

//Page copied image in the clipboard into the (X,Y) location of the image
public void pasteImage(int x, int y)
{
      BufferedImage image = canvasPanel.GetImage();

      if (image==null)
            return;

      Transferable t =
Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

   
      try
      {
            if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor))
            {
                  BufferedImage pasteImage =
(BufferedImage)t.getTransferData(DataFlavor.imageFlavor);

                  if (pasteImage!=null)
                  {
                        image.getGraphics().drawImage(pasteImage, x,y, null);
                  }
                  
            }
      }
      catch (UnsupportedFlavorException e)
      {
      }
      catch (IOException e)
      {
      }
      
}
Try running this code.... you'll get some idea about how to track a mouse motion..

import java.awt.*;
import java.awt.image.*;
import java.awt.Image;
import javax.swing.*;
import java.awt.event.*;

class ABC extends JFrame implements MouseMotionListener
{
   Image image1 = null;
   TextArea textArea = null;
   public ABC() throws Exception
   {
      Container con = this.getContentPane();
      BorderLayout bl = new BorderLayout();
      textArea = new TextArea("Roll the mouse over the image\n");
      MediaTracker tracker = new MediaTracker (this);

      image1 = Toolkit.getDefaultToolkit().getImage("image.jpg");
//make sure the name & path of the image
//if image file is not found, it may draw a black screen
      image1 = image1.getScaledInstance(400, 300, Image.SCALE_SMOOTH);
      tracker.addImage (image1, 0);
      tracker.waitForAll();
      int width = image1.getWidth(this);
      int height = image1.getHeight(this);
      System.out.println("Width : "+width+" Height : "+height);
      this.setSize(width+150, height+150);
      this.addMouseMotionListener(this);
      con.add(textArea, bl.SOUTH);
      this.setVisible(true);
   }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(image1,0, 0, this);
    }

//Starting Methods for MouseMotionListener
    public void mouseMoved(MouseEvent e)
    {
     saySomething("Mouse moved", e);
    }

  public void mouseDragged(MouseEvent e)
  {
     saySomething("Mouse dragged", e);
  }

  public void saySomething(String eventDescription, MouseEvent e)
  {
      textArea.append(eventDescription
                      + " (" + e.getX() + "," + e.getY() + ")"
                      + " detected on "
                      + e.getComponent().getClass().getName()
                      + "\n");
  }

  //Ending Methods for MouseMotionListener
   
 
 public static void main(String aaa[]) throws Exception
   {
        ABC abc = new ABC();
        abc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}//end of class
ASKER CERTIFIED SOLUTION
Avatar of shah1d1698
shah1d1698

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Check this version...

I calulated the selected window size in this example.


import java.awt.*;
import java.awt.image.*;
import java.awt.Image;
import javax.swing.*;
import java.awt.event.*;

class DEF extends JFrame implements MouseListener
{
   Image image1 = null;
   TextArea textArea = null;
   int prevX = 0, prevY = 0;
   
   public DEF() throws Exception
   {
      Container con = this.getContentPane();
      BorderLayout bl = new BorderLayout();
      textArea = new TextArea("Select an window on the image\n");
      MediaTracker tracker = new MediaTracker (this);

      image1 = Toolkit.getDefaultToolkit().getImage("image.jpg");
      image1 = image1.getScaledInstance(400, 300, Image.SCALE_SMOOTH);
      tracker.addImage (image1, 0);
      tracker.waitForAll();
      int width = image1.getWidth(this);
      int height = image1.getHeight(this);
      System.out.println("Width : "+width+" Height : "+height);
      this.setSize(width+150, height+150);
      this.addMouseListener(this);
      con.add(textArea, bl.SOUTH);
      this.setVisible(true);
   }

    public void paint(Graphics g)
    {
        super.paint(g);
        g.drawImage(image1,0, 0, this);
    }

    //Starting Methods for MouseListener
      public void mousePressed(MouseEvent e)
      {
          saySomethingForML("\nMouse pressed at "+" (X, Y) = ("+e.getX()+", "+e.getY()+")");
          prevX = e.getX();
          prevY = e.getY();
      }
   
       public void mouseReleased(MouseEvent e)
       {
           int lengthX = Math.abs(prevX - e.getX());
           int lenghtY = Math.abs(prevY - e.getY());
           saySomethingForML("Mouse released at "+" (X, Y) = ("+e.getX()+", "+e.getY()+")\n"
                             +"Selected window size : "+lengthX+" x "
                             +lenghtY+" pixels "
                             +"\nTo do: \n call your implementation of copyImage with"
                             +" public void copyImage("+prevX+", "+prevY
                             +", "+Math.abs(prevX - e.getX())+", "+ Math.abs(prevY - e.getY())+")");
       }
   
       public void mouseEntered(MouseEvent e)
       {
       }
   
       public void mouseExited(MouseEvent e)
       {
       }
   
       public void mouseClicked(MouseEvent e)
       {
       }
   
       public void saySomethingForML(String eventDescription)
       {
           textArea.append(eventDescription + "\n");
       }
   
   
 //Ending Methods for MouseListener  

 public static void main(String aaa[]) throws Exception
   {
        DEF def = new DEF();
        def.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}//end of class
Hi,

I have one program which does selection by dragging the mouse,
I had difficulties to combine it with my program,,

please let me know how to send all of them to you, would you please help me to combine them,,

Let me give u a hint how to combine your programs...

Say u have a class ImageManipulation which extends JFrame. Now u want to give this class some capabilities so that it can handle mouse events on the components of the JFrame like mouse-press, mouse-release etc. In this case all u need to do is to implement MouseListener to the class. And then define the bodies of the methods that come with MouseListener. The structure of your code should be something like this-

public class ImageManipulation extends JFrame implements MouseListener
{

/*Here is all your code*/

//Starting Methods for MouseListener.
//Define the bodies of the following methods as you need.
//You can refer to my last posted code to examine how to select a window on JFrame.  
      public void mousePressed(MouseEvent e)
      {
      }
   
       public void mouseReleased(MouseEvent e)
       {
       }
   
       public void mouseEntered(MouseEvent e)
       {
       }
   
       public void mouseExited(MouseEvent e)
       {
       }
   
       public void mouseClicked(MouseEvent e)
       {
       }
   
 //Ending Methods for MouseListener  


}// end of class


I suggest u better take a good look at my last posted code. If you understand it well, I believe you can do the rest by yourself. If you have any doubt it, you can ask here.


>> I had difficulties to combine it with my program,,

Can you please be specific about what kind of difficulties you are facing while combining the programs? May be you can post the compile error messages here.
Hi,

I did follow what you said, there is no error when i compile, but i have this msg when I run the program,,,

Exception in thread "main" java.lang.NullPointerException
        at Painterr.<init>....
        at Painterr.main<.....>

whats this?
Please post code here, let us examine it.....
hi, Thanks,, I will send you the whole program, all classes,,, Its not the one that I combine,, becasue for that I did some changes to the whole program,, its abit confusing,, so for now i just post the one which i did before,,
how the copy and paste works :

import image, copy the specifeid part, import a new image and paste there, so how to do by dragging the mouse?

here is all the classes:


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.datatransfer.*;


public class Painter extends JFrame
{
      private CanvasPanel             canvasPanel;
      private ToolButtonPanel         toolBar;
      private ColorButtonPanel      colorButtonPanel;
       int  n1,n2,n3,n4,n5,n6,n7,n8,n9;
      private Container                   mainContainer;
      private String fileName;
      private JButton btnok;
      private JTextField
txtfld1,txtfld2,txtfld3,txtfld4,txtfld5,txtfld6,txtfld7,txtfld8,txtfld9;
       private JDesktopPane desktop;
      private Frame newframe;
      int x,y,w,h;
      JMenuBar mainBar;
      JMenu fileMenu, editMenu, setColorMenuItem, aboutMenu;
      JMenuItem newMenuItem, openMenuItem, /*closeMenuItem,*/ saveMenuItem,
saveAsMenuItem, exitMenuItem, undoMenuItem, redoMenuItem,
foreGroundMenuItem, backGroundMenuItem, authorMenuItem, effectsMenu,
brightenincItem, brightendecItem, sharpenItem, edgeDetectItem, blurItem,
      negativeItem , originalItem, grayItem, embossItem,
toolBarItem,rendItem,opentextMenuItem,openimageMenuItem,copyMenuItem,copyImageMenuItem,pasteImageMenuItem;

      // This class is used to hold an image while on the clipboard.
      public static class ImageSelection implements Transferable
      {
            private Image image;    
    //image = createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x, y, w, h)));
   

            public ImageSelection(Image image)
            {
                  this.image = image;
                  //image = createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x, y, w, h)));
            }
   
            // Returns supported flavors
            public DataFlavor[] getTransferDataFlavors()
            {
                  return new DataFlavor[]{DataFlavor.imageFlavor};
            }
   
            // Returns true if flavor is supported
            public boolean isDataFlavorSupported(DataFlavor flavor)
            {
                  return DataFlavor.imageFlavor.equals(flavor);
            }
   
            // Returns image
            public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
            {
                  if (!DataFlavor.imageFlavor.equals(flavor))
                  {
                        throw new UnsupportedFlavorException(flavor);
                  }
                  return image;
            }
      }

private MenuButtonListener menuListener = new MenuButtonListener();
      

      Font fn=new Font("Courier",0,14);
      TextArea ta=new TextArea(5,4);
    String cuttext="",txtmsg="";
      int getcaretpos=0,setcaretpos=0;
      public FileDialog fd1; //Created a Windows like File Dialog Box




      public Painter()
      {
            super("PAINTER");
            fileName = null;
            Box box=Box.createHorizontalBox();
            
            
            fd1=new FileDialog(this,"Open..",FileDialog.LOAD);
            
            mainBar             = new JMenuBar();
            setJMenuBar(mainBar);
/*----------------------------------------------------------------------------*/            
            fileMenu              = new JMenu("File");
            fileMenu.setMnemonic('F');
            
            newMenuItem      = new JMenuItem("New");
            openMenuItem       = new JMenu("Open");
            opentextMenuItem       = new JMenuItem("Open Text");
            openimageMenuItem=new JMenuItem("Open Image");
            saveMenuItem       = new JMenuItem("Save");
            saveAsMenuItem       = new JMenuItem("Save As");
            exitMenuItem      = new JMenuItem("Exit");
            
            newMenuItem.addActionListener(menuListener);
            opentextMenuItem.addActionListener(menuListener);
            openimageMenuItem.addActionListener(menuListener);
            saveMenuItem.addActionListener(menuListener);
            saveAsMenuItem.addActionListener(menuListener);
            //closeMenuItem.addActionListener(menuListener);
            exitMenuItem.addActionListener(menuListener);
            
            fileMenu.add(newMenuItem);
            fileMenu.add(openMenuItem);
            openMenuItem.add(opentextMenuItem);
            openMenuItem.add(openimageMenuItem);
            //fileMenu.add(closeMenuItem);
            fileMenu.addSeparator();
            fileMenu.add(saveMenuItem);
            fileMenu.add(saveAsMenuItem);
            fileMenu.addSeparator();
            fileMenu.add(exitMenuItem);
/*----------------------------------------------------------------------------*/                  
            editMenu = new JMenu("Edit");
            editMenu.setMnemonic('E');
            copyMenuItem       = new JMenuItem("Copy");
            copyImageMenuItem       = new JMenuItem("Copy Image");
            pasteImageMenuItem       = new JMenuItem("Paste Image");
            undoMenuItem         = new JMenuItem("Undo");
            redoMenuItem          = new JMenuItem("Redo");
            
            setColorMenuItem   = new JMenu("Set Color");
            foreGroundMenuItem = new JMenuItem("Set ForeGround");
            backGroundMenuItem = new JMenuItem("Set BackGround");
            copyMenuItem.addActionListener(menuListener);
            copyImageMenuItem.addActionListener(menuListener);
            pasteImageMenuItem.addActionListener(menuListener);
            undoMenuItem.addActionListener(menuListener);
            redoMenuItem.addActionListener(menuListener);
            foreGroundMenuItem.addActionListener(menuListener);
            backGroundMenuItem.addActionListener(menuListener);
            
            setColorMenuItem.add(foreGroundMenuItem);
            setColorMenuItem.add(backGroundMenuItem);
            editMenu.add(copyMenuItem);
            editMenu.add(copyImageMenuItem);
            editMenu.add(pasteImageMenuItem);
            editMenu.add(undoMenuItem);
            editMenu.add(redoMenuItem);
            editMenu.addSeparator();
            editMenu.add(setColorMenuItem);
/*----------------------------------------------------------------------------*/                  
            aboutMenu      = new JMenu("About");
            aboutMenu.setMnemonic('A');
            
            authorMenuItem = new JMenuItem("Author");
            authorMenuItem.addActionListener(menuListener);
            
            aboutMenu.add(authorMenuItem);
            
            //efect menu start

            effectsMenu = new JMenu("Effects");
            effectsMenu.setMnemonic('E');

      JMenu brightenMenu = new JMenu("Brightness");
      brightenMenu.setMnemonic('B');
          brightenincItem = new JMenuItem("Increase");
      brightenincItem.setMnemonic('I');
      brightenincItem.setActionCommand("Increase");
      brightenincItem.addActionListener(menuListener);
     
brightenincItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.CTRL_MASK));
      brightenMenu.add(brightenincItem);

      brightendecItem = new JMenuItem("Decrease");
      brightendecItem.setMnemonic('D');
      brightendecItem.setActionCommand("Decrease");
      brightendecItem.addActionListener(menuListener);
     
brightendecItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, InputEvent.ALT_MASK));
      brightenMenu.add(brightendecItem);

      effectsMenu.add(brightenMenu);

originalItem = new JMenuItem("Original");
      originalItem.setMnemonic('O');
      originalItem.setActionCommand("Original");
      originalItem.addActionListener(menuListener);
      originalItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0,
InputEvent.CTRL_MASK));
      effectsMenu.add(originalItem);

rendItem=new JMenuItem("Rendering Text");
 rendItem.setActionCommand("Rendering");
      rendItem.addActionListener(menuListener);
      rendItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
InputEvent.CTRL_MASK));
effectsMenu.add(rendItem);

      blurItem = new JMenuItem("Blur");
      blurItem.setMnemonic('L');
      blurItem.setActionCommand("Blur");
      blurItem.addActionListener(menuListener);
      blurItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
InputEvent.CTRL_MASK));
      effectsMenu.add(blurItem);

      sharpenItem = new JMenuItem("Sharpen");
      sharpenItem.setMnemonic('S');
      sharpenItem.setActionCommand("Sharpen");
      sharpenItem.addActionListener(menuListener);
      sharpenItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
InputEvent.CTRL_MASK));
      effectsMenu.add(sharpenItem);

      edgeDetectItem = new JMenuItem("Edge detect");
      edgeDetectItem.setMnemonic('E');
      edgeDetectItem.setActionCommand("Edge Detect");
      edgeDetectItem.addActionListener(menuListener);
     
edgeDetectItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, InputEvent.CTRL_MASK));
      effectsMenu.add(edgeDetectItem);

      negativeItem = new JMenuItem("Negative");
      negativeItem.setMnemonic('N');
      negativeItem.setActionCommand("Negative");
      negativeItem.addActionListener(menuListener);
      negativeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5,
InputEvent.CTRL_MASK));
      effectsMenu.add(negativeItem);

      grayItem = new JMenuItem("GrayScale");
      grayItem.setMnemonic('G');
      grayItem.setActionCommand("GrayScale");
      grayItem.addActionListener(menuListener);
      grayItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_6,
InputEvent.CTRL_MASK));
      effectsMenu.add(grayItem);

      embossItem = new JMenuItem("Emboss");
      embossItem.setMnemonic('M');
      embossItem.setActionCommand("Emboss");
      embossItem.addActionListener(menuListener);
      embossItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_7,
InputEvent.CTRL_MASK));
      effectsMenu.add(embossItem);



      

            
/************************** EffectsMenu Ends **/

  JMenu toolMenu = new JMenu("Tool Box");
  toolBarItem = new JCheckBoxMenuItem("Tool Box");
  toolBarItem.addItemListener(
    new ItemListener(){
      public void itemStateChanged(ItemEvent event){
        if (event.getStateChange() == ItemEvent.DESELECTED)
          hideToolBar();
        if (event.getStateChange() == ItemEvent.SELECTED)
          showToolBar();        
      }
    }
  );
  toolMenu.add(toolBarItem);

/*----------------------------------------------------------------------------*/                        
            mainBar.add(fileMenu);
            mainBar.add(editMenu);
            
    mainBar.add(effectsMenu);
    mainBar.add(toolMenu);  mainBar.add(aboutMenu);
/*----------------------------------------------------------------------------*/
            canvasPanel         = new CanvasPanel();
            toolBar   = new ToolButtonPanel(canvasPanel);
            colorButtonPanel  = new ColorButtonPanel(canvasPanel);
            
            mainContainer = getContentPane();

            
            box.add(new JScrollPane(ta));
            
            //mainContainer.add(toolButtonPanel,BorderLayout.NORTH);
            //showToolBar();                  
            mainContainer.add(canvasPanel,BorderLayout.CENTER);
            mainContainer.add(colorButtonPanel,BorderLayout.SOUTH);
            mainContainer.add(box,BorderLayout.SOUTH);
            setSize(700,550);
            this.setResizable(false);
            setVisible(true);
            
            addWindowListener (
                  new WindowAdapter ()
                  {
                        public void windowClosing (WindowEvent e)
                        {
                              System.exit(0);
                        }
                        public void windowDeiconified (WindowEvent e)
                        {
                              canvasPanel.repaint();
                        }
                        public void windowActivated (WindowEvent e)
                        {       
                              canvasPanel.repaint();
                        }
                  }
            );
      }
/*----------------------------------------------------------------------------*/      
  public void hideToolBar(){
    mainContainer.remove(toolBar);
    validate();
  }
  public void showToolBar(){
    mainContainer.add(toolBar, BorderLayout.PAGE_START);
    validate();    
  }
      public class MenuButtonListener implements ActionListener
      {
            public void actionPerformed(ActionEvent event)            
            {
              Object source = event.getSource();
                  if(source == newMenuItem /*|| event.getSource() == closeMenuItem*/)
                  {
                        canvasPanel.clearCanvas();
                        canvasPanel.setDrawMode(0);
                        canvasPanel.setForeGroundColor(Color.WHITE);
                        canvasPanel.setBackGroundColor(Color.BLACK);
                        canvasPanel.repaint();
                        hide();
                        Painter application = new Painter();
                        application.show();

                        
                  }
                  if(source == exitMenuItem)
                  {
                        System.exit(0);
                  }
                  if(source == foreGroundMenuItem)
                  {
                        colorButtonPanel.setForeGroundColor();
                        canvasPanel.repaint();
                  }
                  if(source == backGroundMenuItem)
                  {
                        colorButtonPanel.setBackGroundColor();
                        canvasPanel.repaint();
                  }
                  if(source == authorMenuItem)
                  {
                        JOptionPane.showMessageDialog(Painter.this,"Overview : The Painter is an image processing/enhancing application that provides \nthe user he ability to do image processin. The user can alter \nthe brightness of the image, apply effect such as blur, sharpen, \nedge detect, negative, grayscale or emboss. The image can be either \nblack-and-white or color, and can be saved as jpg files. \nYou can also use Painter to work with other file format \nsuch as .jpg, .gif, or .bmp files.","Painter",JOptionPane.INFORMATION_MESSAGE);
                        canvasPanel.repaint();
                  }
                  if(source == saveMenuItem) canvasPanel.SaveCanvasToFile();
                  if(source == copyMenuItem) copytext();
                  /* this is just a test data, ya gotta implement a way to select region (hint: use draw box, on mouse down and on mouse up)*/
                  
   


                  if(source == copyImageMenuItem) copyImage(0,0, 100, 100); /*See copyImage declarations for more info on parameters*/
                  if(source == pasteImageMenuItem) pasteImage(50,50); /*see copyImage declarations for more info on parameters*/
                  
                  if(source == saveAsMenuItem)  canvasPanel.SaveAsCanvasToFile();
                  if(source == openimageMenuItem) canvasPanel.OpenCanvasFile();
                  if(source == opentextMenuItem) opentext();
                  if(source == undoMenuItem) canvasPanel.undo();
                  if(source == redoMenuItem) canvasPanel.redo();
      if(source == brightenincItem) canvasPanel.brighteninc();
      if(source == brightendecItem) canvasPanel.brightendec();
      if(source == blurItem) canvasPanel.blur();
      if(source == sharpenItem) {
             
                  JFrame jf=new JFrame();
                  jf.setBounds(350,65,110,140);
                  //to set the size and location of the frame
                  Container c=jf.getContentPane();
                  //in swing the components are always added to the content pane
                  c.setLayout(new FlowLayout());
                  //sets the layout of container as flow layout
                  txtfld1=new JTextField(2);
                  txtfld2=new JTextField(2);
                  txtfld3=new JTextField(2);txtfld4=new JTextField(2);txtfld5=new
JTextField(2);
                  txtfld6=new JTextField(2);txtfld7=new JTextField(2);txtfld8=new
JTextField(2);txtfld9=new JTextField(2);

                  btnok=new JButton("OK");

                  
c.add(txtfld1);c.add(txtfld2);c.add(txtfld3);c.add(txtfld4);c.add(txtfld5);c.add(txtfld6);c.add(txtfld7);c.add(txtfld8);c.add(txtfld9);
                  c.add(btnok);
                  jf.show();
                  
                  
                  

}
      if(source == rendItem) repaint();
      if(source == edgeDetectItem) canvasPanel.edgeDetect();
      if(source == negativeItem) canvasPanel.negative();
      if(source == originalItem) canvasPanel.origImage();
      if(source == grayItem) canvasPanel.grayImage();
      if(source == embossItem) canvasPanel.emboss();
            }
      }

/*----------------------------------------------------------------------------*/
 public void opentext()
      {      
            
            txtmsg="";
                  fd1.setVisible(true);
                  String filename=fd1.getFile();
                  String dirname=fd1.getDirectory();
                  
                  File openfile=new File(dirname,filename);
                  //creates a file object for a file obtd. from dialog box

                  try
                  {
                        FileInputStream fis=new FileInputStream(openfile);
                        //creates an input stream
                        //streams are like passages for data

                        int bytelength=fis.available();
                        //calculates the file size

                        for (int bytecount=0;bytecount<bytelength;bytecount++)
                        {
                              //this loop runs till end of file
                              char fch=(char)fis.read();
                              txtmsg=txtmsg+fch;
                        }
                        ta.setText(txtmsg);
                  }
                  catch(Exception ioe)
                  {
                        System.out.println("An exception has occured");
                  }      
      }

public void copytext()
{
      cuttext=ta.getSelectedText();
}
//image = createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x, y, w, h)));
   


//Copy Region (X,Y,W,H) of the image into clipboard
public void copyImage(int x, int y, int w, int h)
{
      BufferedImage image = canvasPanel.GetImage();
      
      if (image != null)
      {
            BufferedImage copyImage = image.getSubimage(x,y,w,h);
            
            ImageSelection imgSel = new ImageSelection(copyImage);

            Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
            cb.setContents(imgSel, null);

            
      }
      
      
}

//Page copied image in the clipboard into the (X,Y) location of the image
public void pasteImage(int x, int y)
{
      BufferedImage image = canvasPanel.GetImage();

      if (image==null)
            return;

      Transferable t =
Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);

   
      try
      {
            if (t != null && t.isDataFlavorSupported(DataFlavor.imageFlavor))
            {
                  BufferedImage pasteImage =
(BufferedImage)t.getTransferData(DataFlavor.imageFlavor);

                  if (pasteImage!=null)
                  {
                        image.getGraphics().drawImage(pasteImage, x,y, null);
                  }
                  
            }
      }
      catch (UnsupportedFlavorException e)
      {
      }
      catch (IOException e)
      {
      }
      
}


public void paint(Graphics g)
            {
            super.paint(g);
            Graphics2D g2=(Graphics2D)g;
            
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
            Dimension d=getSize();
            AffineTransform
ct=AffineTransform.getTranslateInstance(d.width/2,d.height*3/4);
            g2.transform(ct);
            Font f=new Font("Serif", Font.PLAIN,87);
            g2.setFont(f);
            int limit=6;
            for(int i=1;i<=limit;i++)
            {
                  AffineTransform oldTransform = g2.getTransform();
                  float ratio=(float)i / (float)limit;
                  g2.transform(AffineTransform.getRotateInstance(
                        Math.PI * (ratio - 1.0f)));
                  float alpha=((i==limit) ? 1.0f : ratio/3);
                  g2.setComposite(AlphaComposite.getInstance(
                        AlphaComposite.SRC_OVER, alpha));
                  g2.drawString(cuttext,0,0);
                  g2.setTransform(oldTransform);
                  }
            }

private class ActionEventHandler implements ActionListener{
                  public void actionPerformed(ActionEvent event)
                  {
                        if(event.getSource() == btnok)
                                 {
                             n1=Integer.parseInt(txtfld1.getText());
                            
n2=Integer.parseInt(txtfld2.getText());n3=Integer.parseInt(txtfld3.getText());n4=Integer.parseInt(txtfld4.getText());n5=Integer.parseInt(txtfld5.getText());n6=Integer.parseInt(txtfld6.getText());n7=Integer.parseInt(txtfld7.getText());n8=Integer.parseInt(txtfld8.getText());n9=Integer.parseInt(txtfld9.getText());
                  canvasPanel.sharpen(n1,n2,n3,n4,n5,n6,n7,n8,n9);
                          
                        }
                  }}
      
/*----------------------------------------------------------------------------*/
      public static void main(String args[])
      {
            Painter application = new Painter();
            
            //Frame frame=new applicationFrame("text Rendering"){
            
            //frame.setVisible(true);
application.show();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
}




*********************************************************


import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class ToolButtonPanel extends JToolBar
{
      private JButton lineBtn, squareBtn, ovalBtn, polygonBtn, roundRectBtn,
freeHandBtn, undoBtn, redoBtn, clearBtn;            
      
      private JCheckBox fullChk;
      private CanvasPanel canvasPanel;
      private JSlider brightenSlider;
      private int brightnessCurrentValue = 0;
      private int brightnessMaxValue = 10;
      private int brightnessMinValue = -10;
      
      public ToolButtonPanel(CanvasPanel inCanvasPanel)
      {
            canvasPanel = inCanvasPanel;
/*----------------------------------------------------------------------------*/            
            lineBtn                  = new JButton("",new ImageIcon("straight_line.gif"));
            squareBtn            = new JButton("",new ImageIcon("square.gif"));
            ovalBtn                   = new JButton("",new ImageIcon("circle.gif"));
            polygonBtn            = new JButton("",new ImageIcon("polygon.gif"));
            roundRectBtn      = new JButton("",new ImageIcon("rounded_square.gif"));
            freeHandBtn            = new JButton("",new ImageIcon("freehand.gif"));
            undoBtn                  = new JButton("",new ImageIcon("undo.gif"));
            redoBtn                  = new JButton("",new ImageIcon("redo.gif"));
            clearBtn            = new JButton("",new ImageIcon("clear.gif"));
            
            lineBtn.addActionListener(new ToolButtonListener());
            lineBtn.setToolTipText("Line");
            squareBtn.addActionListener(new ToolButtonListener());
            squareBtn.setToolTipText("Retangle");
            ovalBtn.addActionListener(new ToolButtonListener());
            ovalBtn.setToolTipText("Oval");
            polygonBtn.addActionListener(new ToolButtonListener());
            polygonBtn.setToolTipText("Polygon");
            roundRectBtn.addActionListener(new ToolButtonListener());
            roundRectBtn.setToolTipText("Rectangle");
            freeHandBtn.addActionListener(new ToolButtonListener());
            freeHandBtn.setToolTipText("Free Hand");
            undoBtn.addActionListener(new ToolButtonListener());
            undoBtn.setToolTipText("Undo");
            redoBtn.addActionListener(new ToolButtonListener());
            redoBtn.setToolTipText("Redo");
            clearBtn.addActionListener(new ToolButtonListener());
            clearBtn.setToolTipText("Clear Canvas");
            
            brightenSlider =
              new JSlider(JSlider.HORIZONTAL,brightnessMinValue,
                        brightnessMaxValue, brightnessCurrentValue);
            brightenSlider.addChangeListener(
              new ChangeListener(){
                public void stateChanged(ChangeEvent e){
                  JSlider source = (JSlider)e.getSource();
                  if (!source.getValueIsAdjusting()) {
            int brightnessValue = (int)source.getValue();
            if (brightnessValue > brightnessCurrentValue)
              canvasPanel.brighteninc();
            if (brightnessValue < brightnessCurrentValue)
              canvasPanel.brightendec();
            brightnessCurrentValue = brightnessValue;            
          }
                }
              }
            );
            
            JLabel brightenSliderLabel = new JLabel("Brightness :");
/*----------------------------------------------------------------------------*/            
            fullChk = new JCheckBox("Full");
            fullChk.addItemListener(
                  new ItemListener()
                  {
                        public void itemStateChanged(ItemEvent event)
                        {
                              if(fullChk.isSelected())
                                    canvasPanel.setSolidMode(Boolean.TRUE);
                              else
                                    canvasPanel.setSolidMode(Boolean.FALSE);
                        }      
                  }
            );
/*----------------------------------------------------------------------------*/            
            //this.setLayout(new GridLayout(1,9)); // 8 Buttons & 1 CheckBox
            this.add(lineBtn);
            this.add(squareBtn);
            this.add(ovalBtn);
            this.add(polygonBtn);
            this.add(roundRectBtn);
            this.add(freeHandBtn);
            this.add(undoBtn);
            this.add(redoBtn);
            this.add(clearBtn);
            this.add(fullChk);
            this.addSeparator();
            this.add(brightenSliderLabel);
            this.add(brightenSlider);
      }
/*----------------------------------------------------------------------------*/
      private class ToolButtonListener implements ActionListener
      {
            public void actionPerformed(ActionEvent event)
            {      
                  if(canvasPanel.isExistPolygonBuffer()!= false)
                  {
                        canvasPanel.flushPolygonBuffer();
                  }
                  if(event.getSource() == lineBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.LINE);            
                  }
                  if(event.getSource() == squareBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.SQUARE);
                  }
                  if(event.getSource() == ovalBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.OVAL);
                  }
                  if(event.getSource() == polygonBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.POLYGON);
                  }
                  if(event.getSource() == roundRectBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.ROUND_RECT);
                  }
                  if(event.getSource() == freeHandBtn)
                  {
                        canvasPanel.setDrawMode(canvasPanel.FREE_HAND);
                  }
                  if(event.getSource() == undoBtn)
                  {
                        canvasPanel.undo();
                  }
                  if(event.getSource() == redoBtn)
                  {
                        canvasPanel.redo();
                  }
                  if(event.getSource() == clearBtn)
                  {
                        canvasPanel.clearCanvas();
                  }
            }
      }
}




********************************************************

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class ColorButtonPanel extends JPanel
{
      private JPanel colorButtonPanel;
      private JButton foreGroundColorBtn,backGroundColorBtn;
      private JLabel
foreGroundColorLbl,backGroundColorLbl,foreColorLbl,backColorLbl;
      private Color foreColor, backColor;
      private CanvasPanel canvasPanel;
      
      public ColorButtonPanel(CanvasPanel inCanvasPanel)
      {
            canvasPanel = inCanvasPanel;      
            foreGroundColorLbl = new JLabel("   ");
            foreGroundColorLbl.setOpaque(true);
            foreGroundColorLbl.setBackground(canvasPanel.getForeGroundColor());
            
foreGroundColorLbl.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            
            backGroundColorLbl = new JLabel("   ");
            backGroundColorLbl.setOpaque(true);
            backGroundColorLbl.setBackground(canvasPanel.getBackGroundColor());
            
backGroundColorLbl.setBorder(BorderFactory.createLineBorder(Color.WHITE));
            
            foreGroundColorBtn = new JButton("ForeGroundColor->");
            foreGroundColorBtn.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed(ActionEvent event)
                        {
                              setForeGroundColor();
                        }
                  }
            );
            
            backGroundColorBtn = new JButton("BackGroundColor->");
            backGroundColorBtn.addActionListener(
                  new ActionListener()
                  {
                        public void actionPerformed(ActionEvent event)
                        {
                              setBackGroundColor();
                        }
                  }
            );
      
            this.setLayout(new GridLayout(1,4));
            this.add(foreGroundColorBtn);
            this.add(foreGroundColorLbl);
            this.add(backGroundColorBtn);
            this.add(backGroundColorLbl);
      }
/*----------------------------------------------------------------------------*/      
      public void setForeGroundColor()
      {
            foreColor = JColorChooser.showDialog(null,"ForeGround Color",foreColor);
            if(foreColor!=null)
            {
                  foreGroundColorLbl.setBackground(foreColor);
                  canvasPanel.setForeGroundColor(foreColor);
            }
      }
/*----------------------------------------------------------------------------*/
      public void setBackGroundColor()
      {
            backColor = JColorChooser.showDialog(null,"BackGround Color",backColor);
            if(backColor!=null)
            {
                  backGroundColorLbl.setBackground(backColor);
                  canvasPanel.setBackGroundColor(backColor);
            }
      }
}



****************************************************************

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
import javax.swing.JOptionPane;



public class CanvasPanel extends JPanel implements  
MouseListener,MouseMotionListener, Serializable
{
      protected final static int
LINE=1,SQUARE=2,OVAL=3,POLYGON=4,ROUND_RECT=5,FREE_HAND=6,
                                                SOLID_SQUARE=22, SOLID_OVAL=33, SOLID_POLYGON=44,
                                                SOLID_ROUND_RECT=55;
      protected static Vector
vLine,vSquare,vOval,vPolygon,vRoundRect,vFreeHand,
                                           vSolidSquare,vSolidOval,vSolidPolygon,vSolidRoundRect,vFile,
                                           xPolygon, yPolygon;
      
      private Stack undoStack, redoStack;

      private Color foreGroundColor, backGroundColor;

      private int x1,y1,x2,y2,linex1,linex2,liney1,liney2, drawMode=0;
      private boolean solidMode, polygonBuffer;

      private File fileName;
      



private BufferedImage image = null;

      public CanvasPanel()
      {
            
            vLine                   = new Vector();
            vSquare             = new Vector();
            vOval                  = new Vector();
            vPolygon            = new Vector();
            vRoundRect            = new Vector();
            vFreeHand            = new Vector();
            vSolidSquare      = new Vector();
            vSolidOval            = new Vector();
            vSolidPolygon      = new Vector();
            vSolidRoundRect      = new Vector();
            vFile                  = new Vector();
            xPolygon            = new Vector();
            yPolygon            = new Vector();

            addMouseListener(this);
            addMouseMotionListener(this);
            //fd1=new FileDialog(this,"Open..",FileDialog.LOAD);
            solidMode             = false;
            polygonBuffer       = false;

            foreGroundColor = Color.WHITE;
            backGroundColor = Color.BLACK;
            setBackground(backGroundColor);

            undoStack = new Stack();
            redoStack = new Stack();

            repaint();
      }




/*----------------------------------------------------------------------------*/

      BufferedImage GetImage() { return image;}

/*----------------------------------------------------------------------------*/



/*----------------------------------------------------------------------------*/
      public void mousePressed(MouseEvent event)
      {
            x1 = linex1 = linex2 = event.getX();
        y1 = liney1 = liney2 = event.getY();
      }
/*----------------------------------------------------------------------------*/
      public void mouseClicked(MouseEvent event){}
      public void mouseMoved(MouseEvent event){}
/*----------------------------------------------------------------------------*/
      public void mouseReleased(MouseEvent event)
      {
            if (drawMode == LINE)
        {
                 vLine.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                 undoStack.push(new StepInfo(LINE ,new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
        }
        if (drawMode == SQUARE)
        {
            if(solidMode)
                 {
                       if(x1 > event.getX() || y1 > event.getY())
                        {
                             vSolidSquare.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                             undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                       }
                       else
                       {
                             vSolidSquare.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                             undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                       }
                 }
            else
            {
                       if(x1 > event.getX() || y1 > event.getY())
                       {
                             vSquare.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                             undoStack.push(new StepInfo(SQUARE, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                       }
                       else
                       {
                             vSquare.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                             undoStack.push(new StepInfo(SQUARE, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                       }
                 }
        }
        if (drawMode == this.OVAL)
        {
                if(solidMode)
                {
                      if(x1 > event.getX() || y1 > event.getY())
                      {
                            vSolidOval.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                            undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                      }
                      else
                      {
                            vSolidOval.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                            undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                      }
                 }
                 else
                 {
                       if(x1 > event.getX() || y1 > event.getY())
                       {
                             vOval.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                             undoStack.push(new StepInfo(OVAL, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                       }
                       else
                       {
                             vOval.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                             undoStack.push(new StepInfo(OVAL, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                       }
                 }
        }
        if (drawMode == this.POLYGON || drawMode == this.SOLID_POLYGON)
        {
              xPolygon.add(new Integer(event.getX()));
              yPolygon.add(new Integer(event.getY()));
              polygonBuffer = true;
              repaint();
        }
        if (drawMode == this.ROUND_RECT)
        {
                if(solidMode)
                {
                      if(x1 > event.getX() || y1 > event.getY())
                      {
                            vSolidRoundRect.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                            undoStack.push(new StepInfo(SOLID_ROUND_RECT, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                      }
                      else
                      {
                             vSolidRoundRect.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                             undoStack.push(new StepInfo(SOLID_ROUND_RECT, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                       }
                 }
                 else
                 {
                       if(x1 > event.getX() || y1 > event.getY())
                       {
                             vRoundRect.add(new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor));
                             undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(event.getX(),event.getY(),x1,y1,foreGroundColor)));
                       }
                       else
                       {
                             vRoundRect.add(new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor));
                             undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(x1,y1,event.getX(),event.getY(),foreGroundColor)));
                       }
                 }
        }
        x1=linex1=x2=linex2=0;
        y1=liney1=y2=liney2=0;
      }
/*----------------------------------------------------------------------------*/
      public void mouseEntered(MouseEvent event)
      {
            setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
      }
/*----------------------------------------------------------------------------*/
      public void mouseExited(MouseEvent event)
      {
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
      }
/*----------------------------------------------------------------------------*/
      public void mouseDragged(MouseEvent event)
      {
        x2 = event.getX();
        y2 = event.getY();

        if (drawMode == this.FREE_HAND)
        {
            linex1 = linex2;
            liney1 = liney2;
            linex2 = x2;
            liney2 = y2;

            vFreeHand.add(new
Coordinate(linex1,liney1,linex2,liney2,foreGroundColor));
               undoStack.push(new StepInfo(FREE_HAND, new
Coordinate(linex1,liney1,linex2,liney2,foreGroundColor)));
         }
         repaint();
      }
/*----------------------------------------------------------------------------*/
      public void paintComponent(Graphics g)
      {
            super.paintComponent(g);
    if (image != null){
      g.drawImage(image, 0, 0, null);
    }

            redrawVectorBuffer(g);

              g.setColor(foreGroundColor);

            if (drawMode == LINE)
            {
              g.drawLine(x1,y1,x2,y2);
            }
            if (drawMode == OVAL)
            {
                   if(solidMode)
                   {
                     if(x1 > x2 || y1 > y2)
                           g.fillOval(x2,y2,x1-x2,y1-y2);
                     else
                           g.fillOval(x1,y1,x2-x1,y2-y1);
                   }
               else
               {
                     if(x1 > x2 || y1 > y2)
                           g.drawOval (x2,y2,x1-x2,y1-y2);
                     else
                           g.drawOval (x1,y1,x2-x1,y2-y1);
               }
            }
            if (drawMode == ROUND_RECT)
            {
               if(solidMode)
               {
                     if(x1 > x2 || y1 > y2)
                           g.fillRoundRect(x2,y2,x1-x2,y1-y2,25,25);
                     else
                           g.fillRoundRect(x1,y1,x2-x1,y2-y1,25,25);
               }
               else
               {
                     if(x1 > x2 || y1 > y2)
                           g.drawRoundRect(x2,y2,x1-x2,y1-y2,25,25);
                     else
                           g.drawRoundRect(x1,y1,x2-x1,y2-y1,25,25);
               }
            }
            if (drawMode == SQUARE)
            {
                   if(solidMode)
                   {
                         if(x1 > x2 || y1 > y2)
                               g.fillRect (x2,y2,x1-x2,y1-y2);
                         else
                               g.fillRect (x1,y1,x2-x1,y2-y1);
                   }
               else
               {
                     if(x1 > x2 || y1 > y2)
                           g.drawRect (x2,y2,x1-x2,y1-y2);
                     else
                           g.drawRect (x1,y1,x2-x1,y2-y1);
                  
               }
            }
            if (drawMode == POLYGON || drawMode == SOLID_POLYGON)
            {
                  int xPos[] = new int[xPolygon.size()];
                   int yPos[] = new int[yPolygon.size()];

                   for(int count=0;count<xPos.length;count++)
                   {
                         xPos[count] =
((Integer)(xPolygon.elementAt(count))).intValue();
                         yPos[count] =
((Integer)(yPolygon.elementAt(count))).intValue();
                   }
                   g.drawPolyline(xPos,yPos,xPos.length);
                   polygonBuffer = true;
              }
            if (drawMode == FREE_HAND)
            {
               g.drawLine(linex1,liney1,linex2,liney2);
            }
      }
/*----------------------------------------------------------------------------*/
      public void setDrawMode(int mode)
      {
            drawMode = mode;
      }
      public int getDrawMode()
      {
            return drawMode;
      }
/*----------------------------------------------------------------------------*/
      public void setSolidMode(Boolean inSolidMode)
      {
            solidMode = inSolidMode.booleanValue();
      }
      public Boolean getSolidMode()
      {
            return Boolean.valueOf(solidMode);
      }
/*----------------------------------------------------------------------------*/
      public void setForeGroundColor(Color inputColor)
      {
            foreGroundColor = inputColor;
      }
      public Color getForeGroundColor()
      {
            return foreGroundColor;
      }
/*----------------------------------------------------------------------------*/
      public void setBackGroundColor(Color inputColor)
      {
            backGroundColor = inputColor;
            this.setBackground(backGroundColor);
      }
      public Color getBackGroundColor()
      {
            return backGroundColor;
      }
/*----------------------------------------------------------------------------*/
      public void undo()
      {
            StepInfo tempInfo;

            if(undoStack.isEmpty())
                  JOptionPane.showMessageDialog(null, "Can't Undo","Painter", JOptionPane.INFORMATION_MESSAGE);
            else
            {
                  tempInfo = (StepInfo)undoStack.pop();

                  switch(tempInfo.getStepType())
                  {
                        case 1:      vLine.remove(vLine.size()-1);
                              break;
                        case 2:      vSquare.remove(vSquare.size()-1);
                              break;
                        case 3:      vOval.remove(vOval.size()-1);
                              break;
                        case 4:      vPolygon.remove(vPolygon.size()-1);
                              break;
                        case 5:      vRoundRect.remove(vRoundRect.size()-1);
                              break;
                        case 6:      vFreeHand.remove(vFreeHand.size()-1);
                              break;
                        case 22:vSolidSquare.remove(vSolidSquare.size()-1);
                              break;
                        case 33:vSolidOval.remove(vSolidOval.size()-1);
                              break;
                        case 44:vSolidPolygon.remove(vSolidPolygon.size()-1);
                              break;
                        case 55:vSolidRoundRect.remove(vSolidRoundRect.size()-1);
                              break;
                  }
                  redoStack.push(tempInfo);
            }
            repaint();
      }
/*----------------------------------------------------------------------------*/
      public void redo()
      {
            StepInfo tempInfo;

            if(redoStack.isEmpty())
                  JOptionPane.showMessageDialog(null,"Can't Redo","Painter",JOptionPane.INFORMATION_MESSAGE);
            else
            {
                  tempInfo = (StepInfo)redoStack.pop();

                  switch(tempInfo.getStepType())
                  {
                        case 1:      vLine.add(tempInfo.getStepCoordinate());
                              break;
                        case 2:      vSquare.add(tempInfo.getStepCoordinate());
                              break;
                        case 3:      vOval.add(tempInfo.getStepCoordinate());
                              break;
                        case 4:      vPolygon.add(tempInfo.getStepCoordinate());
                              break;
                        case 5:      vRoundRect.add(tempInfo.getStepCoordinate());
                              break;
                        case 6:      vFreeHand.add(tempInfo.getStepCoordinate());
                              break;
                        case 22:vSolidSquare.add(tempInfo.getStepCoordinate());
                              break;
                        case 33:vSolidOval.add(tempInfo.getStepCoordinate());
                              break;
                        case 44:vSolidPolygon.add(tempInfo.getStepCoordinate());
                              break;
                        case 55:vSolidRoundRect.add(tempInfo.getStepCoordinate());
                              break;
                  }
                  undoStack.push(tempInfo);
            }
            repaint();
      }
/*----------------------------------------------------------------------------*/
      public void clearCanvas()
      {
            vFreeHand.removeAllElements();
            vLine.removeAllElements();
            vOval.removeAllElements();
            vPolygon.removeAllElements();
            vRoundRect.removeAllElements();
            vSolidOval.removeAllElements();
            vSolidPolygon.removeAllElements();
            vSolidRoundRect.removeAllElements();
            vSolidSquare.removeAllElements();
            vSquare.removeAllElements();
            undoStack.clear();
            redoStack.clear();
            repaint();
      }
/*----------------------------------------------------------------------------*/
      public void SaveCanvasToFile()
      {
            if(fileName != null)
            {
                  BufferedImage rendImage = myCreateImage();
                  try
                  {
                    File file = new File(fileName.toString());
                    ImageIO.write(rendImage, "jpg", file);
                  this.image = rendImage;
                }catch (IOException e) {}
            }
            else
            {
                  SaveAsCanvasToFile();
            }
            repaint();
JOptionPane.showMessageDialog(null,"The file has been successfully saved.");
      }
/*----------------------------------------------------------------------------*/
      public void SaveAsCanvasToFile()
      {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result = fileChooser.showSaveDialog(null);

            if(result == JFileChooser.CANCEL_OPTION) return;

            fileName = fileChooser.getSelectedFile();

            if(fileName == null || fileName.getName().equals(""))
                  JOptionPane.showMessageDialog(null,"Invalid File Name","Painter",JOptionPane.ERROR_MESSAGE);
            else
            {

                  BufferedImage rendImage = myCreateImage();

                  try {
                    File file = new File(fileName.toString());
                    ImageIO.write(rendImage, "jpg", file);
this.image = rendImage;

                }catch (IOException e) {}
            }
      repaint();
      JOptionPane.showMessageDialog(null,"The file has been successfully saved.");
      }
/*----------------------------------------------------------------------------*/
      public void OpenCanvasFile()
      {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter()
            { public boolean accept(File f)
              {  String name = f.getName().toLowerCase();
                 return name.endsWith(".gif")
                     || name.endsWith(".jpg")
                     || name.endsWith(".jpeg")
                     || name.endsWith(".png")
                     || name.endsWith(".tif")
                     || name.endsWith(".bmp")
                     || f.isDirectory();
               }
               public String getDescription()
               {  return "Image files";
               }
            });



            int result = fileChooser.showOpenDialog(null);

            if(result == JFileChooser.CANCEL_OPTION) return;
            if(result == JFileChooser.APPROVE_OPTION){
              fileName = fileChooser.getSelectedFile();
              String name = fileName.getAbsolutePath();
              loadImage(name);
            }
            repaint();
      }

      

/*----------------------------------------------------------------------------*/
      public boolean isExistPolygonBuffer()
      {
            return polygonBuffer;
      }
/*----------------------------------------------------------------------------*/
      public void flushPolygonBuffer()
      {
            if(!solidMode)
            {
                  vPolygon.add(new Coordinate(xPolygon, yPolygon, foreGroundColor));
                  undoStack.push(new StepInfo(POLYGON,new Coordinate(xPolygon,
yPolygon, foreGroundColor)));
            }
            else
            {
                  vSolidPolygon.add(new Coordinate(xPolygon, yPolygon,
foreGroundColor));
                  undoStack.push(new StepInfo(SOLID_POLYGON,new Coordinate(xPolygon,
yPolygon, foreGroundColor)));
            }

            xPolygon.removeAllElements();
            yPolygon.removeAllElements();

            polygonBuffer = false;
            repaint();
      }
/*----------------------------------------------------------------------------*/
      private class Coordinate implements Serializable
      {
            private int x1,y1,x2,y2;
            private Color foreColor;
            private Vector xPoly, yPoly;

            public Coordinate (int inx1,int iny1,int inx2, int iny2, Color color)
            {
              x1 = inx1;
               y1 = iny1;
               x2 = inx2;
               y2 = iny2;
               foreColor = color;
            }
            public Coordinate(Vector inXPolygon, Vector inYPolygon, Color color)
            {
                  xPoly = (Vector)inXPolygon.clone();
                  yPoly = (Vector)inYPolygon.clone();
                  foreColor = color;
            }
            public Color colour()
            {
              return foreColor;
            }
            public int getX1 ()
            {
              return x1;
            }
            public int getX2 ()
            {
              return x2;
            }
            public int getY1 ()
            {
              return y1;
            }
            public int getY2 ()
            {
              return y2;
            }
            public Vector getXPolygon()
            {
                  return xPoly;
            }
            public Vector getYPolygon()
            {
                  return yPoly;
            }
      }
/*----------------------------------------------------------------------------*/
      private class StepInfo implements Serializable
      {
            private int stepType;
            private Coordinate stepCoordinate;

            public StepInfo(int inStepType, Coordinate inStepCoordinate)
            {
                  stepType = inStepType;
                  stepCoordinate = inStepCoordinate;
            }
            public int getStepType()
            {
                  return stepType;
            }
            public Coordinate getStepCoordinate()
            {
                  return stepCoordinate;
            }
      }
/*----------------------------------------------------------------------------*/
      private BufferedImage myCreateImage()
      {
        BufferedImage bufferedImage =new BufferedImage(600,390,
BufferedImage.TYPE_INT_RGB);

        Graphics g = bufferedImage.createGraphics();
if(this.image!=null){
g.drawImage(image, 0, 0, null);
}

          redrawVectorBuffer(g);

            g.dispose();
            return bufferedImage;
    }
/*----------------------------------------------------------------------------*/
    private void redrawVectorBuffer(Graphics g)
    {
          for (int i=0;i<vFreeHand.size();i++){
              g.setColor(((Coordinate)vFreeHand.elementAt(i)).colour());
               
g.drawLine(((Coordinate)vFreeHand.elementAt(i)).getX1(),((Coordinate)vFreeHand.elementAt(i)).getY1(),((Coordinate)vFreeHand.elementAt(i)).getX2(),((Coordinate)vFreeHand.elementAt(i)).getY2());
            }
            for (int i=0;i<vLine.size();i++){
               g.setColor(((Coordinate)vLine.elementAt(i)).colour());
               
g.drawLine(((Coordinate)vLine.elementAt(i)).getX1(),((Coordinate)vLine.elementAt(i)).getY1(),((Coordinate)vLine.elementAt(i)).getX2(),((Coordinate)vLine.elementAt(i)).getY2());
            }
              for (int i=0;i<vOval.size();i++){
               g.setColor(((Coordinate)vOval.elementAt(i)).colour());
               
g.drawOval(((Coordinate)vOval.elementAt(i)).getX1(),((Coordinate)vOval.elementAt(i)).getY1(),((Coordinate)vOval.elementAt(i)).getX2()-((Coordinate)vOval.elementAt(i)).getX1(),((Coordinate)vOval.elementAt(i)).getY2()-((Coordinate)vOval.elementAt(i)).getY1());
            }
            for (int i=0;i<vRoundRect.size();i++){
               g.setColor(((Coordinate)vRoundRect.elementAt(i)).colour());
               
g.drawRoundRect(((Coordinate)vRoundRect.elementAt(i)).getX1(),((Coordinate)vRoundRect.elementAt(i)).getY1(),((Coordinate)vRoundRect.elementAt(i)).getX2()-((Coordinate)vRoundRect.elementAt(i)).getX1(),((Coordinate)vRoundRect.elementAt(i)).getY2()-((Coordinate)vRoundRect.elementAt(i)).getY1(),25,25);
            }
            for (int i=0;i<vSolidOval.size();i++){
               g.setColor(((Coordinate)vSolidOval.elementAt(i)).colour());
               
g.fillOval(((Coordinate)vSolidOval.elementAt(i)).getX1(),((Coordinate)vSolidOval.elementAt(i)).getY1(),((Coordinate)vSolidOval.elementAt(i)).getX2()-((Coordinate)vSolidOval.elementAt(i)).getX1(),((Coordinate)vSolidOval.elementAt(i)).getY2()-((Coordinate)vSolidOval.elementAt(i)).getY1());
            }
            for (int i=0;i<vSolidRoundRect.size();i++){
               
g.setColor(((Coordinate)vSolidRoundRect.elementAt(i)).colour());
                    
g.fillRoundRect(((Coordinate)vSolidRoundRect.elementAt(i)).getX1(),((Coordinate)vSolidRoundRect.elementAt(i)).getY1(),((Coordinate)vSolidRoundRect.elementAt(i)).getX2()-((Coordinate)vSolidRoundRect.elementAt(i)).getX1(),((Coordinate)vSolidRoundRect.elementAt(i)).getY2()-((Coordinate)vSolidRoundRect.elementAt(i)).getY1(),25,25);
            }
            for (int i=0;i<vSquare.size();i++){
               g.setColor(((Coordinate)vSquare.elementAt(i)).colour());
               
g.drawRect(((Coordinate)vSquare.elementAt(i)).getX1(),((Coordinate)vSquare.elementAt(i)).getY1(),((Coordinate)vSquare.elementAt(i)).getX2()-((Coordinate)vSquare.elementAt(i)).getX1(),((Coordinate)vSquare.elementAt(i)).getY2()-((Coordinate)vSquare.elementAt(i)).getY1());
            }
            for (int i=0;i<vSolidSquare.size();i++){
               g.setColor(((Coordinate)vSolidSquare.elementAt(i)).colour());
               
g.fillRect(((Coordinate)vSolidSquare.elementAt(i)).getX1(),((Coordinate)vSolidSquare.elementAt(i)).getY1(),((Coordinate)vSolidSquare.elementAt(i)).getX2()-((Coordinate)vSolidSquare.elementAt(i)).getX1(),((Coordinate)vSolidSquare.elementAt(i)).getY2()-((Coordinate)vSolidSquare.elementAt(i)).getY1());
            }
            for(int i=0;i<vPolygon.size();i++){
                   int xPos[] = new
int[((Coordinate)vPolygon.elementAt(i)).getXPolygon().size()];
                   int yPos[] = new
int[((Coordinate)vPolygon.elementAt(i)).getYPolygon().size()];

                   for(int count=0;count<xPos.length;count++)
                   {
                         xPos[count] =
((Integer)((Coordinate)vPolygon.elementAt(i)).getXPolygon().elementAt(count)).intValue();
                         yPos[count] =
((Integer)((Coordinate)vPolygon.elementAt(i)).getYPolygon().elementAt(count)).intValue();
                   }
                   g.setColor(((Coordinate)vPolygon.elementAt(i)).colour());
                   g.drawPolygon(xPos,yPos,xPos.length);
              }
              for(int i=0;i<vSolidPolygon.size();i++){
                   int xPos[] = new
int[((Coordinate)vSolidPolygon.elementAt(i)).getXPolygon().size()];
                   int yPos[] = new
int[((Coordinate)vSolidPolygon.elementAt(i)).getYPolygon().size()];

                   for(int count=0;count<xPos.length;count++)
                   {
                         xPos[count] =
((Integer)((Coordinate)vSolidPolygon.elementAt(i)).getXPolygon().elementAt(count)).intValue();
                         yPos[count] =
((Integer)((Coordinate)vSolidPolygon.elementAt(i)).getYPolygon().elementAt(count)).intValue();
                   }
                   g.setColor(((Coordinate)vSolidPolygon.elementAt(i)).colour());
                   g.fillPolygon(xPos,yPos,xPos.length);
            }
    }

  public void loadImage(String name){
    Image loadedImage = Toolkit.getDefaultToolkit().getImage(name);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(loadedImage, 0);

    try { tracker.waitForID(0); }
    catch (InterruptedException e) {}

    image = new BufferedImage(loadedImage.getWidth(null),
         loadedImage.getHeight(null), BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = image.createGraphics();
    g2.drawImage(loadedImage, 0, 0, null);

      repaint();
   }

   private void filter(BufferedImageOp op)
   {  BufferedImage filteredImage
         = new BufferedImage(image.getWidth(), image.getHeight(),
            image.getType());
      op.filter(image, filteredImage);
      image = filteredImage;
      repaint();
   }

   public void brighteninc()
   {  float a = 1.5f;
      float b = -20.0f;
      RescaleOp op = new RescaleOp(a, b, null);
      filter(op);
   }

   public void brightendec()
   {  float a = 1.0f;
      float b = -20.0f;
      RescaleOp op = new RescaleOp(a, b, null);
      filter(op);
   }

   public void origImage(){
    String name = fileName.getAbsolutePath();
    Image loadedImage = Toolkit.getDefaultToolkit().getImage(name);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(loadedImage, 0);
    try { tracker.waitForID(0); }
    catch (InterruptedException e) {}
    image = new BufferedImage(loadedImage.getWidth(null),
      loadedImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(loadedImage, 0, 0, null);
    repaint();
   }

   public void grayImage(){
    String name = fileName.getAbsolutePath();
    Image loadedImage = Toolkit.getDefaultToolkit().getImage(name);
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(loadedImage, 0);
    try { tracker.waitForID(0); }
    catch (InterruptedException e) {}
    image = new BufferedImage(loadedImage.getWidth(null),
      loadedImage.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(loadedImage, 0, 0, null);
    repaint();
   }


   private void convolve(float[] elements)
   {  Kernel kernel = new Kernel(3, 3, elements);
      ConvolveOp op = new ConvolveOp(kernel);
      filter(op);
   }

   public void blur()
   {  float weight = 1.0f/9.0f;
      float[] elements = new float[9];
      for (int i = 0; i < 9; i++)
         elements[i] = weight;
      convolve(elements);
   }

   public void sharpen(int n1,int n2,int n3,int n4,int n5,int n6,int
n7,int n8,int n9)
   {   float[] elements =
      {n1,n2,n3,n4,n5,n6,n7,n8,n9};
        float[] element = {  0.0f, -1.0f, 0.0f,
            -1.0f,  5.f, -1.0f,
            0.0f, -1.0f, 0.0f
         };
      convolve(elements);
   }

   public void edgeDetect()
   {  float[] elements =
         {  0.0f, -1.0f, 0.0f,
            -1.0f,  4.f, -1.0f,
            0.0f, -1.0f, 0.0f
         };
      convolve(elements);
   }


   public void negative()
   {  byte negative[] = new byte[256];
      for (int i = 0; i < 252; i++)
         negative[i] = (byte)(255-i);
      ByteLookupTable table = new ByteLookupTable(0, negative);
      LookupOp op = new LookupOp(table, null);
      filter(op);
   }

   public void emboss()
   { Kernel kernel = new Kernel(3 ,3 ,
     new float[]{
                 -1, -1, 0,
                 -1, 1, 1,
                  0, 1, 1 } );
     BufferedImageOp op = new ConvolveOp(kernel);
     filter(op);
   }

   

}

J........H...........CHRIST.........    

I'm buying some time to look into your code..
If I'm too late to answer, you can close the question to get full refund of your points. Then u can ask it again.
I really need help for it,,

you run the program, you will undrestand everything,,

then you just have to combine it,,   I really appreciate if u can help,,.

hi,

i think i could manage to do the selection,, but i think the copy and paste function does not work,,
can u help me for that? any sample program which does copy and paste...

thanks

I'll look for it..
Dear shah,

thanks for yr help so far, finally i could do copy and paste,,,, its done,

if u have run the program, u know that i am doing image editing, we have some affect which is implemented by java 2D API, such as grayscale, emboss, edge detect, negative,sharpen and ...

the code is exactlly is at the end of the program that i posted, for example the code for doing emboss is as follow:

 public void emboss()
   { Kernel kernel = new Kernel(3 ,3 ,
     new float[]{
                 -1, -1, 0,
                 -1, 1, 1,
                  0, 1, 1 } );
     BufferedImageOp op = new ConvolveOp(kernel);
     filter(op);
   }

how i call this methode is from painter.java file,,, but what  my question is now :

you will see there is a matrix of 3*3 to implemented in this code,, i want to pop up a new window when i chose a emboos effect,, it contain a 9 text file to get a number, then pass the number to this methode in order to implement the affect,

hope you undrestood what my question is:

i have done the code to open the new window,,
 
if(source == sharpenItem) {
           
               JFrame jf=new JFrame();
               jf.setBounds(350,65,110,140);
                            Container c=jf.getContentPane();
                            c.setLayout(new FlowLayout());
                             txtfld1=new JTextField(2);
               txtfld2=new JTextField(2);
               txtfld3=new JTextField(2);txtfld4=new JTextField(2);txtfld5=new
JTextField(2);
               txtfld6=new JTextField(2);txtfld7=new JTextField(2);txtfld8=new
JTextField(2);txtfld9=new JTextField(2);

               btnok=new JButton("OK");
               
c.add(txtfld1);c.add(txtfld2);c.add(txtfld3);c.add(txtfld4);c.add(txtfld5);c.add(txtfld6);c.add(txtfld7);c.add(txtfld8);c.add(txtfld9);
               c.add(btnok);
               jf.show();
}


 but i don know how to do the action listener to pass the value to the emboss function when i press OK,,, would you please help me for it,,,

Dear shah,,

thanks for yr help,, i could do all those,, just one more thing,, in yr example , when we do drag the mouse, I wana a rectangle appear to show where we are draging the mouse,,,

thanks,,
Try this example...



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Painter extends JFrame {
   private int xValue = -10, yValue = -10;
   private int lastXValue = -10, lastYValue = -10;

   // set up GUI and register mouse event handler
   public Painter()
   {
      super( "A simple paint program" );

      // create a label and place it in SOUTH of BorderLayout
      getContentPane().add(
         new Label( "Drag the mouse to draw" ),
         BorderLayout.SOUTH );

      addMouseMotionListener(

         // anonymous inner class
         new MouseMotionAdapter() {

            // store drag coordinates and repaint
            public void mouseDragged( MouseEvent event )
            {
               xValue = event.getX();
               yValue = event.getY();
               repaint();
            }  
            public void mouseMoved( MouseEvent event )
            {
               lastXValue = event.getX();
               lastYValue = event.getY();
            }  


         }  // end anonymous inner class

      ); // end call to addMouseMotionListener

      setSize( 400, 300 );  
      setVisible( true );  
   }

   public void paint( Graphics g )
   {
      super.paint(g);
      g.drawRect(lastXValue, lastYValue, Math.abs(xValue-lastXValue), Math.abs(yValue-lastYValue));
   }

   // execute application
   public static void main( String args[] )
   {
      Painter application = new Painter();

      application.addWindowListener(

         // adapter to handle only windowClosing event
         new WindowAdapter() {

            public void windowClosing( WindowEvent event )
            {
               System.exit( 0 );
            }

         }  // end anonymous inner class

      ); // end call to addWindowListener
   }

}  // end class Painter