1 package mousedragicon;
2
3 import java.awt.Dimension;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import java.awt.Point;
7 import java.awt.Shape;
8 import java.awt.event.MouseAdapter;
9 import java.awt.event.MouseEvent;
10 import java.awt.event.MouseMotionAdapter;
11 import java.awt.geom.Ellipse2D;
12 import java.net.URL;
13 import javax.swing.*;
14
15
16 public class MouseDragIcon extends JComponent {
17 private Point mousePt;
18 private ImageIcon pon;
19 private int wp,hp,xce,yce,W,H,dx,dy;
20 private Shape shape = null;
21 private Dimension sz;
22 private Point icoPt;
23
24 public MouseDragIcon() {
25 pon = createImageIcon("/image/drag03.png");
26 wp=pon.getIconWidth();
27 hp=pon.getIconHeight();
28
29 icoPt=new Point(0, 0);
30
31 addMouseListener(new MouseAdapter() {
32 @Override
33 public void mousePressed(MouseEvent e) {
34 mousePt = e.getPoint();
35 repaint();
36 }
37 });
38 addMouseMotionListener(new MouseMotionAdapter() {
39 @Override
40 public void mouseDragged(MouseEvent e) {
41 dx = e.getX() - mousePt.x;
42 dy = e.getY() - mousePt.y;
43 icoPt.setLocation(icoPt.x+dx,icoPt.y+dy);
44 mousePt = e.getPoint();
45 repaint();
46 }
47 });
48 }
49
50 @Override
51 public void paintComponent(Graphics g) {
52 super.paintComponent(g);
53 Graphics2D g2d =(Graphics2D)g;
54
55 shape=new Ellipse2D.Float(icoPt.x ,icoPt.y ,wp,hp);
56 pon.paintIcon(this, g2d,icoPt.x ,icoPt.y);
57 }
58
59 @Override
60 public boolean contains(int x, int y) {
61 return shape.contains(x,y);
62 }
63
64 public Point getSz(){
65 Point pnt =new Point(wp,hp);
66 return(pnt);
67 }
68 public void centra(int x,int y){
69 icoPt.x=x;
70 icoPt.y=y;
71 repaint();
72 }
73
74 private ImageIcon createImageIcon(String path) {
75 URL imgURL = getClass().getResource(path);
76 if (imgURL != null) {
77 return new ImageIcon(imgURL);
78 } else {
79 System.err.println("Non รจ possibile trovare il file: " + path);
80 return null;
81 }
82 }
83 } |