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,
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,
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,
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);
If you have created the images using Toolkit.getDefaultToolkit(
image = createImage(new FilteredImageSource(image.
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(
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.setDefaultCloseOperati on(JFrame. EXIT_ON_CL OSE);
}
}//end of class
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(
//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.setDefaultCloseOperati
}
}//end of class
<not ....Cantainer con = getContainer();>
Container for sure...
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.jp g");
//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.setDefaultCloseOperati on(JFrame. EXIT_ON_CL OSE);
}
}//end of class
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(
//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.setDefaultCloseOperati
}
}//end of class
ASKER
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,,
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.jp g");
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.setDefaultCloseOperati on(JFrame. EXIT_ON_CL OSE);
}
}//end of class
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(
image1 = createImage(new FilteredImageSource(image1
//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.setDefaultCloseOperati
}
}//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...
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...
ASKER
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( ).getSyste mClipboard ();
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( ).getSyste mClipboard ().getCont ents(null) ;
try
{
if (t != null && t.isDataFlavorSupported(Da taFlavor.i mageFlavor ))
{
BufferedImage pasteImage =
(BufferedImage)t.getTransf erData(Dat aFlavor.im ageFlavor) ;
if (pasteImage!=null)
{
image.getGraphics().drawIm age(pasteI mage, x,y, null);
}
}
}
catch (UnsupportedFlavorExceptio n e)
{
}
catch (IOException e)
{
}
}
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(
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(
try
{
if (t != null && t.isDataFlavorSupported(Da
{
BufferedImage pasteImage =
(BufferedImage)t.getTransf
if (pasteImage!=null)
{
image.getGraphics().drawIm
}
}
}
catch (UnsupportedFlavorExceptio
{
}
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.jp g");
//make sure the name & path of the image
//if image file is not found, it may draw a black screen
image1 = image1.getScaledInstance(4 00, 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.addMouseMotionListene r(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(eventDescr iption
+ " (" + 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.setDefaultCloseOperati on(JFrame. EXIT_ON_CL OSE);
}
}//end of class
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(
//make sure the name & path of the image
//if image file is not found, it may draw a black screen
image1 = image1.getScaledInstance(4
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.addMouseMotionListene
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(eventDescr
+ " (" + e.getX() + "," + e.getY() + ")"
+ " detected on "
+ e.getComponent().getClass(
+ "\n");
}
//Ending Methods for MouseMotionListener
public static void main(String aaa[]) throws Exception
{
ABC abc = new ABC();
abc.setDefaultCloseOperati
}
}//end of class
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.jp g");
image1 = image1.getScaledInstance(4 00, 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(eventDescr iption + "\n");
}
//Ending Methods for MouseListener
public static void main(String aaa[]) throws Exception
{
DEF def = new DEF();
def.setDefaultCloseOperati on(JFrame. EXIT_ON_CL OSE);
}
}//end of class
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(
image1 = image1.getScaledInstance(4
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
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(eventDescr
}
//Ending Methods for MouseListener
public static void main(String aaa[]) throws Exception
{
DEF def = new DEF();
def.setDefaultCloseOperati
}
}//end of class
ASKER
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,,
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.
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.
ASKER
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.NullPointerExcep tion
at Painterr.<init>....
at Painterr.main<.....>
whats this?
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.NullPointerExcep
at Painterr.<init>....
at Painterr.main<.....>
whats this?
Please post code here, let us examine it.....
ASKER
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,tx tfld4,txtf ld5,txtfld 6,txtfld7, txtfld8,tx tfld9;
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,opent extMenuIte m,openimag eMenuItem, copyMenuIt em,copyIma geMenuItem ,pasteImag eMenuItem;
// 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.im ageFlavor} ;
}
// Returns true if flavor is supported
public boolean isDataFlavorSupported(Data Flavor flavor)
{
return DataFlavor.imageFlavor.equ als(flavor );
}
// Returns image
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException , IOException
{
if (!DataFlavor.imageFlavor.e quals(flav or))
{
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.createHorizontalBo x();
fd1=new FileDialog(this,"Open..",F ileDialog. 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.addActionListe ner(menuLi stener);
opentextMenuItem.addAction Listener(m enuListene r);
openimageMenuItem.addActio nListener( menuListen er);
saveMenuItem.addActionList ener(menuL istener);
saveAsMenuItem.addActionLi stener(men uListener) ;
//closeMenuItem.addActionL istener(me nuListener );
exitMenuItem.addActionList ener(menuL istener);
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem) ;
openMenuItem.add(opentextM enuItem);
openMenuItem.add(openimage MenuItem);
//fileMenu.add(closeMenuIt em);
fileMenu.addSeparator();
fileMenu.add(saveMenuItem) ;
fileMenu.add(saveAsMenuIte m);
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.addActionList ener(menuL istener);
copyImageMenuItem.addActio nListener( menuListen er);
pasteImageMenuItem.addActi onListener (menuListe ner);
undoMenuItem.addActionList ener(menuL istener);
redoMenuItem.addActionList ener(menuL istener);
foreGroundMenuItem.addActi onListener (menuListe ner);
backGroundMenuItem.addActi onListener (menuListe ner);
setColorMenuItem.add(foreG roundMenuI tem);
setColorMenuItem.add(backG roundMenuI tem);
editMenu.add(copyMenuItem) ;
editMenu.add(copyImageMenu Item);
editMenu.add(pasteImageMen uItem);
editMenu.add(undoMenuItem) ;
editMenu.add(redoMenuItem) ;
editMenu.addSeparator();
editMenu.add(setColorMenuI tem);
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
aboutMenu = new JMenu("About");
aboutMenu.setMnemonic('A') ;
authorMenuItem = new JMenuItem("Author");
authorMenuItem.addActionLi stener(men uListener) ;
aboutMenu.add(authorMenuIt em);
//efect menu start
effectsMenu = new JMenu("Effects");
effectsMenu.setMnemonic('E ');
JMenu brightenMenu = new JMenu("Brightness");
brightenMenu.setMnemonic(' B');
brightenincItem = new JMenuItem("Increase");
brightenincItem.setMnemoni c('I');
brightenincItem.setActionC ommand("In crease");
brightenincItem.addActionL istener(me nuListener );
brightenincItem.setAcceler ator(KeySt roke.getKe yStroke(Ke yEvent.VK_ 3, InputEvent.CTRL_MASK));
brightenMenu.add(brighteni ncItem);
brightendecItem = new JMenuItem("Decrease");
brightendecItem.setMnemoni c('D');
brightendecItem.setActionC ommand("De crease");
brightendecItem.addActionL istener(me nuListener );
brightendecItem.setAcceler ator(KeySt roke.getKe yStroke(Ke yEvent.VK_ 3, InputEvent.ALT_MASK));
brightenMenu.add(brightend ecItem);
effectsMenu.add(brightenMe nu);
originalItem = new JMenuItem("Original");
originalItem.setMnemonic(' O');
originalItem.setActionComm and("Origi nal");
originalItem.addActionList ener(menuL istener);
originalItem.setAccelerato r(KeyStrok e.getKeySt roke(KeyEv ent.VK_0,
InputEvent.CTRL_MASK));
effectsMenu.add(originalIt em);
rendItem=new JMenuItem("Rendering Text");
rendItem.setActionCommand( "Rendering ");
rendItem.addActionListener (menuListe ner);
rendItem.setAccelerator(Ke yStroke.ge tKeyStroke (KeyEvent. VK_1,
InputEvent.CTRL_MASK));
effectsMenu.add(rendItem);
blurItem = new JMenuItem("Blur");
blurItem.setMnemonic('L');
blurItem.setActionCommand( "Blur");
blurItem.addActionListener (menuListe ner);
blurItem.setAccelerator(Ke yStroke.ge tKeyStroke (KeyEvent. VK_1,
InputEvent.CTRL_MASK));
effectsMenu.add(blurItem);
sharpenItem = new JMenuItem("Sharpen");
sharpenItem.setMnemonic('S ');
sharpenItem.setActionComma nd("Sharpe n");
sharpenItem.addActionListe ner(menuLi stener);
sharpenItem.setAccelerator (KeyStroke .getKeyStr oke(KeyEve nt.VK_2,
InputEvent.CTRL_MASK));
effectsMenu.add(sharpenIte m);
edgeDetectItem = new JMenuItem("Edge detect");
edgeDetectItem.setMnemonic ('E');
edgeDetectItem.setActionCo mmand("Edg e Detect");
edgeDetectItem.addActionLi stener(men uListener) ;
edgeDetectItem.setAccelera tor(KeyStr oke.getKey Stroke(Key Event.VK_4 , InputEvent.CTRL_MASK));
effectsMenu.add(edgeDetect Item);
negativeItem = new JMenuItem("Negative");
negativeItem.setMnemonic(' N');
negativeItem.setActionComm and("Negat ive");
negativeItem.addActionList ener(menuL istener);
negativeItem.setAccelerato r(KeyStrok e.getKeySt roke(KeyEv ent.VK_5,
InputEvent.CTRL_MASK));
effectsMenu.add(negativeIt em);
grayItem = new JMenuItem("GrayScale");
grayItem.setMnemonic('G');
grayItem.setActionCommand( "GrayScale ");
grayItem.addActionListener (menuListe ner);
grayItem.setAccelerator(Ke yStroke.ge tKeyStroke (KeyEvent. VK_6,
InputEvent.CTRL_MASK));
effectsMenu.add(grayItem);
embossItem = new JMenuItem("Emboss");
embossItem.setMnemonic('M' );
embossItem.setActionComman d("Emboss" );
embossItem.addActionListen er(menuLis tener);
embossItem.setAccelerator( KeyStroke. getKeyStro ke(KeyEven t.VK_7,
InputEvent.CTRL_MASK));
effectsMenu.add(embossItem );
/************************* * EffectsMenu Ends **/
JMenu toolMenu = new JMenu("Tool Box");
toolBarItem = new JCheckBoxMenuItem("Tool Box");
toolBarItem.addItemListene r(
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(canvasPane l);
colorButtonPanel = new ColorButtonPanel(canvasPan el);
mainContainer = getContentPane();
box.add(new JScrollPane(ta));
//mainContainer.add(toolBu ttonPanel, BorderLayo ut.NORTH);
//showToolBar();
mainContainer.add(canvasPa nel,Border Layout.CEN TER);
mainContainer.add(colorBut tonPanel,B orderLayou t.SOUTH);
mainContainer.add(box,Bord erLayout.S OUTH);
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(toolB ar);
validate();
}
public void showToolBar(){
mainContainer.add(toolBar, BorderLayout.PAGE_START);
validate();
}
public class MenuButtonListener implements ActionListener
{
public void actionPerformed(ActionEven t event)
{
Object source = event.getSource();
if(source == newMenuItem /*|| event.getSource() == closeMenuItem*/)
{
canvasPanel.clearCanvas();
canvasPanel.setDrawMode(0) ;
canvasPanel.setForeGroundC olor(Color .WHITE);
canvasPanel.setBackGroundC olor(Color .BLACK);
canvasPanel.repaint();
hide();
Painter application = new Painter();
application.show();
}
if(source == exitMenuItem)
{
System.exit(0);
}
if(source == foreGroundMenuItem)
{
colorButtonPanel.setForeGr oundColor( );
canvasPanel.repaint();
}
if(source == backGroundMenuItem)
{
colorButtonPanel.setBackGr oundColor( );
canvasPanel.repaint();
}
if(source == authorMenuItem)
{
JOptionPane.showMessageDia log(Painte r.this,"Ov erview : 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",JOptionP ane.INFORM ATION_MESS AGE);
canvasPanel.repaint();
}
if(source == saveMenuItem) canvasPanel.SaveCanvasToFi le();
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.SaveAsCanvasTo File();
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,14 0);
//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(txtfl d2);c.add( txtfld3);c .add(txtfl d4);c.add( txtfld5);c .add(txtfl d6);c.add( txtfld7);c .add(txtfl d8);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<byte length;byt ecount++)
{
//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( ).getSyste mClipboard ();
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( ).getSyste mClipboard ().getCont ents(null) ;
try
{
if (t != null && t.isDataFlavorSupported(Da taFlavor.i mageFlavor ))
{
BufferedImage pasteImage =
(BufferedImage)t.getTransf erData(Dat aFlavor.im ageFlavor) ;
if (pasteImage!=null)
{
image.getGraphics().drawIm age(pasteI mage, x,y, null);
}
}
}
catch (UnsupportedFlavorExceptio n e)
{
}
catch (IOException e)
{
}
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(Render ingHints.K EY_ANTIALI ASING,Rend eringHints .VALUE_ANT IALIAS_ON) ;
Dimension d=getSize();
AffineTransform
ct=AffineTransform.getTran slateInsta nce(d.widt h/2,d.heig ht*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(AffineTransfo rm.getRota teInstance (
Math.PI * (ratio - 1.0f)));
float alpha=((i==limit) ? 1.0f : ratio/3);
g2.setComposite(AlphaCompo site.getIn stance(
AlphaComposite.SRC_OVER, alpha));
g2.drawString(cuttext,0,0) ;
g2.setTransform(oldTransfo rm);
}
}
private class ActionEventHandler implements ActionListener{
public void actionPerformed(ActionEven t event)
{
if(event.getSource() == btnok)
{
n1=Integer.parseInt(txtfld 1.getText( ));
n2=Integer.parseInt(txtfld 2.getText( ));n3=Inte ger.parseI nt(txtfld3 .getText() );n4=Integ er.parseIn t(txtfld4. getText()) ;n5=Intege r.parseInt (txtfld5.g etText()); n6=Integer .parseInt( txtfld6.ge tText());n 7=Integer. parseInt(t xtfld7.get Text());n8 =Integer.p arseInt(tx tfld8.getT ext());n9= Integer.pa rseInt(txt fld9.getTe xt());
canvasPanel.sharpen(n1,n2, n3,n4,n5,n 6,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.setDefaultClos eOperation (JFrame.EX IT_ON_CLOS E);
}
}
************************** ********** ********** ********** *
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(CanvasPane l inCanvasPanel)
{
canvasPanel = inCanvasPanel;
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
lineBtn = new JButton("",new ImageIcon("straight_line.g if"));
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("Li ne");
squareBtn.addActionListene r(new ToolButtonListener());
squareBtn.setToolTipText(" Retangle") ;
ovalBtn.addActionListener( new ToolButtonListener());
ovalBtn.setToolTipText("Ov al");
polygonBtn.addActionListen er(new ToolButtonListener());
polygonBtn.setToolTipText( "Polygon") ;
roundRectBtn.addActionList ener(new ToolButtonListener());
roundRectBtn.setToolTipTex t("Rectang le");
freeHandBtn.addActionListe ner(new ToolButtonListener());
freeHandBtn.setToolTipText ("Free Hand");
undoBtn.addActionListener( new ToolButtonListener());
undoBtn.setToolTipText("Un do");
redoBtn.addActionListener( new ToolButtonListener());
redoBtn.setToolTipText("Re do");
clearBtn.addActionListener (new ToolButtonListener());
clearBtn.setToolTipText("C lear Canvas");
brightenSlider =
new JSlider(JSlider.HORIZONTAL ,brightnes sMinValue,
brightnessMaxValue, brightnessCurrentValue);
brightenSlider.addChangeLi stener(
new ChangeListener(){
public void stateChanged(ChangeEvent e){
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusti ng()) {
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(B oolean.TRU E);
else
canvasPanel.setSolidMode(B oolean.FAL SE);
}
}
);
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
//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(brightenSliderLab el);
this.add(brightenSlider);
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
private class ToolButtonListener implements ActionListener
{
public void actionPerformed(ActionEven t event)
{
if(canvasPanel.isExistPoly gonBuffer( )!= false)
{
canvasPanel.flushPolygonBu ffer();
}
if(event.getSource() == lineBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. LINE);
}
if(event.getSource() == squareBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. SQUARE);
}
if(event.getSource() == ovalBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. OVAL);
}
if(event.getSource() == polygonBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. POLYGON);
}
if(event.getSource() == roundRectBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. ROUND_RECT );
}
if(event.getSource() == freeHandBtn)
{
canvasPanel.setDrawMode(ca nvasPanel. 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,backGro undColorBt n;
private JLabel
foreGroundColorLbl,backGro undColorLb l,foreColo rLbl,backC olorLbl;
private Color foreColor, backColor;
private CanvasPanel canvasPanel;
public ColorButtonPanel(CanvasPan el inCanvasPanel)
{
canvasPanel = inCanvasPanel;
foreGroundColorLbl = new JLabel(" ");
foreGroundColorLbl.setOpaq ue(true);
foreGroundColorLbl.setBack ground(can vasPanel.g etForeGrou ndColor()) ;
foreGroundColorLbl.setBord er(BorderF actory.cre ateLineBor der(Color. BLACK));
backGroundColorLbl = new JLabel(" ");
backGroundColorLbl.setOpaq ue(true);
backGroundColorLbl.setBack ground(can vasPanel.g etBackGrou ndColor()) ;
backGroundColorLbl.setBord er(BorderF actory.cre ateLineBor der(Color. WHITE));
foreGroundColorBtn = new JButton("ForeGroundColor-> ");
foreGroundColorBtn.addActi onListener (
new ActionListener()
{
public void actionPerformed(ActionEven t event)
{
setForeGroundColor();
}
}
);
backGroundColorBtn = new JButton("BackGroundColor-> ");
backGroundColorBtn.addActi onListener (
new ActionListener()
{
public void actionPerformed(ActionEven t event)
{
setBackGroundColor();
}
}
);
this.setLayout(new GridLayout(1,4));
this.add(foreGroundColorBt n);
this.add(foreGroundColorLb l);
this.add(backGroundColorBt n);
this.add(backGroundColorLb l);
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void setForeGroundColor()
{
foreColor = JColorChooser.showDialog(n ull,"ForeG round Color",foreColor);
if(foreColor!=null)
{
foreGroundColorLbl.setBack ground(for eColor);
canvasPanel.setForeGroundC olor(foreC olor);
}
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void setBackGroundColor()
{
backColor = JColorChooser.showDialog(n ull,"BackG round Color",backColor);
if(backColor!=null)
{
backGroundColorLbl.setBack ground(bac kColor);
canvasPanel.setBackGroundC olor(backC olor);
}
}
}
************************** ********** ********** ********** ********
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,MouseMotionL istener, Serializable
{
protected final static int
LINE=1,SQUARE=2,OVAL=3,POL YGON=4,ROU ND_RECT=5, FREE_HAND= 6,
SOLID_SQUARE=22, SOLID_OVAL=33, SOLID_POLYGON=44,
SOLID_ROUND_RECT=55;
protected static Vector
vLine,vSquare,vOval,vPolyg on,vRoundR ect,vFreeH and,
vSolidSquare,vSolidOval,vS olidPolygo n,vSolidRo undRect,vF ile,
xPolygon, yPolygon;
private Stack undoStack, redoStack;
private Color foreGroundColor, backGroundColor;
private int x1,y1,x2,y2,linex1,linex2, liney1,lin ey2, 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(thi s);
//fd1=new FileDialog(this,"Open..",F ileDialog. LOAD);
solidMode = false;
polygonBuffer = false;
foreGroundColor = Color.WHITE;
backGroundColor = Color.BLACK;
setBackground(backGroundCo lor);
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.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(LINE ,new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
if (drawMode == SQUARE)
{
if(solidMode)
{
if(x1 > event.getX() || y1 > event.getY())
{
vSolidSquare.add(new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vSolidSquare.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vSquare.add(new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(SQUARE, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vSquare.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(SQUARE, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
}
if (drawMode == this.OVAL)
{
if(solidMode)
{
if(x1 > event.getX() || y1 > event.getY())
{
vSolidOval.add(new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vSolidOval.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vOval.add(new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(OVAL, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vOval.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(OVAL, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
}
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(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(SOLID_ROUND_RECT, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vSolidRoundRect.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(SOLID_ROUND_RECT, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vRoundRect.add(new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or));
undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(event.getX(),ev ent.getY() ,x1,y1,for eGroundCol or)));
}
else
{
vRoundRect.add(new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or));
undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(x1,y1,event.get X(),event. getY(),for eGroundCol or)));
}
}
}
x1=linex1=x2=linex2=0;
y1=liney1=y2=liney2=0;
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void mouseEntered(MouseEvent event)
{
setCursor(new Cursor(Cursor.CROSSHAIR_CU RSOR));
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void mouseExited(MouseEvent event)
{
setCursor(new Cursor(Cursor.DEFAULT_CURS OR));
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
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,l inex2,line y2,foreGro undColor)) ;
undoStack.push(new StepInfo(FREE_HAND, new
Coordinate(linex1,liney1,l inex2,line y2,foreGro undColor)) );
}
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-x 2,y1-y2,25 ,25);
else
g.fillRoundRect(x1,y1,x2-x 1,y2-y1,25 ,25);
}
else
{
if(x1 > x2 || y1 > y2)
g.drawRoundRect(x2,y2,x1-x 2,y1-y2,25 ,25);
else
g.drawRoundRect(x1,y1,x2-x 1,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.elemen tAt(count) )).intValu e();
yPos[count] =
((Integer)(yPolygon.elemen tAt(count) )).intValu e();
}
g.drawPolyline(xPos,yPos,x Pos.length );
polygonBuffer = true;
}
if (drawMode == FREE_HAND)
{
g.drawLine(linex1,liney1,l inex2,line y2);
}
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
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(backGro undColor);
}
public Color getBackGroundColor()
{
return backGroundColor;
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void undo()
{
StepInfo tempInfo;
if(undoStack.isEmpty())
JOptionPane.showMessageDia log(null, "Can't Undo","Painter", JOptionPane.INFORMATION_ME SSAGE);
else
{
tempInfo = (StepInfo)undoStack.pop();
switch(tempInfo.getStepTyp e())
{
case 1: vLine.remove(vLine.size()- 1);
break;
case 2: vSquare.remove(vSquare.siz e()-1);
break;
case 3: vOval.remove(vOval.size()- 1);
break;
case 4: vPolygon.remove(vPolygon.s ize()-1);
break;
case 5: vRoundRect.remove(vRoundRe ct.size()- 1);
break;
case 6: vFreeHand.remove(vFreeHand .size()-1) ;
break;
case 22:vSolidSquare.remove(vSo lidSquare. size()-1);
break;
case 33:vSolidOval.remove(vSoli dOval.size ()-1);
break;
case 44:vSolidPolygon.remove(vS olidPolygo n.size()-1 );
break;
case 55:vSolidRoundRect.remove( vSolidRoun dRect.size ()-1);
break;
}
redoStack.push(tempInfo);
}
repaint();
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void redo()
{
StepInfo tempInfo;
if(redoStack.isEmpty())
JOptionPane.showMessageDia log(null," Can't Redo","Painter",JOptionPan e.INFORMAT ION_MESSAG E);
else
{
tempInfo = (StepInfo)redoStack.pop();
switch(tempInfo.getStepTyp e())
{
case 1: vLine.add(tempInfo.getStep Coordinate ());
break;
case 2: vSquare.add(tempInfo.getSt epCoordina te());
break;
case 3: vOval.add(tempInfo.getStep Coordinate ());
break;
case 4: vPolygon.add(tempInfo.getS tepCoordin ate());
break;
case 5: vRoundRect.add(tempInfo.ge tStepCoord inate());
break;
case 6: vFreeHand.add(tempInfo.get StepCoordi nate());
break;
case 22:vSolidSquare.add(tempIn fo.getStep Coordinate ());
break;
case 33:vSolidOval.add(tempInfo .getStepCo ordinate() );
break;
case 44:vSolidPolygon.add(tempI nfo.getSte pCoordinat e());
break;
case 55:vSolidRoundRect.add(tem pInfo.getS tepCoordin ate());
break;
}
undoStack.push(tempInfo);
}
repaint();
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void clearCanvas()
{
vFreeHand.removeAllElement s();
vLine.removeAllElements();
vOval.removeAllElements();
vPolygon.removeAllElements ();
vRoundRect.removeAllElemen ts();
vSolidOval.removeAllElemen ts();
vSolidPolygon.removeAllEle ments();
vSolidRoundRect.removeAllE lements();
vSolidSquare.removeAllElem ents();
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.showMessageDia log(null," The file has been successfully saved.");
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void SaveAsCanvasToFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelecti onMode(JFi leChooser. FILES_ONLY );
int result = fileChooser.showSaveDialog (null);
if(result == JFileChooser.CANCEL_OPTION ) return;
fileName = fileChooser.getSelectedFil e();
if(fileName == null || fileName.getName().equals( ""))
JOptionPane.showMessageDia log(null," Invalid File Name","Painter",JOptionPan e.ERROR_ME SSAGE);
else
{
BufferedImage rendImage = myCreateImage();
try {
File file = new File(fileName.toString());
ImageIO.write(rendImage, "jpg", file);
this.image = rendImage;
}catch (IOException e) {}
}
repaint();
JOptionPane.showMessageDia log(null," The file has been successfully saved.");
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
public void OpenCanvasFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelecti onMode(JFi leChooser. FILES_ONLY );
fileChooser.setFileFilter( new javax.swing.filechooser.Fi leFilter()
{ 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_OPTIO N){
fileName = fileChooser.getSelectedFil e();
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.createGraphi cs();
if(this.image!=null){
g.drawImage(image, 0, 0, null);
}
redrawVectorBuffer(g);
g.dispose();
return bufferedImage;
}
/*------------------------ ---------- ---------- ---------- ---------- ---------- --*/
private void redrawVectorBuffer(Graphic s g)
{
for (int i=0;i<vFreeHand.size();i++ ){
g.setColor(((Coordinate)vF reeHand.el ementAt(i) ).colour() );
g.drawLine(((Coordinate)vF reeHand.el ementAt(i) ).getX1(), ((Coordina te)vFreeHa nd.element At(i)).get Y1(),((Coo rdinate)vF reeHand.el ementAt(i) ).getX2(), ((Coordina te)vFreeHa nd.element At(i)).get Y2());
}
for (int i=0;i<vLine.size();i++){
g.setColor(((Coordinate)vL ine.elemen tAt(i)).co lour());
g.drawLine(((Coordinate)vL ine.elemen tAt(i)).ge tX1(),((Co ordinate)v Line.eleme ntAt(i)).g etY1(),((C oordinate) vLine.elem entAt(i)). getX2(),(( Coordinate )vLine.ele mentAt(i)) .getY2());
}
for (int i=0;i<vOval.size();i++){
g.setColor(((Coordinate)vO val.elemen tAt(i)).co lour());
g.drawOval(((Coordinate)vO val.elemen tAt(i)).ge tX1(),((Co ordinate)v Oval.eleme ntAt(i)).g etY1(),((C oordinate) vOval.elem entAt(i)). getX2()-(( Coordinate )vOval.ele mentAt(i)) .getX1(),( (Coordinat e)vOval.el ementAt(i) ).getY2()- ((Coordina te)vOval.e lementAt(i )).getY1() );
}
for (int i=0;i<vRoundRect.size();i+ +){
g.setColor(((Coordinate)vR oundRect.e lementAt(i )).colour( ));
g.drawRoundRect(((Coordina te)vRoundR ect.elemen tAt(i)).ge tX1(),((Co ordinate)v RoundRect. elementAt( i)).getY1( ),((Coordi nate)vRoun dRect.elem entAt(i)). getX2()-(( Coordinate )vRoundRec t.elementA t(i)).getX 1(),((Coor dinate)vRo undRect.el ementAt(i) ).getY2()- ((Coordina te)vRoundR ect.elemen tAt(i)).ge tY1(),25,2 5);
}
for (int i=0;i<vSolidOval.size();i+ +){
g.setColor(((Coordinate)vS olidOval.e lementAt(i )).colour( ));
g.fillOval(((Coordinate)vS olidOval.e lementAt(i )).getX1() ,((Coordin ate)vSolid Oval.eleme ntAt(i)).g etY1(),((C oordinate) vSolidOval .elementAt (i)).getX2 ()-((Coord inate)vSol idOval.ele mentAt(i)) .getX1(),( (Coordinat e)vSolidOv al.element At(i)).get Y2()-((Coo rdinate)vS olidOval.e lementAt(i )).getY1() );
}
for (int i=0;i<vSolidRoundRect.size ();i++){
g.setColor(((Coordinate)vS olidRoundR ect.elemen tAt(i)).co lour());
g.fillRoundRect(((Coordina te)vSolidR oundRect.e lementAt(i )).getX1() ,((Coordin ate)vSolid RoundRect. elementAt( i)).getY1( ),((Coordi nate)vSoli dRoundRect .elementAt (i)).getX2 ()-((Coord inate)vSol idRoundRec t.elementA t(i)).getX 1(),((Coor dinate)vSo lidRoundRe ct.element At(i)).get Y2()-((Coo rdinate)vS olidRoundR ect.elemen tAt(i)).ge tY1(),25,2 5);
}
for (int i=0;i<vSquare.size();i++){
g.setColor(((Coordinate)vS quare.elem entAt(i)). colour());
g.drawRect(((Coordinate)vS quare.elem entAt(i)). getX1(),(( Coordinate )vSquare.e lementAt(i )).getY1() ,((Coordin ate)vSquar e.elementA t(i)).getX 2()-((Coor dinate)vSq uare.eleme ntAt(i)).g etX1(),((C oordinate) vSquare.el ementAt(i) ).getY2()- ((Coordina te)vSquare .elementAt (i)).getY1 ());
}
for (int i=0;i<vSolidSquare.size(); i++){
g.setColor(((Coordinate)vS olidSquare .elementAt (i)).colou r());
g.fillRect(((Coordinate)vS olidSquare .elementAt (i)).getX1 (),((Coord inate)vSol idSquare.e lementAt(i )).getY1() ,((Coordin ate)vSolid Square.ele mentAt(i)) .getX2()-( (Coordinat e)vSolidSq uare.eleme ntAt(i)).g etX1(),((C oordinate) vSolidSqua re.element At(i)).get Y2()-((Coo rdinate)vS olidSquare .elementAt (i)).getY1 ());
}
for(int i=0;i<vPolygon.size();i++) {
int xPos[] = new
int[((Coordinate)vPolygon. elementAt( i)).getXPo lygon().si ze()];
int yPos[] = new
int[((Coordinate)vPolygon. elementAt( i)).getYPo lygon().si ze()];
for(int count=0;count<xPos.length; count++)
{
xPos[count] =
((Integer)((Coordinate)vPo lygon.elem entAt(i)). getXPolygo n().elemen tAt(count) ).intValue ();
yPos[count] =
((Integer)((Coordinate)vPo lygon.elem entAt(i)). getYPolygo n().elemen tAt(count) ).intValue ();
}
g.setColor(((Coordinate)vP olygon.ele mentAt(i)) .colour()) ;
g.drawPolygon(xPos,yPos,xP os.length) ;
}
for(int i=0;i<vSolidPolygon.size() ;i++){
int xPos[] = new
int[((Coordinate)vSolidPol ygon.eleme ntAt(i)).g etXPolygon ().size()] ;
int yPos[] = new
int[((Coordinate)vSolidPol ygon.eleme ntAt(i)).g etYPolygon ().size()] ;
for(int count=0;count<xPos.length; count++)
{
xPos[count] =
((Integer)((Coordinate)vSo lidPolygon .elementAt (i)).getXP olygon().e lementAt(c ount)).int Value();
yPos[count] =
((Integer)((Coordinate)vSo lidPolygon .elementAt (i)).getYP olygon().e lementAt(c ount)).int Value();
}
g.setColor(((Coordinate)vS olidPolygo n.elementA t(i)).colo ur());
g.fillPolygon(xPos,yPos,xP os.length) ;
}
}
public void loadImage(String name){
Image loadedImage = Toolkit.getDefaultToolkit( ).getImage (name);
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(loadedIma ge, 0);
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage. getWidth(n ull),
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.getWid th(), 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(loadedIma ge, 0);
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage. getWidth(n ull),
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(loadedIma ge, 0);
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage. getWidth(n ull),
loadedImage.getHeight(null ), BufferedImage.TYPE_BYTE_GR AY);
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,n 9};
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);
}
}
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,tx
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,opent
// 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.
public ImageSelection(Image image)
{
this.image = image;
//image = createImage(new FilteredImageSource(image.
}
// Returns supported flavors
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[]{DataFlavor.im
}
// Returns true if flavor is supported
public boolean isDataFlavorSupported(Data
{
return DataFlavor.imageFlavor.equ
}
// Returns image
public Object getTransferData(DataFlavor
{
if (!DataFlavor.imageFlavor.e
{
throw new UnsupportedFlavorException
}
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=
public FileDialog fd1; //Created a Windows like File Dialog Box
public Painter()
{
super("PAINTER");
fileName = null;
Box box=Box.createHorizontalBo
fd1=new FileDialog(this,"Open..",F
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.addActionListe
opentextMenuItem.addAction
openimageMenuItem.addActio
saveMenuItem.addActionList
saveAsMenuItem.addActionLi
//closeMenuItem.addActionL
exitMenuItem.addActionList
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem)
openMenuItem.add(opentextM
openMenuItem.add(openimage
//fileMenu.add(closeMenuIt
fileMenu.addSeparator();
fileMenu.add(saveMenuItem)
fileMenu.add(saveAsMenuIte
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.addActionList
copyImageMenuItem.addActio
pasteImageMenuItem.addActi
undoMenuItem.addActionList
redoMenuItem.addActionList
foreGroundMenuItem.addActi
backGroundMenuItem.addActi
setColorMenuItem.add(foreG
setColorMenuItem.add(backG
editMenu.add(copyMenuItem)
editMenu.add(copyImageMenu
editMenu.add(pasteImageMen
editMenu.add(undoMenuItem)
editMenu.add(redoMenuItem)
editMenu.addSeparator();
editMenu.add(setColorMenuI
/*------------------------
aboutMenu = new JMenu("About");
aboutMenu.setMnemonic('A')
authorMenuItem = new JMenuItem("Author");
authorMenuItem.addActionLi
aboutMenu.add(authorMenuIt
//efect menu start
effectsMenu = new JMenu("Effects");
effectsMenu.setMnemonic('E
JMenu brightenMenu = new JMenu("Brightness");
brightenMenu.setMnemonic('
brightenincItem = new JMenuItem("Increase");
brightenincItem.setMnemoni
brightenincItem.setActionC
brightenincItem.addActionL
brightenincItem.setAcceler
brightenMenu.add(brighteni
brightendecItem = new JMenuItem("Decrease");
brightendecItem.setMnemoni
brightendecItem.setActionC
brightendecItem.addActionL
brightendecItem.setAcceler
brightenMenu.add(brightend
effectsMenu.add(brightenMe
originalItem = new JMenuItem("Original");
originalItem.setMnemonic('
originalItem.setActionComm
originalItem.addActionList
originalItem.setAccelerato
InputEvent.CTRL_MASK));
effectsMenu.add(originalIt
rendItem=new JMenuItem("Rendering Text");
rendItem.setActionCommand(
rendItem.addActionListener
rendItem.setAccelerator(Ke
InputEvent.CTRL_MASK));
effectsMenu.add(rendItem);
blurItem = new JMenuItem("Blur");
blurItem.setMnemonic('L');
blurItem.setActionCommand(
blurItem.addActionListener
blurItem.setAccelerator(Ke
InputEvent.CTRL_MASK));
effectsMenu.add(blurItem);
sharpenItem = new JMenuItem("Sharpen");
sharpenItem.setMnemonic('S
sharpenItem.setActionComma
sharpenItem.addActionListe
sharpenItem.setAccelerator
InputEvent.CTRL_MASK));
effectsMenu.add(sharpenIte
edgeDetectItem = new JMenuItem("Edge detect");
edgeDetectItem.setMnemonic
edgeDetectItem.setActionCo
edgeDetectItem.addActionLi
edgeDetectItem.setAccelera
effectsMenu.add(edgeDetect
negativeItem = new JMenuItem("Negative");
negativeItem.setMnemonic('
negativeItem.setActionComm
negativeItem.addActionList
negativeItem.setAccelerato
InputEvent.CTRL_MASK));
effectsMenu.add(negativeIt
grayItem = new JMenuItem("GrayScale");
grayItem.setMnemonic('G');
grayItem.setActionCommand(
grayItem.addActionListener
grayItem.setAccelerator(Ke
InputEvent.CTRL_MASK));
effectsMenu.add(grayItem);
embossItem = new JMenuItem("Emboss");
embossItem.setMnemonic('M'
embossItem.setActionComman
embossItem.addActionListen
embossItem.setAccelerator(
InputEvent.CTRL_MASK));
effectsMenu.add(embossItem
/*************************
JMenu toolMenu = new JMenu("Tool Box");
toolBarItem = new JCheckBoxMenuItem("Tool Box");
toolBarItem.addItemListene
new ItemListener(){
public void itemStateChanged(ItemEvent
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(canvasPane
colorButtonPanel = new ColorButtonPanel(canvasPan
mainContainer = getContentPane();
box.add(new JScrollPane(ta));
//mainContainer.add(toolBu
//showToolBar();
mainContainer.add(canvasPa
mainContainer.add(colorBut
mainContainer.add(box,Bord
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(toolB
validate();
}
public void showToolBar(){
mainContainer.add(toolBar,
validate();
}
public class MenuButtonListener implements ActionListener
{
public void actionPerformed(ActionEven
{
Object source = event.getSource();
if(source == newMenuItem /*|| event.getSource() == closeMenuItem*/)
{
canvasPanel.clearCanvas();
canvasPanel.setDrawMode(0)
canvasPanel.setForeGroundC
canvasPanel.setBackGroundC
canvasPanel.repaint();
hide();
Painter application = new Painter();
application.show();
}
if(source == exitMenuItem)
{
System.exit(0);
}
if(source == foreGroundMenuItem)
{
colorButtonPanel.setForeGr
canvasPanel.repaint();
}
if(source == backGroundMenuItem)
{
colorButtonPanel.setBackGr
canvasPanel.repaint();
}
if(source == authorMenuItem)
{
JOptionPane.showMessageDia
canvasPanel.repaint();
}
if(source == saveMenuItem) canvasPanel.SaveCanvasToFi
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.SaveAsCanvasTo
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,14
//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(txtfl
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<byte
{
//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.
//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(
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(
try
{
if (t != null && t.isDataFlavorSupported(Da
{
BufferedImage pasteImage =
(BufferedImage)t.getTransf
if (pasteImage!=null)
{
image.getGraphics().drawIm
}
}
}
catch (UnsupportedFlavorExceptio
{
}
catch (IOException e)
{
}
}
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(Render
Dimension d=getSize();
AffineTransform
ct=AffineTransform.getTran
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(AffineTransfo
Math.PI * (ratio - 1.0f)));
float alpha=((i==limit) ? 1.0f : ratio/3);
g2.setComposite(AlphaCompo
AlphaComposite.SRC_OVER, alpha));
g2.drawString(cuttext,0,0)
g2.setTransform(oldTransfo
}
}
private class ActionEventHandler implements ActionListener{
public void actionPerformed(ActionEven
{
if(event.getSource() == btnok)
{
n1=Integer.parseInt(txtfld
n2=Integer.parseInt(txtfld
canvasPanel.sharpen(n1,n2,
}
}}
/*------------------------
public static void main(String args[])
{
Painter application = new Painter();
//Frame frame=new applicationFrame("text Rendering"){
//frame.setVisible(true);
application.show();
application.setDefaultClos
}
}
**************************
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(CanvasPane
{
canvasPanel = inCanvasPanel;
/*------------------------
lineBtn = new JButton("",new ImageIcon("straight_line.g
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.
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(
lineBtn.setToolTipText("Li
squareBtn.addActionListene
squareBtn.setToolTipText("
ovalBtn.addActionListener(
ovalBtn.setToolTipText("Ov
polygonBtn.addActionListen
polygonBtn.setToolTipText(
roundRectBtn.addActionList
roundRectBtn.setToolTipTex
freeHandBtn.addActionListe
freeHandBtn.setToolTipText
undoBtn.addActionListener(
undoBtn.setToolTipText("Un
redoBtn.addActionListener(
redoBtn.setToolTipText("Re
clearBtn.addActionListener
clearBtn.setToolTipText("C
brightenSlider =
new JSlider(JSlider.HORIZONTAL
brightnessMaxValue, brightnessCurrentValue);
brightenSlider.addChangeLi
new ChangeListener(){
public void stateChanged(ChangeEvent e){
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusti
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
{
if(fullChk.isSelected())
canvasPanel.setSolidMode(B
else
canvasPanel.setSolidMode(B
}
}
);
/*------------------------
//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(brightenSliderLab
this.add(brightenSlider);
}
/*------------------------
private class ToolButtonListener implements ActionListener
{
public void actionPerformed(ActionEven
{
if(canvasPanel.isExistPoly
{
canvasPanel.flushPolygonBu
}
if(event.getSource() == lineBtn)
{
canvasPanel.setDrawMode(ca
}
if(event.getSource() == squareBtn)
{
canvasPanel.setDrawMode(ca
}
if(event.getSource() == ovalBtn)
{
canvasPanel.setDrawMode(ca
}
if(event.getSource() == polygonBtn)
{
canvasPanel.setDrawMode(ca
}
if(event.getSource() == roundRectBtn)
{
canvasPanel.setDrawMode(ca
}
if(event.getSource() == freeHandBtn)
{
canvasPanel.setDrawMode(ca
}
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,backGro
private JLabel
foreGroundColorLbl,backGro
private Color foreColor, backColor;
private CanvasPanel canvasPanel;
public ColorButtonPanel(CanvasPan
{
canvasPanel = inCanvasPanel;
foreGroundColorLbl = new JLabel(" ");
foreGroundColorLbl.setOpaq
foreGroundColorLbl.setBack
foreGroundColorLbl.setBord
backGroundColorLbl = new JLabel(" ");
backGroundColorLbl.setOpaq
backGroundColorLbl.setBack
backGroundColorLbl.setBord
foreGroundColorBtn = new JButton("ForeGroundColor->
foreGroundColorBtn.addActi
new ActionListener()
{
public void actionPerformed(ActionEven
{
setForeGroundColor();
}
}
);
backGroundColorBtn = new JButton("BackGroundColor->
backGroundColorBtn.addActi
new ActionListener()
{
public void actionPerformed(ActionEven
{
setBackGroundColor();
}
}
);
this.setLayout(new GridLayout(1,4));
this.add(foreGroundColorBt
this.add(foreGroundColorLb
this.add(backGroundColorBt
this.add(backGroundColorLb
}
/*------------------------
public void setForeGroundColor()
{
foreColor = JColorChooser.showDialog(n
if(foreColor!=null)
{
foreGroundColorLbl.setBack
canvasPanel.setForeGroundC
}
}
/*------------------------
public void setBackGroundColor()
{
backColor = JColorChooser.showDialog(n
if(backColor!=null)
{
backGroundColorLbl.setBack
canvasPanel.setBackGroundC
}
}
}
**************************
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,MouseMotionL
{
protected final static int
LINE=1,SQUARE=2,OVAL=3,POL
SOLID_SQUARE=22, SOLID_OVAL=33, SOLID_POLYGON=44,
SOLID_ROUND_RECT=55;
protected static Vector
vLine,vSquare,vOval,vPolyg
vSolidSquare,vSolidOval,vS
xPolygon, yPolygon;
private Stack undoStack, redoStack;
private Color foreGroundColor, backGroundColor;
private int x1,y1,x2,y2,linex1,linex2,
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(thi
//fd1=new FileDialog(this,"Open..",F
solidMode = false;
polygonBuffer = false;
foreGroundColor = Color.WHITE;
backGroundColor = Color.BLACK;
setBackground(backGroundCo
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.get
undoStack.push(new StepInfo(LINE ,new
Coordinate(x1,y1,event.get
}
if (drawMode == SQUARE)
{
if(solidMode)
{
if(x1 > event.getX() || y1 > event.getY())
{
vSolidSquare.add(new
Coordinate(event.getX(),ev
undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(event.getX(),ev
}
else
{
vSolidSquare.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(SOLID_SQUARE, new
Coordinate(x1,y1,event.get
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vSquare.add(new
Coordinate(event.getX(),ev
undoStack.push(new StepInfo(SQUARE, new
Coordinate(event.getX(),ev
}
else
{
vSquare.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(SQUARE, new
Coordinate(x1,y1,event.get
}
}
}
if (drawMode == this.OVAL)
{
if(solidMode)
{
if(x1 > event.getX() || y1 > event.getY())
{
vSolidOval.add(new
Coordinate(event.getX(),ev
undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(event.getX(),ev
}
else
{
vSolidOval.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(SOLID_OVAL, new
Coordinate(x1,y1,event.get
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vOval.add(new
Coordinate(event.getX(),ev
undoStack.push(new StepInfo(OVAL, new
Coordinate(event.getX(),ev
}
else
{
vOval.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(OVAL, new
Coordinate(x1,y1,event.get
}
}
}
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(),ev
undoStack.push(new StepInfo(SOLID_ROUND_RECT,
Coordinate(event.getX(),ev
}
else
{
vSolidRoundRect.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(SOLID_ROUND_RECT,
Coordinate(x1,y1,event.get
}
}
else
{
if(x1 > event.getX() || y1 > event.getY())
{
vRoundRect.add(new
Coordinate(event.getX(),ev
undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(event.getX(),ev
}
else
{
vRoundRect.add(new
Coordinate(x1,y1,event.get
undoStack.push(new StepInfo(ROUND_RECT, new
Coordinate(x1,y1,event.get
}
}
}
x1=linex1=x2=linex2=0;
y1=liney1=y2=liney2=0;
}
/*------------------------
public void mouseEntered(MouseEvent event)
{
setCursor(new Cursor(Cursor.CROSSHAIR_CU
}
/*------------------------
public void mouseExited(MouseEvent event)
{
setCursor(new Cursor(Cursor.DEFAULT_CURS
}
/*------------------------
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,l
undoStack.push(new StepInfo(FREE_HAND, new
Coordinate(linex1,liney1,l
}
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-
else
g.fillOval(x1,y1,x2-x1,y2-
}
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-x
else
g.fillRoundRect(x1,y1,x2-x
}
else
{
if(x1 > x2 || y1 > y2)
g.drawRoundRect(x2,y2,x1-x
else
g.drawRoundRect(x1,y1,x2-x
}
}
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;
{
xPos[count] =
((Integer)(xPolygon.elemen
yPos[count] =
((Integer)(yPolygon.elemen
}
g.drawPolyline(xPos,yPos,x
polygonBuffer = true;
}
if (drawMode == FREE_HAND)
{
g.drawLine(linex1,liney1,l
}
}
/*------------------------
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(backGro
}
public Color getBackGroundColor()
{
return backGroundColor;
}
/*------------------------
public void undo()
{
StepInfo tempInfo;
if(undoStack.isEmpty())
JOptionPane.showMessageDia
else
{
tempInfo = (StepInfo)undoStack.pop();
switch(tempInfo.getStepTyp
{
case 1: vLine.remove(vLine.size()-
break;
case 2: vSquare.remove(vSquare.siz
break;
case 3: vOval.remove(vOval.size()-
break;
case 4: vPolygon.remove(vPolygon.s
break;
case 5: vRoundRect.remove(vRoundRe
break;
case 6: vFreeHand.remove(vFreeHand
break;
case 22:vSolidSquare.remove(vSo
break;
case 33:vSolidOval.remove(vSoli
break;
case 44:vSolidPolygon.remove(vS
break;
case 55:vSolidRoundRect.remove(
break;
}
redoStack.push(tempInfo);
}
repaint();
}
/*------------------------
public void redo()
{
StepInfo tempInfo;
if(redoStack.isEmpty())
JOptionPane.showMessageDia
else
{
tempInfo = (StepInfo)redoStack.pop();
switch(tempInfo.getStepTyp
{
case 1: vLine.add(tempInfo.getStep
break;
case 2: vSquare.add(tempInfo.getSt
break;
case 3: vOval.add(tempInfo.getStep
break;
case 4: vPolygon.add(tempInfo.getS
break;
case 5: vRoundRect.add(tempInfo.ge
break;
case 6: vFreeHand.add(tempInfo.get
break;
case 22:vSolidSquare.add(tempIn
break;
case 33:vSolidOval.add(tempInfo
break;
case 44:vSolidPolygon.add(tempI
break;
case 55:vSolidRoundRect.add(tem
break;
}
undoStack.push(tempInfo);
}
repaint();
}
/*------------------------
public void clearCanvas()
{
vFreeHand.removeAllElement
vLine.removeAllElements();
vOval.removeAllElements();
vPolygon.removeAllElements
vRoundRect.removeAllElemen
vSolidOval.removeAllElemen
vSolidPolygon.removeAllEle
vSolidRoundRect.removeAllE
vSolidSquare.removeAllElem
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.showMessageDia
}
/*------------------------
public void SaveAsCanvasToFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelecti
int result = fileChooser.showSaveDialog
if(result == JFileChooser.CANCEL_OPTION
fileName = fileChooser.getSelectedFil
if(fileName == null || fileName.getName().equals(
JOptionPane.showMessageDia
else
{
BufferedImage rendImage = myCreateImage();
try {
File file = new File(fileName.toString());
ImageIO.write(rendImage, "jpg", file);
this.image = rendImage;
}catch (IOException e) {}
}
repaint();
JOptionPane.showMessageDia
}
/*------------------------
public void OpenCanvasFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelecti
fileChooser.setFileFilter(
{ 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
if(result == JFileChooser.CANCEL_OPTION
if(result == JFileChooser.APPROVE_OPTIO
fileName = fileChooser.getSelectedFil
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
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.createGraphi
if(this.image!=null){
g.drawImage(image, 0, 0, null);
}
redrawVectorBuffer(g);
g.dispose();
return bufferedImage;
}
/*------------------------
private void redrawVectorBuffer(Graphic
{
for (int i=0;i<vFreeHand.size();i++
g.setColor(((Coordinate)vF
g.drawLine(((Coordinate)vF
}
for (int i=0;i<vLine.size();i++){
g.setColor(((Coordinate)vL
g.drawLine(((Coordinate)vL
}
for (int i=0;i<vOval.size();i++){
g.setColor(((Coordinate)vO
g.drawOval(((Coordinate)vO
}
for (int i=0;i<vRoundRect.size();i+
g.setColor(((Coordinate)vR
g.drawRoundRect(((Coordina
}
for (int i=0;i<vSolidOval.size();i+
g.setColor(((Coordinate)vS
g.fillOval(((Coordinate)vS
}
for (int i=0;i<vSolidRoundRect.size
g.setColor(((Coordinate)vS
g.fillRoundRect(((Coordina
}
for (int i=0;i<vSquare.size();i++){
g.setColor(((Coordinate)vS
g.drawRect(((Coordinate)vS
}
for (int i=0;i<vSolidSquare.size();
g.setColor(((Coordinate)vS
g.fillRect(((Coordinate)vS
}
for(int i=0;i<vPolygon.size();i++)
int xPos[] = new
int[((Coordinate)vPolygon.
int yPos[] = new
int[((Coordinate)vPolygon.
for(int count=0;count<xPos.length;
{
xPos[count] =
((Integer)((Coordinate)vPo
yPos[count] =
((Integer)((Coordinate)vPo
}
g.setColor(((Coordinate)vP
g.drawPolygon(xPos,yPos,xP
}
for(int i=0;i<vSolidPolygon.size()
int xPos[] = new
int[((Coordinate)vSolidPol
int yPos[] = new
int[((Coordinate)vSolidPol
for(int count=0;count<xPos.length;
{
xPos[count] =
((Integer)((Coordinate)vSo
yPos[count] =
((Integer)((Coordinate)vSo
}
g.setColor(((Coordinate)vS
g.fillPolygon(xPos,yPos,xP
}
}
public void loadImage(String name){
Image loadedImage = Toolkit.getDefaultToolkit(
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(loadedIma
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage.
loadedImage.getHeight(null
Graphics2D g2 = image.createGraphics();
g2.drawImage(loadedImage, 0, 0, null);
repaint();
}
private void filter(BufferedImageOp op)
{ BufferedImage filteredImage
= new BufferedImage(image.getWid
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(
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(loadedIma
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage.
loadedImage.getHeight(null
Graphics2D g2 = image.createGraphics();
g2.drawImage(loadedImage, 0, 0, null);
repaint();
}
public void grayImage(){
String name = fileName.getAbsolutePath()
Image loadedImage = Toolkit.getDefaultToolkit(
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(loadedIma
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
image = new BufferedImage(loadedImage.
loadedImage.getHeight(null
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,n
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...........CHRIS T.........
I'm buying some time to look into your code..
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.
ASKER
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,,.
you run the program, you will undrestand everything,,
then you just have to combine it,, I really appreciate if u can help,,.
ASKER
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 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..
ASKER
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,14 0);
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(txtfl d2);c.add( txtfld3);c .add(txtfl d4);c.add( txtfld5);c .add(txtfl d6);c.add( txtfld7);c .add(txtfl d8);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,,,
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,14
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(txtfl
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,,,
ASKER
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,,
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.addWindowListe ner(
// 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
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
}
// execute application
public static void main( String args[] )
{
Painter application = new Painter();
application.addWindowListe
// 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
http://www.javaalmanac.com/egs/java.awt.image/CropImage.html