62 lines
1.5 KiB
Java
62 lines
1.5 KiB
Java
import java.awt.*;
|
|
import javax.swing.*;
|
|
|
|
public class NumberDisplay extends JComponent {
|
|
public static final int DIGIT_WIDTH = 11;
|
|
public static final int DIGIT_HEIGHT = 21;
|
|
public static final int BACKDROP_WIDTH = 41;
|
|
public static final int BACKDROP_HEIGHT = 25;
|
|
public static final int MINUS_INDEX = 10;
|
|
|
|
private static final int[] DIGIT_X = {28, 15, 2};
|
|
private static final int DIGIT_Y = 2;
|
|
|
|
public final Image BACKDROP;
|
|
public final Image[] DIGITS;
|
|
|
|
private int num;
|
|
private boolean negative;
|
|
|
|
public NumberDisplay(Image backdrop, Image[] digits) {
|
|
BACKDROP = backdrop;
|
|
DIGITS = digits;
|
|
setPreferredSize(new Dimension(BACKDROP_WIDTH, BACKDROP_HEIGHT));
|
|
}
|
|
|
|
public void setNum(int num) {
|
|
setClamped(num);
|
|
repaint();
|
|
}
|
|
|
|
private void setClamped(int num) {
|
|
// Clamp all number assignments between -99 and 999, inclusive
|
|
if (num < 0) {
|
|
this.num = Math.min(-num, 99);
|
|
negative = true;
|
|
} else {
|
|
this.num = Math.min(num, 999);
|
|
negative = false;
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public void paintComponent(Graphics gr) {
|
|
super.paintComponent(gr);
|
|
Graphics2D g = (Graphics2D) gr;
|
|
|
|
g.drawImage(BACKDROP, 0, 0, this);
|
|
// Preserve the original num for divison, in case we repaint twice
|
|
// without updating the number
|
|
int num = this.num;
|
|
for (int i = 0; i < 3; i++) {
|
|
int digitsIndex;
|
|
if (negative && i == 2)
|
|
digitsIndex = MINUS_INDEX;
|
|
else
|
|
digitsIndex = num % 10;
|
|
g.drawImage(DIGITS[digitsIndex], DIGIT_X[i], DIGIT_Y, this);
|
|
num /= 10;
|
|
}
|
|
}
|
|
}
|