01: import java.awt.*;
02: import java.awt.event.*;
03: import java.awt.geom.*;
04: import javax.swing.*;
05: import java.util.*;
06: 
07: /**
08:    A component that shows a scene composed of shapes.
09: */
10: public class SceneComponent extends JComponent
11: {
12:    public SceneComponent()
13:    {
14:       shapes = new ArrayList<SceneShape>();
15: 
16:       addMouseListener(new
17:          MouseAdapter()
18:          {
19:             public void mousePressed(MouseEvent event)
20:             {
21:                mousePoint = event.getPoint();
22:                for (SceneShape s : shapes)
23:                {
24:                   if (s.contains(mousePoint))
25:                      s.setSelected(!s.isSelected());
26:                }
27:                repaint();
28:             }
29:          });
30: 
31:       addMouseMotionListener(new
32:          MouseMotionAdapter()
33:          {
34:             public void mouseDragged(MouseEvent event)
35:             {
36:                Point lastMousePoint = mousePoint;
37:                mousePoint = event.getPoint();
38:                for (SceneShape s : shapes)
39:                {
40:                   if (s.isSelected())
41:                   {
42:                      double dx = mousePoint.getX() - lastMousePoint.getX();
43:                      double dy = mousePoint.getY() - lastMousePoint.getY();
44:                      s.translate((int) dx, (int) dy);
45:                   }
46:                }
47:                repaint();
48:             }
49:          });
50:    }
51: 
52:    /**
53:       Adds a shape to the scene.
54:       @param s the shape to add
55:    */
56:    public void add(SceneShape s)
57:    {
58:       shapes.add(s);
59:       repaint();
60:    }
61: 
62:    /**
63:       Removes all selected shapes from the scene.
64:    */
65:    public void removeSelected()
66:    {
67:       for (int i = shapes.size() - 1; i >= 0; i--)
68:       {
69:          SceneShape s = shapes.get(i);
70:          if (s.isSelected()) shapes.remove(i);
71:       }
72:       repaint();
73:    }
74: 
75:    public void paintComponent(Graphics g)
76:    {
77:       super.paintComponent(g);
78:       Graphics2D g2 = (Graphics2D) g;
79:       for (SceneShape s : shapes)
80:       {
81:          s.draw(g2);
82:          if (s.isSelected())
83:             s.drawSelection(g2);
84:       }
85:    }
86: 
87:    private ArrayList<SceneShape> shapes;
88:    private Point mousePoint;
89: }