File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .awt .Graphics ;
2+
3+ /**
4+ * Simulation element.
5+ */
6+ public interface Actor {
7+
8+ /**
9+ * Updates the state of the simulation element.
10+ */
11+ void act ();
12+
13+ /**
14+ * Paints the simulation element in the context.
15+ *
16+ * @param g graphics context
17+ */
18+ void draw (Graphics g );
19+
20+ }
Original file line number Diff line number Diff line change 1+ import java .awt .Canvas ;
2+ import java .awt .Color ;
3+ import java .awt .Graphics ;
4+ import java .util .ArrayList ;
5+
6+ /**
7+ * Draws a collection of actors.
8+ */
9+ public class Drawing extends Canvas {
10+
11+ private ArrayList <Actor > actors ;
12+
13+ /**
14+ * Constructs a drawing of given size.
15+ *
16+ * @param width the width in pixels
17+ * @param height the height in pixels
18+ */
19+ public Drawing (int width , int height ) {
20+ setSize (width , height );
21+ setBackground (Color .white );
22+ actors = new ArrayList <Actor >();
23+ }
24+
25+ /**
26+ * Adds a new actor to the drawing.
27+ *
28+ * @param actor the actor to add
29+ */
30+ public void add (Actor actor ) {
31+ actors .add (actor );
32+ }
33+
34+ /**
35+ * Calls the act method of each actor.
36+ */
37+ public void action () {
38+ for (Actor actor : actors ) {
39+ actor .act ();
40+ }
41+ }
42+
43+ /**
44+ * Draws all the actors on the canvas.
45+ *
46+ * @param g graphics context
47+ */
48+ public void paint (Graphics g ) {
49+ for (Actor actor : actors ) {
50+ actor .draw (g );
51+ }
52+ }
53+
54+ }
Original file line number Diff line number Diff line change 1+ import javax .swing .JFrame ;
2+
3+ /**
4+ * Example simulation of moving objects.
5+ */
6+ public class Main {
7+
8+ /**
9+ * Sets up the drawing, creates the actors, and runs the simulation.
10+ *
11+ * @param args command-line arguments
12+ */
13+ public static void main (String [] args ) {
14+
15+ // set up the drawing and add actors
16+ Drawing drawing = new Drawing (800 , 600 );
17+
18+ // set up the window frame
19+ JFrame frame = new JFrame ("Drawing" );
20+ frame .setDefaultCloseOperation (JFrame .EXIT_ON_CLOSE );
21+ frame .add (drawing );
22+ frame .pack ();
23+ frame .setVisible (true );
24+
25+ // main simulation loop
26+ while (true ) {
27+
28+ // update the drawing
29+ drawing .action ();
30+ drawing .repaint ();
31+
32+ // delay the simulation
33+ try {
34+ Thread .sleep (10 );
35+ } catch (InterruptedException e ) {
36+ // do nothing
37+ }
38+ }
39+ }
40+
41+ }
You can’t perform that action at this time.
0 commit comments