001package horstmann.ch06_car;
002import java.awt.Graphics;
003import java.awt.Graphics2D;
004import java.awt.Point;
005import java.awt.event.MouseAdapter;
006import java.awt.event.MouseEvent;
007import java.awt.event.MouseMotionAdapter;
008
009import javax.swing.JComponent;
010
011/**
012   A component that shows a scene composed of items.
013 */
014@SuppressWarnings("serial")
015public class CarComponent extends JComponent
016{
017        public CarComponent()
018        {
019                car = new CarShape(20, 20, 50);
020                addMouseListener(new
021                                MouseAdapter()
022                {
023                        public void mousePressed(MouseEvent event)
024                        {
025                                mousePoint = event.getPoint();
026                                if (!car.contains(mousePoint))
027                                        mousePoint = null;
028                        }
029                });
030
031                addMouseMotionListener(new
032                                MouseMotionAdapter()
033                {
034                        public void mouseDragged(MouseEvent event)
035                        {
036                                if (mousePoint == null) return;
037                                Point lastMousePoint = mousePoint;
038                                mousePoint = event.getPoint();
039
040                                double dx = mousePoint.getX() - lastMousePoint.getX();
041                                double dy = mousePoint.getY() - lastMousePoint.getY();
042                                car.translate((int) dx, (int) dy);
043                                repaint();
044                        }
045                });
046        }
047
048        public void paintComponent(Graphics g)
049        {
050                Graphics2D g2 = (Graphics2D) g;
051                car.draw(g2);
052        }
053
054        private CarShape car;
055        private Point mousePoint;
056}