I am trying to write a program that allows the user to draw a polygon by drawing a line every time they click within the frame. On the first click, a small square should be drawn. Every click following, a line should be drawn from where the endpoint of the last line is to where the user has clicked. Once the user clicks within the square that was made originally, the polygon will be completed and the square will disappear. My code is as follows; it runs but it does not operate correctly.
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.util.ArrayList;
import javax.swing.JFrame;
public class DrawPolygonComponent {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setTitle("Draw a Polygon");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ArrayList<Point2D.Double> path = new ArrayList();
//addRectangle(frame, 10, 10);
//
class ClickListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent me) {
if (path.isEmpty()) {
System.out.println("First");
addRectangle(frame, me.getX(),me.getY());
path.add(new Point2D.Double(me.getX(),me.getY()));
} else {
System.out.println("Second");
Point2D.Double prev = path.get(path.size()-1);
addLine(frame, (int) prev.x, (int) prev.y,me.getX(),me.getY());
path.add(new Point2D.Double(me.getX(),me.getY()));
frame.repaint();
}
}
public void mousePressed(MouseEvent me) {}
public void mouseReleased(MouseEvent me) {}
public void mouseEntered(MouseEvent me) {}
public void mouseExited(MouseEvent me) {}
}
MouseListener listener = new ClickListener();
frame.addMouseListener (listener);
frame.setVisible (true);
}
public static void addRectangle(JFrame frame, int x , int y) {
RectangleComponent r = new RectangleComponent(x, y, 10, 10);
frame.add(r);
}
public static void addLine(JFrame frame, int x1, int y1, int x2, int y2) {
LineComponent line = new LineComponent(x1, y1, x2, y2);
frame.add(line);
}
}
/////////other
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
public class LineComponent extends JComponent {
private int px;
private int py;
private int x;
private int y;
public LineComponent(int px, int py, int x, int y){
this.px=px;
this.py=py;
this.x=x;
this.y=y;
}
@Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.drawLine(px,py,x,y);
}
}
////////other
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
public class RectangleComponent extends JComponent {
private Rectangle box;
public RectangleComponent(int x,int y, int l, int w){
box = new Rectangle(x,y,l,w);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.fill(box);
g2.draw(box);
}
}