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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package horstmann.ch06_scene1;
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 java.util.ArrayList;

import javax.swing.JComponent;

/**
   A component that shows a scene composed of shapes.
 */
@SuppressWarnings("serial")
public class SceneComponent extends JComponent
{
  public SceneComponent()
  {
    shapes = new ArrayList<SceneShape>();

    addMouseListener(new
        MouseAdapter()
    {
      public void mousePressed(MouseEvent event)
      {
        mousePoint = event.getPoint();
        for (SceneShape s : shapes)
        {
          if (s.contains(mousePoint))
            s.setSelected(!s.isSelected());
        }
        repaint();
      }
    });

    addMouseMotionListener(new
        MouseMotionAdapter()
    {
      public void mouseDragged(MouseEvent event)
      {
        Point lastMousePoint = mousePoint;
        mousePoint = event.getPoint();
        for (SceneShape s : shapes)
        {
          if (s.isSelected())
          {
            double dx = mousePoint.getX() - lastMousePoint.getX();
            double dy = mousePoint.getY() - lastMousePoint.getY();
            s.translate((int) dx, (int) dy);
          }
        }
        repaint();
      }
    });
  }

  /**
      Adds a shape to the scene.
      @param s the shape to add
   */
  public void add(SceneShape s)
  {
    shapes.add(s);
    repaint();
  }

  /**
      Removes all selected shapes from the scene.
   */
  public void removeSelected()
  {
    for (int i = shapes.size() - 1; i >= 0; i--)
    {
      SceneShape s = shapes.get(i);
      if (s.isSelected()) shapes.remove(i);
    }
    repaint();
  }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    for (SceneShape s : shapes)
    {
      s.draw(g2);
      if (s.isSelected())
        s.drawSelection(g2);
    }
  }

  private ArrayList<SceneShape> shapes;
  private Point mousePoint;
}