import java.awt.*; import javax.swing.*; // The number displays in the game public class NumberDisplay extends JComponent { // The dimensions of each individual digit public static final int DIGIT_WIDTH = 11; public static final int DIGIT_HEIGHT = 21; // The dimensions of the big box public static final int BACKDROP_WIDTH = 41; public static final int BACKDROP_HEIGHT = 25; // The index of the minus sign public static final int MINUS_INDEX = 10; // The x-positions of each digit: units -> tens -> hundreds private static final int[] DIGIT_X = {28, 15, 2}; // The y-position of each digit private static final int DIGIT_Y = 2; public Image backdrop; public Image[] digits; private int num; private boolean negative; public NumberDisplay() { setPreferredSize(new Dimension(BACKDROP_WIDTH, BACKDROP_HEIGHT)); } public void setImages(Image[] digits, Image backdrop) { this.digits = digits; this.backdrop = backdrop; } 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 in-place divison, because we don't want // non-graphical side effects in paintComponent int num = this.num; for (int i = 0; i < 3; i++) { int digitsIndex; // Get the index of the proper digit for this position, drawing the // minus sign in the hundreds digit if necessary if (negative && i == 2) digitsIndex = MINUS_INDEX; else digitsIndex = num % 10; g.drawImage(digits[digitsIndex], DIGIT_X[i], DIGIT_Y, this); // Next digit num /= 10; } } }