我正在尝试编写一个程序,该程序允许用户每次在框架内单击时通过绘制一条线来绘制多边形。第一次单击时,应绘制一个小方块。每次点击之后,应该从最后一行的端点到用户点击的地方画一条线。一旦用户在最初制作的正方形内单击,多边形将完成,正方形将消失。我的代码如下;它运行但无法正常运行。
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);
}
}