I am trying to create a whack a mole game. I have used swing to create background and add mole images with event listeners which increment a score each time they are clicked, but I am having problems setting whether they should be visible or not. I thought the best way to do this would be to use a timer to set/reset a boolean (vis). Randomizing the period for which the images are visible would be ideal. I have tried using a swing timer several times but doesn't seem to be working. Where do I instantiate the timer, and to what do I attach the event listener which executes the code after the timer has counted down?
package whackmole;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class WhackAMole extends JFrame {
public WhackAMole() {
createAndShowGUI();
}
static int score = 0;
public static JLabel scoreDisplay;
boolean vis;
public static void main(String[] args) throws Exception {
// run asynchronously
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(600, 600));
Holes holes = new Holes(frame);
frame.getContentPane().add(holes);
holes.setLayout(null);
frame.pack();
frame.setVisible(true);
scoreDisplay = new JLabel("Score: " + score);
scoreDisplay.setBounds(239, 11, 84, 38);
holes.add(scoreDisplay);
Mole mole = new Mole(68, 92, true);
mole.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
score++;
scoreDisplay.setText("Score: " + score);
}
});
holes.add(mole);
Mole mole2 = new Mole(181, 320, false);
mole2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
score++;
scoreDisplay.setText("Score: " + score);
}
});
holes.add(mole2);
Mole mole3 = new Mole(414, 439, true);
mole3.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
score++;
scoreDisplay.setText("Score: " + score);
}
});
holes.add(mole3);
Mole mole4 = new Mole(297, 203, false);
mole4.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
score++;
scoreDisplay.setText("Score: " + score);
}
});
holes.add(mole4);
}
}