ApprenticeHacker
ApprenticeHacker

Reputation: 22031

Creating a Curve Tool using Java2D and Swing for my Java Vector Graphics Editor

I am creating a Vector Graphics editor and have successfully created the paint-brush and some basic 2d shapes like Rectange, Ellipse , Line etc. Now what's bothering me is the Curved Line or Curve tool. I created the others by getting the original point from mousePressed and then updating the second point on each mouseDragged. Here's part of the code:

public void mousePressed(MouseEvent e){
    gfx.setColor(Tool.currentColor);
    pos1 = e.getPoint(); //Get the First Point
}
public void mouseReleased(MouseEvent e){
    if(!e.isAltDown() && !e.isMetaDown())

    if(currentShape != null) shapeSet.add(currentShape);
    currentShape = null;
}
public void mouseDragged(MouseEvent e){
    if(e.isAltDown() || e.isMetaDown()) return;
    //the mouse was dragged, so begin painting
    pos2 = e.getPoint();

    int ctool = Tool.currentTool;

    if(ctool == Tool.LINE){
        currentShape = new Line(pos1,pos2,Tool.currentColor,null);
    }else if(ctool == Tool.ELLIPSE){
        currentShape = new Ellipse(pos1,pos2,Tool.currentColor,null);
    }else if(ctool == Tool.RECTANGLE){
        currentShape = new Rectangle(pos1,pos2,Tool.currentColor,null);
    }

    this.repaint();
}

The Line,Ellipse etc. classes are quite simple, they just take the points and draw them later in the repaint. All the Shapes temporarily stored in currentShape are then later appended to shapeSet , which is an ArrayList of the abstract class Shape.

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);

    gfx.setBackground(Color.WHITE);

    gfx.clearRect(0, 0, img.getWidth(), img.getHeight());
    for(int i=0; i< shapeSet.size(); i++){
        shapeSet.get(i).draw(gfx);
    }
    if(currentShape != null){
        currentShape.draw(gfx);
    }

    g.drawImage(img, 0, 0, null);
} 

img is a BufferedImage and gfx is img's Graphics.

img = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
gfx = img.createGraphics(); //Graphics2D

Now how exactly would I go about creating a Curve Tool?

P.S If you want the code of the Shape (Line,Ellipse etc.) classes, just comment and I'll post it.

Upvotes: 2

Views: 1210

Answers (2)

Catalina Island
Catalina Island

Reputation: 7136

Here's a Bézier Curve Editor in Java that might give you some ideas, but I'm not sure how you'd integrate it into your program.

Upvotes: 2

StanislavL
StanislavL

Reputation: 57421

Use http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/geom/PathIterator.html

You have to define SEG_QUADTO or SEG_CUBICTO. Just add a new segment with propr double coordinates.

Upvotes: 2

Related Questions