我正在用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和abstract方法。
当我运行此程序时,我单击所看到的是
left pressed
left pressed
left pressed
left pressed
left pressed
left pressed
几次。
这是因为它在tick方法中,每秒更新60次。我可以将mousePressed和mouseReleased方法更改为仅使其成为一种
left pressed
非常感谢
最佳答案
我可以将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继承,该具有用于多个Mouse releted侦听器的空方法实现