    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 panel that shows a scene composed of shapes.
    09: */
    10: public class ScenePanel extends JPanel
    11: {
    12:    public ScenePanel()
    13:    {
    14:       shapes = new ArrayList();
    15:
    16:       addMouseListener(new
    17:          MouseAdapter()
    18:          {
    19:             public void mousePressed(MouseEvent event)
    20:             {
    21:                mousePoint = event.getPoint();
    22:                for (int i = 0; i < shapes.size(); i++)
    23:                {
    24:                   SceneShape s = (SceneShape) shapes.get(i);
    25:                   if (s.contains(mousePoint))
    26:                      s.setSelected(!s.isSelected());
    27:                }
    28:                repaint();
    29:             }
    30:          });
    31:
    32:       addMouseMotionListener(new
    33:          MouseMotionAdapter()
    34:          {
    35:             public void mouseDragged(MouseEvent event)
    36:             {
    37:                Point lastMousePoint = mousePoint;
    38:                mousePoint = event.getPoint();
    39:                for (int i = 0; i < shapes.size(); i++)
    40:                {
    41:                   SceneShape s = (SceneShape) shapes.get(i);
    42:                   if (s.isSelected())
    43:                      s.translate(
    44:                         mousePoint.getX() - lastMousePoint.getX(),
    45:                         mousePoint.getY() - lastMousePoint.getY());
    46:                }
    47:                repaint();
    48:             }
    49:          });
    50:    }
    51:
    52:    /**
    53:       Adds an 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 = (SceneShape) 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 (int i = 0; i < shapes.size(); i++)
    80:       {
    81:          SceneShape s = (SceneShape) shapes.get(i);
    82:          s.draw(g2);
    83:          if (s.isSelected())
    84:             s.drawSelection(g2);
    85:       }
    86:    }
    87:
    88:    private ArrayList shapes;
    89:    private Point mousePoint;
    90: }