01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package horstmann.ch06_car;
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.MouseMotionAdapter;

import javax.swing.JComponent;

/**
   A component that shows a scene composed of items.
 */
@SuppressWarnings("serial")
public class CarComponent extends JComponent
{
  public CarComponent()
  {
    car = new CarShape(20, 20, 50);
    addMouseListener(new
        MouseAdapter()
    {
      public void mousePressed(MouseEvent event)
      {
        mousePoint = event.getPoint();
        if (!car.contains(mousePoint))
          mousePoint = null;
      }
    });

    addMouseMotionListener(new
        MouseMotionAdapter()
    {
      public void mouseDragged(MouseEvent event)
      {
        if (mousePoint == null) return;
        Point lastMousePoint = mousePoint;
        mousePoint = event.getPoint();

        double dx = mousePoint.getX() - lastMousePoint.getX();
        double dy = mousePoint.getY() - lastMousePoint.getY();
        car.translate((int) dx, (int) dy);
        repaint();
      }
    });
  }

  public void paintComponent(Graphics g)
  {
    Graphics2D g2 = (Graphics2D) g;
    car.draw(g2);
  }

  private CarShape car;
  private Point mousePoint;
}