Search code examples
javagraphics2dmouselistener

MouseListener prints message multiple times


So I am trying to create a Video Game using Java Graphics, and I need to use MouseListener for the "Play" button on the menu screen. When I press the button it repeats printing the test text for as long as I hold down on the button. I think it would be as easy as writing code that only allows it to be printed once but I do not know how to do this.

I've tried adding a return method but I've had no luck. I've also tried moving the MouseListener statement to mouseClicked, mouseEntered, mouseExited, and mouseReleased but have had no luck I did have a similar problem in the past, except replacing print statements with opening other windows.

here is the MouseListener statement

public void mousePressed(MouseEvent e) {
    if ((e.getButton() == 1)
            && (e.getX() >= Playx1 && e.getX() <= Playx1 + Playw1 && e.getY() >= Playy1 && e
            .getY() <= Playy1 + Playh1)) {
        System.out.println("Test Text, Replace line with method later");
    }
}

and the animation loop MIGHT be important, I don't know

private Thread animationThread = new Thread(new Runnable() {
    public void run() {
        while (true) {
            repaint();
            try {Thread.sleep(10);} catch (Exception ex) {}

        }
    }
});

I expect when I press the button to display "Test Text, Replace line with method later" just once, but instead, it keeps showing it as long as I press the button.


Solution

  • I would solve it as below:

    AtomicBoolean buttonIsPressed = new AtomicBoolean( false );
    
    public void mousePressed( MouseEvent e ) 
    {
        if( ((e.getButton() == 1)
            && (e.getX() >= Playx1 && e.getX() <= Playx1 + Playw1 && e.getY() >= Playy1 && 
            e.getY() <= Playy1 + Playh1))
            && !buttonIsPressed.compareAndExchange( false, true ) ) 
        {
            System.out.println("Test Text, Replace line with method later");
        }
    }
    
    public void mouseReleased( MouseEvent e ) 
    {
        if( e.getButton() == 1 ) 
        {
            buttonIsPressed.compareAndExchange( true, false );
        }
    }
    

    I assume this is what @inquizitive meant with their comment.