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

时间:2016-12-25 22:06:23

标签: java swing loops mouseevent mouselistener

我在java中制作游戏,并添加了鼠标输入。这是我的代码。

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;

}

我删除了此问题中没有涉及的所有多余代码,例如getter,setter和抽象方法。

当我运行这个并点击我看到的是

left pressed
left pressed
left pressed
left pressed
left pressed
left pressed
几次。 这是因为它位于tick方法的内部,每秒更新60次。我可以更改为mousePressed和mouseReleased方法,只能使其成为一个

left pressed

非常感谢

1 个答案:

答案 0 :(得分:2)

  

我可以将mousePressed和mouseReleased方法更改为只有一个

目前你可以明显地将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;

    }
}

您不应该重复mousePressed()mouseReleased()中的代码,选择更符合您需求的代码。

为了避免空方法实现,您可以从MouseAdapter继承,它具有几个鼠标相关侦听器的空方法实现