简体   繁体   中英

Java - when clicking the mouse, the tick() loop causes more than one action

I am making a game in java and I have added mouse input. Here is my code.

public class MouseInput implements MouseListener, MouseMotionListener {

public static boolean leftPressed;
public static boolean rightPressed;

public MouseInput(){

}
public void tick(){
    if(leftPressed){
        System.out.println("left pressed");
    }
}

@Override
public void mousePressed(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1){
        leftPressed = true;

    }else if(e.getButton() == MouseEvent.BUTTON3){
        rightPressed = true;

    }
}

@Override
public void mouseReleased(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1)
        leftPressed = false;
    else if(e.getButton() == MouseEvent.BUTTON3)
        rightPressed = false;

}

I removed all of the excess code that isn't involved in this question such as getters, setters and abstract methods.

When I run this and I click what I see is

left pressed
left pressed
left pressed
left pressed
left pressed
left pressed

several times. This is because it is inside of the tick method, which updates 60 times per second. What can I change to the mousePressed and mouseReleased methods to only make it one

left pressed

Thanks a lot

What can I change to the mousePressed and mouseReleased methods to only make it one

fore the time being you can obviously move the sysout statement from the tick() method to mousePressed()

public void tick(){
    if(leftPressed){
    }
}

@Override
public void mousePressed(MouseEvent e) {
    if(e.getButton() == MouseEvent.BUTTON1){
        leftPressed = true;
        System.out.println("left pressed");

    }else if(e.getButton() == MouseEvent.BUTTON3){
        rightPressed = true;

    }
}

Forethemore you should not repead the code in mousePressed() and mouseReleased() choose either one that fits your need better.

To avoid empty method implementations you may inherit from MouseAdapter which has empty methods implementations for several Mouse releted listeners

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM