I am building a game in Java and I need to add a mouselistener to an random drawn image in my game.
I made the image appear on random places every x seconds, when I click the image I would like to add 1 point to the scoreboard.
My code for the random image adding is:
Random rand = new Random();
private int x = 0;
private int y = 0;
Timer timer = new Timer(700, new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
x = rand.nextInt(400);
y = rand.nextInt(330);
repaint();
}
});
public void mousePressed (MouseEvent me) {
// Do something here
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(), null);
//g.drawImage(muisje, 10, 10, null);
g.drawImage(muisje, x, y, 100, 100, this);
}
I looked on google and found that I need to add a new class with a mouse event, but How do I add this? It's not clear enough because I'm just a beginner in Java.
You need to register a MouseListener
for your Gamevenster
class. Instead of making the class implement MouseListener
, just use a MouseAdapter
, where you only have to implement the method mouseClicked
. So in your constructor, you something like this
private JLabel scoreLabel = new JLabel("Score: " + score);
private int score = 0;
public Gamevenster() {
scoreLabel.setFont(new Font("impact", Font.PLAIN, 30));
scoreLabel.setForeground(Color.WHITE);
add(scoreLabel);
addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
Point p = e.getPoint();
int clickX = (int)p.getX();
int clickY = (int)p.getY();
if(clickX > x && clickX < x + 100 && clickY > y && clickY < y + 100) {
score++;
scoreLabel.setText("Score: " + score);
}
}
});
}