Import Java.awt.Cursor;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Point;
Import Java.awt.event.MouseAdapter;
Import java.awt.event.MouseEvent;
Import Java.awt.event.MouseMotionListener;
Import Java.awt.geom.Point2D;
Import Java.awt.geom.Rectangle2D;
Import java.awt.geom.Rectangle2D.Double;
Import java.util.ArrayList;
Import javax.swing.JComponent;
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 ());//monitor mouse click events
This.addmousemotionlistener (New Mousemotionhandler ());//monitor Mouse movement events
}
Rectangle is not drawn if there is a rectangle where the mouse clicks the screen
Public rectangle2d Find (point2d p) {
for (Rectangle2D r:squares) {
if (R.contains (p))
return R;
}
return null;
}
Draw a rectangle
public void Paintcomponent (Graphics g) {
graphics2d g2 = (graphics2d) g;
for (Rectangle2D r:squares) {
G2.draw (R);
}
}
Add a rectangle to the screen
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 ();
}
Delete Rectangle
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 ());
If the current position has a rectangle and the click is greater than 2 times, the rectangle is deleted
if (current! = null && e.getclickcount () >= 2)
Remove (current);
}
@Override
public void mousepressed (MouseEvent e) {
Current = Find (E.getpoint ());
Draw with no rectangle at the current position
if (current = = null)
Add (E.getpoint ());
}
}
Private class Mousemotionhandler implements Mousemotionlistener {
@Override
public void mousedragged (MouseEvent e) {
If the current position has a rectangle, drag.
if (current! = null) {
int x = E.getx ();
int y = e.gety ();
Current.setframe (X-SIDELENGTH/2, Y-SIDELENGTH/2,
Sidelength, sidelength);
Repaint ();
}
}
@Override
public void mousemoved (MouseEvent e) {
Mouse on blank screen default arrow
if (Find (E.getpoint ()) ==null) SetCursor (Cursor.getdefaultcursor ());
Hit the rectangular area into a cross.
else SetCursor (Cursor.getpredefinedcursor (cursor.crosshair_cursor));
}
}
}