1 package mousedragtesto;
2
3 import java.awt.Dimension;
4 import java.awt.EventQueue;
5 import java.awt.Font;
6 import java.awt.Graphics;
7 import java.awt.Point;
8 import java.awt.event.MouseAdapter;
9 import java.awt.event.MouseEvent;
10 import java.awt.event.MouseMotionAdapter;
11 import javax.swing.JFrame;
12 import javax.swing.JPanel;
13
14
15 public class MouseDragTesto extends JPanel {
16
17 private static final String TITLE = "Drag me!";
18 private static final int W = 640;
19 private static final int H = 480;
20 private Point textPt = new Point(W / 2, H / 2);
21 private Point mousePt;
22
23 public MouseDragTesto() {
24 this.setFont(new Font("Serif", Font.ITALIC + Font.BOLD, 32));
25 this.addMouseListener(new MouseAdapter() {
26
27 @Override
28 public void mousePressed(MouseEvent e) {
29 mousePt = e.getPoint();
30 repaint();
31 }
32 });
33 this.addMouseMotionListener(new MouseMotionAdapter() {
34
35 @Override
36 public void mouseDragged(MouseEvent e) {
37 int dx = e.getX() - mousePt.x;
38 int dy = e.getY() - mousePt.y;
39 textPt.setLocation(textPt.x + dx, textPt.y + dy);
40 mousePt = e.getPoint();
41 repaint();
42 }
43 });
44 }
45
46 @Override
47 public Dimension getPreferredSize() {
48 return new Dimension(W, H);
49 }
50
51 @Override
52 public void paintComponent(Graphics g) {
53 super.paintComponent(g);
54 int w2 = g.getFontMetrics().stringWidth(TITLE) / 2;
55 g.drawString(TITLE, textPt.x - w2, textPt.y);
56 }
57
58 public static void main(String[] args) {
59 EventQueue.invokeLater(new Runnable() {
60
61 @Override
62 public void run() {
63 JFrame f = new JFrame(TITLE);
64 f.add(new MouseDragTesto());
65 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
66 f.pack();
67 f.setLocationRelativeTo(null);
68 f.setVisible(true);
69 }
70 });
71 }
72 } |