-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCritterPanel.java
More file actions
48 lines (42 loc) · 1.65 KB
/
CritterPanel.java
File metadata and controls
48 lines (42 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
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
// Class CritterPanel displays a grid of critters
import javax.swing.*;
import java.awt.Point;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CritterPanel extends JPanel {
private CritterModel myModel;
private Font myFont;
private static boolean created;
public static final int FONT_SIZE = 12;
public CritterPanel(CritterModel model) {
// this prevents someone from trying to create their own copy of
// the GUI components
if (created)
throw new RuntimeException("Only one world allowed");
created = true;
myModel = model;
// construct font and compute char width once in constructor
// for efficiency
myFont = new Font("Monospaced", Font.BOLD, FONT_SIZE + 4);
setBackground(Color.CYAN);
setPreferredSize(new Dimension(FONT_SIZE * model.getWidth() + 20,
FONT_SIZE * model.getHeight() + 20));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(myFont);
Iterator<Critter> i = myModel.iterator();
while (i.hasNext()) {
Critter next = i.next();
Point p = myModel.getPoint(next);
String appearance = myModel.getAppearance(next);
g.setColor(Color.BLACK);
g.drawString("" + appearance, p.x * FONT_SIZE + 11,
p.y * FONT_SIZE + 21);
g.setColor(myModel.getColor(next));
g.drawString("" + appearance, p.x * FONT_SIZE + 10,
p.y * FONT_SIZE + 20);
}
}
}