001package horstmann.ch06_scene1; 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; 008import java.util.ArrayList; 009 010import javax.swing.JComponent; 011 012/** 013 A component that shows a scene composed of shapes. 014 */ 015@SuppressWarnings("serial") 016public class SceneComponent extends JComponent 017{ 018 public SceneComponent() 019 { 020 shapes = new ArrayList<SceneShape>(); 021 022 addMouseListener(new 023 MouseAdapter() 024 { 025 public void mousePressed(MouseEvent event) 026 { 027 mousePoint = event.getPoint(); 028 for (SceneShape s : shapes) 029 { 030 if (s.contains(mousePoint)) 031 s.setSelected(!s.isSelected()); 032 } 033 repaint(); 034 } 035 }); 036 037 addMouseMotionListener(new 038 MouseMotionAdapter() 039 { 040 public void mouseDragged(MouseEvent event) 041 { 042 Point lastMousePoint = mousePoint; 043 mousePoint = event.getPoint(); 044 for (SceneShape s : shapes) 045 { 046 if (s.isSelected()) 047 { 048 double dx = mousePoint.getX() - lastMousePoint.getX(); 049 double dy = mousePoint.getY() - lastMousePoint.getY(); 050 s.translate((int) dx, (int) dy); 051 } 052 } 053 repaint(); 054 } 055 }); 056 } 057 058 /** 059 Adds a shape to the scene. 060 @param s the shape to add 061 */ 062 public void add(SceneShape s) 063 { 064 shapes.add(s); 065 repaint(); 066 } 067 068 /** 069 Removes all selected shapes from the scene. 070 */ 071 public void removeSelected() 072 { 073 for (int i = shapes.size() - 1; i >= 0; i--) 074 { 075 SceneShape s = shapes.get(i); 076 if (s.isSelected()) shapes.remove(i); 077 } 078 repaint(); 079 } 080 081 public void paintComponent(Graphics g) 082 { 083 super.paintComponent(g); 084 Graphics2D g2 = (Graphics2D) g; 085 for (SceneShape s : shapes) 086 { 087 s.draw(g2); 088 if (s.isSelected()) 089 s.drawSelection(g2); 090 } 091 } 092 093 private ArrayList<SceneShape> shapes; 094 private Point mousePoint; 095}