import java.awt.*; import java.awt.event.*; import javax.swing.*; // The face at the top of the game public class Face extends JComponent { // The width and height public static final int SIZE = 26; // The indexes of each face in the array public static final int HAPPY_INDEX = 0; public static final int SHOCKED_INDEX = 1; public static final int DEAD_INDEX = 2; public static final int COOL_INDEX = 3; public static final int PRESSED_INDEX = 4; // The main game canvas to refer back to private final Canvas GAME_CANVAS; private Image[] faces; // The current face index private int face; // The last face index, before being pressed, in order to revert on unpress private int unpressedFace; // Whether the face is being pressed right now private boolean pressed; // Whether the mouse is over the face private boolean mouseOver; public Face(Canvas gameCanvas) { GAME_CANVAS = gameCanvas; face = HAPPY_INDEX; pressed = false; mouseOver = false; setPreferredSize(new Dimension(SIZE, SIZE)); // We want to show the pressed sprite only if the mouse is down while // the mouse is over the face, reverting back when it's no longer over // the face but coming back as soon as the mouse comes back addMouseListener(new MouseAdapter() { // The only way to initiate a pressed face state is when the mouse // is over it and is pressed down @Override public void mousePressed(MouseEvent e) { pressed = true; unpressedFace = face; setFace(PRESSED_INDEX); } // If the face recieves a mouseReleased event while the mouse is // over it, that means that it was a completed click, so restart the // game on the canvas, also resetting back to the happy face that // should be shown at the start of every game @Override public void mouseReleased(MouseEvent e) { pressed = false; if (mouseOver) { setFace(HAPPY_INDEX); GAME_CANVAS.restart(); } } // If it was previously being pressed, reshow the pressed sprite as // soon as mouse enters @Override public void mouseEntered(MouseEvent e) { mouseOver = true; if (pressed) setFace(PRESSED_INDEX); } // Temporarily show the unpressed face, but keep the pressed boolean // true in case the mouse reenters @Override public void mouseExited(MouseEvent e) { mouseOver = false; if (pressed) setFace(unpressedFace); } }); } public void setImages(Image[] faces) { this.faces = faces; } public void setFace(int face) { this.face = face; repaint(); } @Override public void paintComponent(Graphics gr) { super.paintComponent(gr); Graphics2D g = (Graphics2D) gr; g.drawImage(faces[face], 0, 0, this); } }