-
Notifications
You must be signed in to change notification settings - Fork 1
/
Counter.java
83 lines (73 loc) · 1.65 KB
/
Counter.java
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/**
* Counter that displays an (optional) text and a number.
*
* @author Michael Kolling
* @version 1.0
*/
public class Counter extends Actor
{
public static final float FONT_SIZE = 18.0f;
private int value;
private String text;
private int stringLength;
private Font font;
/**
* Create a counter without text.
*/
public Counter()
{
this("");
}
/**
* Create a counter with prefix text, and 0 value.
*/
public Counter(String prefix)
{
this(prefix, 0);
}
/**
* Create a counter with prefix text and value.
*/
public Counter(String prefix, int value)
{
this.value = value;
text = prefix;
stringLength = (text.length() + 4) * 10;
GreenfootImage image = new GreenfootImage(stringLength, 22);
setImage(image);
font = image.getFont();
font = font.deriveFont(FONT_SIZE);
updateImage();
}
/**
* Increment the counter by one.
*/
public void increment()
{
value++;
updateImage();
}
/**
* Return the current counter value.
*/
public int getValue()
{
return value;
}
/**
* Make the image
*/
private void updateImage()
{
GreenfootImage image = getImage();
image.clear();
image.setFont(font);
image.setColor(Color.BLACK);
image.drawString(text + value, 6, (int)FONT_SIZE);
}
}