Generalpath

could someone please help me with this program. I have to randomly draw triangles. I have pasted my code and it draws one triangle. I know I should use math.random but I dont know how. can someone should me how to write it in.
thanks
i
ps I love this site. it has really been a great help to me, but sometimes I am not able to sign in. Is there a problem. does it only allow so many people to be signed in at one time?

I don't know anything about general path... but I do know when dealing with random positions for drawing, most people use the int type. This little example should get you started a bit:
import java.applet.*;
import java.awt.*;
// <applet code="Example.class" width=300 height=300></applet>
public class Example extends Applet {
     Polygon[] tri; // triangles
     int[] xp, yp; // points
     int x,y,size; // position and size
     public void init() {
          tri = new Polygon[3]; // 3 triangles
          size = 20; // triangle size 20
     public void start() {
          for (int j = 0;j < tri.length;j++) { // for each triangle
               x = (int)Math.round(Math.random()*(getSize().width-size)); // random X position
               y = (int)Math.round(Math.random()*(getSize().height-size)); // random Y position
               xp = new int[] {x+size/2,x,x+size,x+size/2}; // triangle X points
               yp = new int[] {y,y+size,y+size,y}; // triangle Y points
               tri[j] = new Polygon(xp,yp,xp.length); // make triangle
     public void paint(Graphics g) {
          Color[] random = new Color[]
          { // random colors for fun
               Color.red,Color.green,Color.blue,
               Color.orange,Color.yellow,Color.cyan,
               Color.magenta
          for (int j = 0;j < tri.length;j++) {
               g.setColor(random[(int)Math.round(Math.random()*(random.length-1))]); // random color
               g.fillPolygon(tri[j]); // show triangle
}Hope it helps.

Similar Messages

  • GeneralPath of 100k lines drawing performance

    Hi!
    I find that there is a great difference in time between drawing 1 path of 100 000 lines and 100 paths of 1000 lines.
    Drawing 100 paths of 1000 lines is much quicker.
    It seems to me that there is some `unlinearity` in drawing alghorithm, ex. drawing time is proportional to n^1,5 may be.
    But drawing one path with porthions is not good if I use big line width (>3) and not 255 alpha because of overlapping of two path on junctions.
    So, why drawing of path of 100 000 lines is so slow and what can I do to accelerate it?
    P.s.
    1. I also noticed that drawing with stroke width 1 is much quicker than if width is more than 1. But the time difference if I use single path length not more than about 1000 is not so big.
    2. I noticed that if I draw a path of 100 000 lines, turning on antialiasing occelerates rendering. It was strange for me. Antialiasing still slow down rendering if I draw 100 path with 1000 lines - I think it is normal.
    3. I use GeneralPath constructor with predefined initial path points count to prevent redundant memory allocation. I tested float and double lineTo and moveTo methods and don`t see the difference in time.
    Alexander.
    Edited by: Electriq on 18.03.2009 15:00

    I have the latest Wacom drivers for my model - it's the same driver for all Intuos and Cintiq models. Besides, as I said - the performance is perfect in all other software, except Flash. And also as I said - in Flash CS6 the performance is better than CS5.5, but not better than CS3... It is acceptable though, because it's rare that I will draw such fast lines - in my case I can see a clear difference in performance if I draw fast or slow. I have tried to compare results on my older MacBook Pro and I get similar results...

  • GeneralPath not Filling entire path

    Hi,
    i'm trying to draw a graph using a GeneralPath.
    the problem is that if at the bottom it's not wide enough the top ends
    up lower than it's supposed to.
    Here is a crude example (i just put this together as an
    example)please compile and run this program
    -----------------------PathTest.java----------------------------------
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class PathTest extends JFrame implements ActionListener{
    public PathTest(){
    setSize(400,500);
    setTitle("TestGraph's Frame");
    addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Container contentPane = getContentPane();
    p = new PathPanel();
    contentPane.add(p,"Center");
    String [] tOrF = {"Fill","Just Draw"};
    JComboBox comb = new JComboBox(tOrF);
    comb.setSelectedIndex(1);
    comb.addActionListener(this);
    contentPane.add(comb,"North");
    public void actionPerformed(ActionEvent evt){
    JComboBox comb = (JComboBox)evt.getSource();
    String f = (String)comb.getSelectedItem();
    if(f.trim().equals("Fill"))
    p.setFill(true);
    else
    p.setFill(false);
    p.repaint();
    public static void main(String [] args){
    JFrame frame = new PathTest();
    frame.show();
    PathPanel p = null;
    class PathPanel extends JPanel{
    boolean fill = true;
    public void setFill(boolean fill){this.fill = fill;}
    public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D)g;
    double [] pixPoints = {365.0,290.0,370.0,89.0,375.0,290.0};
    paintPath(g2d,pixPoints);
    double [] pixPoints1 = {10.0,290,200.0,89.0,299.0,290.00};
    paintPath(g2d,pixPoints1);
    public void paintPath(Graphics2D g2d,double [] pixPoints){
    GeneralPath path = new GeneralPath();
    g2d.drawLine(0,(int)pixPoints[1],this.getWidth(),(int)pixPoints[1]);
    g2d.drawLine(0,89,this.getWidth(),89);
    for(int i =0 ; i < pixPoints.length -1;i +=2){
    double pix [] = {pixPoints[i],pixPoints[i+1]};
    if(i ==0)
    path.moveTo((float)pix[0],(float)pix[1]);
    else
    path.lineTo((int)pix[0],(int)pix[1]);
    path.closePath();
    if(fill)
    g2d.fill(path);
    else
    g2d.draw(path);
    as you see the problem is only if i use g2d.fill and not when i use
    g2d.draw.....
    any help would be greatly appreciated
    Thanks,
    Sol

    OK,
    sorry everybody. i just found out that means something when u post it, so here is the source code in code tags..
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class PathTest extends JFrame implements ActionListener{
        public PathTest(){
            setSize(400,500);
          setTitle("TestGraph's Frame");
          addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);
          Container contentPane = getContentPane();
           p = new PathPanel();
          contentPane.add(p,"Center");
          String [] tOrF = {"Fill","Just Draw"};
          JComboBox comb = new JComboBox(tOrF);
          comb.setSelectedIndex(1);
          comb.addActionListener(this);
          contentPane.add(comb,"North");
        public void actionPerformed(ActionEvent evt){
            JComboBox comb  = (JComboBox)evt.getSource();
            String f = (String)comb.getSelectedItem();
            if(f.trim().equals("Fill"))
             p.setFill(true);
            else
             p.setFill(false);
            p.repaint();
        public static void main(String [] args){
            JFrame frame = new PathTest();
            frame.show();
        PathPanel p = null;
    class PathPanel extends JPanel{
        boolean fill = true;
        public void setFill(boolean fill){this.fill = fill;}
        public void paintComponent(Graphics g){
            Graphics2D g2d = (Graphics2D)g;
            double [] pixPoints = {365.0,290.0,370.0,89.0,375.0,290.0};
            paintPath(g2d,pixPoints);
            double [] pixPoints1 = {10.0,290,200.0,89.0,299.0,290.00};
            paintPath(g2d,pixPoints1);
        public void paintPath(Graphics2D g2d,double [] pixPoints){
         GeneralPath path = new GeneralPath();
    g2d.drawLine(0,(int)pixPoints[1],this.getWidth(),(int)pixPoints[1]);
         g2d.drawLine(0,89,this.getWidth(),89);
         for(int i =0 ; i < pixPoints.length -1;i +=2){
            double pix [] = {pixPoints,pixPoints[i+1]};
    if(i ==0)
    path.moveTo((float)pix[0],(float)pix[1]);
    else
    path.lineTo((int)pix[0],(int)pix[1]);
    path.closePath();
    if(fill)
    g2d.fill(path);
    else
    g2d.draw(path);

  • ConcurrentModificationException for a GeneralPath

    I've got a problem that I don't know how to solve.
    I've got a GeneralPath, let's call it path. I've got the normal EDT thread running. I've got a JPanel in a JFrame. I also got a communication thread (separate thread).
    Now, I get coordinates to add to the path via the communication thread. This happens sporadically, let's say every 200ms. This thread in turn accesses a class existing in the EDT that adds points to the path.
    The JPanel reads the generalpath in an overridden paintComponent(Graphics g) class and thus read from the path.
    Sometimes I assume the communcation thread tries to add a new part to the path, while the paintComponent tries to draw it. So I get a:
    "Lane.draw(Lane.java:46) exception ConcurrentModificationException"
    I am wondering how I would go about to fix this? I assume it isn't dangerous, since the draw method only reads the path. But still, what should I do or what am I doing wrong?
    Appreciate help!

    Make sure you have one place to access all the data that is shared between the two threads (lets call this place a model). In the model you synchronize on an object before reading or writing (as the other poster noted). The concurrent modification exception is most likely caused by you iterating over an array and make changes on it from the other thread at the same time. So make sure that you synchronize this behavior: if you are iterating, you can not make changes and the other way around.

  • Alternative to GeneralPath?

    I'm looking for an alternative to GeneralPath that supports double precision.
    Specifically I want to create an Area in double precision. Any suggestions?
    Thx,
    Mark

    You won't find it in the standard API. You can write your own class by extending Shape. If the methods in GeneralPath suit you then you can just take the source code and modify it so that the points are stored in double precision.

  • Why no Polygon2d? Is GeneralPath the alternative?

    In Java2D all the old shapes got new Shape versions with
    double precision - except for Polygon.
    Id like to have a Polygon that uses double precision.
    Im thinking that maybe they didnt update Polygon because
    GeneralPath should be its replacement in Java2D (it has
    float precision)?
    For graphics intensive operations - is one "faster" than the other?
    Thanks!

    this probably does not help you much, but, as the writer of a 225+ FPS game engine, I am proud to say that GeneralPaths seem to not hinder rendering at all (as every shape in my engine is stored as one). I do not think there is much of a loss at all when rendering a GeneralPath as opposed to a Polygon because (correct me if I'm wrong) the data is still stored in sequential order, so that in essence the drawing process does the same thing, just through a different object...
    Hope that helps your last question a little
    Alex

  • Working with polygons (GeneralPath)

    Hi
    This is the first time I'm working with a polygon. I realise that I need to declare GeneralPath for the polygon. Could anyone please explain me the following:
    1) the difference between WIND_EVEN_ODD and WIND_NON_ZERO
    2) what is "initialCapacity"? how does it work?
    Thanks a lot

    Googling 'winding rule example' found a visual example:
    http://www.glprogramming.com/red/chapter11.html
    Search for 'Winding Numbers and Winding Rules' in that page.

  • Algorithm on GeneralPath in Graphics2D

    Hie!~Good Day
    I am facing this problem for some time but still cannot solve it. I got all the syntax correct (well at least no error during compiling) but still nothing change.
    The part that perform this consists of 2 class file, Zoom and Data. In Zoom, it loads the image and display it when the program starts. Data is started when a file is loaded into the program. The file contains the coordinates,which is used to draw lines connecting all the coordinates.
    What I did: in Data, I get all the values into 2 public array(xcoor,ycoor). If the xcoor or ycoor is not null, I run the zoom again, like this:
    if(xcoor!=null||ycoor!=null)
    new Zoom();
    in Zoom, actually it already ran once when loaded, so the image is already displayed. I create 2 new arrays (xcoor1,ycoor2) to copy all the value from xcoor and ycoor(just to play safe). then I start draw it. like this:
    GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,x1Points.length);
    polygon.moveTo(xcoor1[0], ycoor1[0]);
    for ( int i = 1; i < xcoor1.length; i++ ) {
    polygon.lineTo(xcoor1, ycoor1[i]);
    context.draw(polygon);
    context is Graphics2D. The compilation into class file is ok. But the GeneralPath is not drawn into the context. What is wrong with this?
    P.S. I don't want the topic to be so long so I didn't paste the whole code.

    Here is what I did:
    if((x == null) || (y == null))
    return;
    int num = x.length;
    path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
    path.moveTo(x[0], y[0]);
    for(int i=1; i<num;i++)
    path.lineTo(x, y[i]);
    g.draw(path);
    This code is within a function and after the function call, I call repaint and then my graphic is displayed. It looks to me that the piece of code you showed is ok. Therefore the problem may come from somewhere else. I suggest you check the coordinate array to make sure it contains valid value( at least not all zeros ). Also double check you paintComponent.

  • Determine whether ellipse perimeter or GeneralPath is in a rectangle

    Hi all,
    I'm making a graphing program in which I can draw a number of shapes and lines (all members of java.awt.geom.*). Also, I have a selection tool. The selection tool draws a Rectangle2D over the canvas, and (in theory) any part of a shape or line which is inside the selection box ought to be selected.
    Making this functionality for lines and rectangles was easy, as I could use the intersectsLine(line) method in Rectangle2D.
    However, doing this for ellipses or GeneralPaths is proving to be much more difficult. As far as I can tell, both intersects(...) methods will return true even if I'm inside the object (I want it only to be true if I'm intersecting with a line itself).
    I was wondering if I could use a PathIterator in some way, since they can both give me a PathIterator? Or is there something else I could use?
    Any help would be very much appreciated!

    If you need to check intersection with the perimeter of the shape then you can do the following,
    Stroke stroke = new BasicStroke(1);
    Shape outline = stroke.createStrokedShape(shape);Then test the 'outline' shape for intersection with your rectangle. Obviously you can adjust the stroke to suit.
    Note that you might want to cache the stroked shapes if you're doing a lot of these tests.

  • Area in units of a GeneralPath

    Is there a method to get the area (in units) of a closed GeneralPath or Area object?

    For simple and convex shapes, work around the edge to create a large number of triangles (with one common point in the interior). Then add these up.
    For simple, but nonconvex shapes ... there's always [Green's theorem|http://en.wikipedia.org/wiki/Planimeter]! Obtain a path iterator and integrate your way around the shape. Good luck with that.
    In "Origin of Species" (written only a few years after the first working planimeter was constructed), Darwin estimates the forrested area of North America by cutting the map out of his atlas and weighing the bits.

  • Tooltiptext on a shape or a generalpath

    Hi all,
    is it possible to set a toolTipText when the mouse pointer stays over a Shape or a GeneralPath?
    thanks

    I tried to use getToolTipText as yuo explayned but maybe I didnt understand very weel...
    When exactly I have to invoce that method?
    Is setTooltipText method necessary?
    Maybe a simple example could be useful...
    thanks

  • How to draw non intersecting area of two GeneralPath

    Hi all ,
    I have two generalpath GP1 and GP2 .
    GP1 and Gp2 are overlapping.
    Im able to draw the overlapping region between the two .
    I want to make the non overlapping area between these two generalpath .
    Is there any API or method to draw that
    Thanks and regards
    Anshuman Srivastava

    Not tested.
        public static Shape createNonOverlappingArea(Shape GP1, Shape GP2) {
          * Create an area that contains the total of GP1 and GP2.
         Area rv = new Area(GP1);
         rv.add(new Area(GP2));
          * Create an area that contains the overlap.
         Area overlap = new Area(GP1);
         overlap.exclusiveOr(new Area(GP2));
          * Subtract the overlap from the total area.
         rv.subtract(overlap);
          * Now rv contains the non overlapping parts.
         return rv;
        }Piet

  • Is a dilatation of a generalpath possible?

    Hi,
    I've got a generalpath that represents the inner contour of a floor plan. Interior like tables are also represented in this generalpath. It's the base for a little simulation program where persons should walk around. Now I'm looking for a way to create a dilatation (e.g. 25 pixel) of the objects and walls that i only need to simulate a single point moving around without paying attention to collide with door frames, tables, etc..
    Is there a way to do this? I hope my problem is understandable.
    Sincerely yours
    Andr�

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Dilatation extends JPanel {
        GeneralPath rooms;
        JLabel xLabel;
        JLabel yLabel;
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(rooms == null) initRooms();
            g2.setPaint(Color.blue);
            g2.draw(rooms);
            Rectangle r = rooms.getBounds();
            double x = r.getCenterX();
            double y = r.getCenterY();
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            at.scale(3.0, 3.0);
            at.translate(5, -30);
            g2.draw(at.createTransformedShape(rooms));
        private void initRooms() {
            rooms = new GeneralPath();
            rooms.moveTo(25,25);
            rooms.lineTo(125,25);
            rooms.lineTo(125,135);
            rooms.lineTo(25,135);
            rooms.lineTo(25,25);
            rooms.moveTo(75,25);
            rooms.lineTo(75,115);
            rooms.moveTo(75,125);
            rooms.lineTo(75,135);
            rooms.moveTo(40,50);
            rooms.lineTo(65,50);
            rooms.lineTo(65,85);
            rooms.lineTo(40,85);
            rooms.lineTo(40,50);
            rooms.moveTo(85,60);
            rooms.lineTo(110,60);
            rooms.lineTo(110,95);
            rooms.lineTo(85,95);
            rooms.lineTo(85,60);
        public static void main(String[] args) {
            Dilatation test = new Dilatation();
            test.addMouseMotionListener(test.pointer);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLabel(), "Last");
            f.setSize(500,500);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        private JPanel getLabel() {
            xLabel = new JLabel();
            yLabel = new JLabel();
            Dimension d = new Dimension(45,25);
            JPanel panel = new JPanel(new GridBagLayout());
            panel.setBorder(BorderFactory.createEtchedBorder());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(1,1,1,1);
            addComponents(new JLabel("x ="), xLabel, panel, d, gbc, true);
            addComponents(new JLabel("y ="), yLabel, panel, d, gbc, false);
            return panel;
        private void addComponents(JComponent c1, JComponent c2, Container c,
                                   Dimension d, GridBagConstraints gbc, boolean b) {
            gbc.anchor = gbc.EAST;
            gbc.weightx = b ? 1.0 : 0;
            c.add(c1, gbc);
            c2.setPreferredSize(d);
            //c2.setBorder(BorderFactory.createEtchedBorder());
            gbc.anchor = gbc.WEST;
            gbc.weightx = b ? 0 : 1.0;
            c.add(c2, gbc);
        private MouseMotionListener pointer = new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                xLabel.setText(String.valueOf(e.getX()));
                yLabel.setText(String.valueOf(e.getY()));
    }

  • Will 2D objects in java.awt.geom.* be Serializable in next version of Java?

    I am pretty frustrated about having to write my own Serializable classes. I'm not sure if this is the right place to ask, but will the next version of Java supports Serializable 2D objects?
    Further, I was trying to write my own class to extend java.awt.geom.GeneralPath to become Serializable, but it's declared "final". What should I do? (I had no problems with Rectangle2D.Double, Line2D.Double, etc.)
    Any help is greatly appreciated.
    Selwyn

    Your code for serializing the state of the General path forgets two things:
    1. the winding rule
    2. the segments types!
    You could use a vector, but I just directly wrote to the file:
    private void writeObject(ObjectOutputStream oos) throws IOException
    {     out.defaultWriteObject();
         //write state of transient GeneralPath _gp;
         out.writeInt(_gp.getWindingRule());
         float[] coord = new float[6];
         PathIterator i = _gp.getPathIterator(null);
         while(!i.isDone())
         {     int seg = i.currentSegment(coords);
              writeInt(seg);
              //switch on seg, writing correct # of floats from coords
              i.next();
         out.writeInt(-1);     //sentinel for end-of-data: SEG_LINETO etc are [0,4]
    private void readObject(ObjectInputStream in)
    throws IOException, ClassNotFoundException
    {     in.defaultReadObject();
         int rule = in.readInt();
         _gp = new GeneralPath(rule);
         //etc...
    }3. I'm just winging this code -- haven't tested it
    --Nax                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How can I get  the part image from a rectangle region?

    hi,
    I'm trying to draw a rectagle region on a picture with mouse and crop it. but the rectangle is not vertical along x-axis.that is to say, there is a angle between x-axis and the base of the rectangle. I don't know , how can I do it. Can someone give me some tip or some java-code. Thank you very much in advance.

    I completely misunderstood your question. As I read it again it seems clear and straight-forward. I'm sorry. Let's see if this is closer.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class CropImage
        BufferedImage original;
        CropPanel cropPanel;
        CropSelector selector;
        public CropImage()
            original = getImage();
            cropPanel = new CropPanel(original);
            selector = new CropSelector(cropPanel);
            cropPanel.addMouseListener(selector);
            cropPanel.addMouseMotionListener(selector);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(getUIPanel(), "North");
            f.getContentPane().add(new JScrollPane(cropPanel));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private BufferedImage getImage()
            String fileName = "images/coyote.jpg";
            BufferedImage image = null;
            try
                URL url = getClass().getResource(fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
            return image;
        private JPanel getUIPanel()
            final JButton
                mask    = new JButton("mask"),
                crop    = new JButton("crop"),
                restore = new JButton("restore");
            ActionListener l = new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JButton button = (JButton)e.getSource();
                    if(button == mask)
                        selector.mask();
                    if(button == crop)
                        selector.crop();
                    if(button == restore)
                        cropPanel.restore(original);
            mask.addActionListener(l);
            crop.addActionListener(l);
            restore.addActionListener(l);
            JPanel panel = new JPanel();
            panel.add(mask);
            panel.add(crop);
            panel.add(restore);
            return panel;
        public static void main(String[] args)
            new CropImage();
    class CropPanel extends JPanel
        BufferedImage image;
        Dimension size;
        GeneralPath clip;
        Point[] corners;
        Area mask;
        boolean showMask;
        Color bgColor;
        public CropPanel(BufferedImage bi)
            image = bi;
            setSize();
            clip = new GeneralPath();
            showMask = false;
            bgColor = getBackground();
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int x = (w - size.width)/2;
            int y = (h - size.height)/2;
            g2.drawImage(image, x, y, this);
            if(showMask)
                g2.setPaint(getBackground());
                g2.fill(mask);
            else
                g2.setPaint(Color.red);
                g2.draw(clip);
        public Dimension getPreferredSize()
            return size;
        public void setClip(Point[] p)
            corners = p;
            clip.reset();
            clip.moveTo(p[0].x, p[0].y);
            clip.lineTo(p[1].x, p[1].y);
            clip.lineTo(p[2].x, p[2].y);
            clip.lineTo(p[3].x, p[3].y);
            clip.closePath();
            repaint();
        public void clearClip()
            clip.reset();
            repaint();
        public void setMask(Area area)
            mask = area;
            showMask = true;
            repaint();
        public void setImage(BufferedImage image)
            this.image = image;
            setSize();
            showMask = false;
            clip.reset();
            repaint();
            revalidate();
        public void restore(BufferedImage image)
            setBackground(bgColor);
            setImage(image);
        private void setSize()
            size = new Dimension(image.getWidth(), image.getHeight());
    class CropSelector extends MouseInputAdapter
        CropPanel cropPanel;
        Point start, end;
        public CropSelector(CropPanel cp)
            cropPanel = cp;
        public void mask()
            Dimension d = cropPanel.getSize();
            Rectangle r = new Rectangle(0, 0, d.width, d.height);
            Area mask = new Area(r);
            Area port = new Area(cropPanel.clip);
            mask.subtract(port);
            cropPanel.setMask(mask);
        public void crop()
            Point[] p = cropPanel.corners;
            int w = p[2].x - p[0].x;
            int h = p[1].y - p[3].y;
            BufferedImage cropped = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = cropped.createGraphics();
            g2.translate(-p[0].x, -p[3].y);
            cropPanel.paint(g2);
            g2.dispose();
            cropPanel.setBackground(Color.pink);
            cropPanel.setImage(cropped);
        public void mousePressed(MouseEvent e)
            if(e.getClickCount() == 2)
                cropPanel.clearClip();
            start = e.getPoint();
        public void mouseDragged(MouseEvent e)
            end = e.getPoint();
            // locate high and low points of rectangle from start
            int dy = end.y - start.y;
            int dx = end.x - start.x;
            double theta = Math.atan2(dy, dx);
            double spoke = start.distance(end)/2;
            double side = Math.sqrt(spoke*spoke + spoke*spoke);
            Point[] corners = new Point[4];           // counter-clockwise
            corners[0] = start;                       // left
            int x = (int)(start.x + side * Math.cos(theta + Math.PI/4));
            int y = (int)(start.y + side * Math.sin(theta + Math.PI/4));
            corners[1] = new Point(x, y);             // bottom
            corners[2] = end;                         // right
            x = (int)(start.x + side * Math.cos(theta - Math.PI/4));
            y = (int)(start.y + side * Math.sin(theta - Math.PI/4));
            corners[3] = new Point(x, y);             // top
            cropPanel.setClip(corners);
    }

Maybe you are looking for

  • Book revenue on this month but the cost of goods sold need to get from last month

    Hi experts, I have a question about cost and revenue. We have a standing service repair order and a contract to customer. Because the revenue is calculated by flight cycle so maybe when we get the flight cycle information for this month should be the

  • Mail Signature Issues (multiple)

    Cumulatively I have spend 20-30 hours trying to make a signature and continue to have issues (never see this experience in APPLE holiday commercials!). I have researched this Board and there are a few cross-overs, but I am including them all here to

  • IDoc to IDoc Scenario - Correct Interface Mapping configuration

    Hello All, i have to configure an Interface Mapping for an IDoc to IDoc scenario. IDoc Type for sending and receiving already imported and located under Imported Objectes\IDocs in respective Software Component Version. Now, how is the correct configu

  • F.62 Configure print program

    Hello Experts, I need to modify the data and the layout of transaction F.62 (Print Journal Voucher).  I have searched information from the web that it is possible to add a custom print program to modify the logic.  I would like to ask what is the tra

  • I am unable to send pictures from Adobe elements 6 via e-mail anymore. Using windows 7 and Windows L

    Old PC died. Bought new PC, installed my Adobe Elements 6 but now I am unable to send photos by email from Adobe Elements 6 via email anymore. Using win7 and Windows Live email. I have tried uninstalling the program and re-installing. Please help.