gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:42:09 25 4
gpt4 key购买 nike

我正在用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

非常感谢

最佳答案

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

目前,您显然可以将 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其中有几个与鼠标相关的监听器的空方法实现

关于Java - 单击鼠标时,tick() 循环会导致多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com