public class MouseComponent extends JComponent {
private static final int SIDELENGTH = 10;
private ArrayList<Rectangle2D> squares;
private Rectangle2D current;
public MouseComponent() {
this.squares = new ArrayList<Rectangle2D>();
this.current = null;
this.addMouseListener(new MouseHandle());//监听鼠标点击事件
this.addMouseMotionListener(new MouseMotionHandler());//监听鼠标移动事件
}
//如果鼠标单击屏幕的地方有矩形则不绘制矩形
public Rectangle2D find(Point2D p) {
for (Rectangle2D r : squares) {
if (r.contains(p))
return r;
}
return null;
}
//绘制矩形
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (Rectangle2D r : squares) {
g2.draw(r);
}
}
//添加矩形到屏幕
public void add(Point2D p) {
double x = p.getX();
double y = p.getY();
current = new Rectangle2D.Double(x - SIDELENGTH / 2,
y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
squares.add(current);
repaint();
}
//删除矩形
public void remove(Rectangle2D s) {
if (s == null)
return;
if (s == current)
current = null;
squares.remove(s);
repaint();
}
private class MouseHandle extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
current = find(e.getPoint());
//当前位置如果有矩形,且点击大于2次,则删除矩形
if (current != null && e.getClickCount() >= 2)
remove(current);
}
@Override
public void mousePressed(MouseEvent e) {
current = find(e.getPoint());
//当前位置没有矩形则绘制
if (current == null)
add(e.getPoint());
}
}
private class MouseMotionHandler implements MouseMotionListener {
@Override
public void mouseDragged(MouseEvent e) {
//如果当前位置有矩形,进行拖拽。
if (current != null) {
int x = e.getX();
int y = e.getY();