简体   繁体   English

Java-单击鼠标时,tick()循环会导致多个动作

[英]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. 我正在用Java做游戏,并且添加了鼠标输入。 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. 我删除了此问题中未涉及的所有多余代码,例如getter,setter和abstract方法。

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. 这是因为它在tick方法中,每秒更新60次。 What can I change to the mousePressed and mouseReleased methods to only make it one 我可以将mousePressed和mouseReleased方法更改为仅使它成为一种

left pressed

Thanks a lot 非常感谢

What can I change to the mousePressed and mouseReleased methods to only make it one 我可以将mousePressed和mouseReleased方法更改为仅使它成为一种

fore the time being you can obviously move the sysout statement from the tick() method to mousePressed() 暂时,您显然可以将sysout语句从tick()方法移至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. 因此,您不应该废除mousePressed()的代码,而mouseReleased()可以选择更适合您需要的代码。

To avoid empty method implementations you may inherit from MouseAdapter which has empty methods implementations for several Mouse releted listeners 为了避免使用空的方法实现,您可以继承MouseAdapter ,它为多个Mouse releted侦听器提供了空的方法实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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