问题描述
|
我正在创建一个显示几个基地以及每个基地的兵力数量的程序。有两种类型的基地,友好基地和敌人基地。每个基地都扩展了GCompound,并由一个GRect和一个GLabel(用于显示部队人数)组成。使用两个阵列来跟踪基地,一个用于友军,一个用于敌人。
我希望用户能够在一个友善的基础上按下鼠标,然后在另一个友善的基础上释放鼠标,从而使部队数量从第一个基础转移到第二个基础。
目前我的问题是我只能检测用户按下鼠标的基准,而不能检测到释放鼠标的基准。我正在使用ACM库中的getElementAt方法来返回发生鼠标操作的GObject。
鼠标按下的代码:
public void mousepressed(MouseEvent e){
int mouseX = e.getX();
int mouseY = e.getY();
for(int i = 0; i < PlayerBaseArray.length; i++){
if(getClickedobject(mouseX,mouseY) == PlayerBaseArray[i]){ //Checks to see if the clicked base is in the Array of friendly bases.
pressedIndex = i;
pressedBaseTroopCount = PlayerBaseArray[pressedIndex].getTroopCount();
}
}
}
鼠标释放的代码:
public void mouseReleased(MouseEvent m){
int mouseX = m.getX();
int mouseY = m.getY();
for(int i = 0; i < PlayerBaseArray.length; i++){
if(getClickedobject(mouseX,mouseY) == PlayerBaseArray[i]){ // This is always false for some reason.
PlayerBaseArray[i].changeTroopCount(pressedBaseTroopCount);
PlayerBaseArray[pressedIndex].changeTroopCount(-pressedBaseTroopCount);
}
}
}
查看单击哪个对象的方法:
private GObject getClickedobject(int x,int y){
GObject clicked = getElementAt(x,y);
if(clicked == null) return null;
else return clicked;
}
由于某种原因,即使在mousepressed()
中正常运行,mouseReleased()
中的if语句也永远不会成立。关于为什么ѭ3中的if语句不起作用的任何想法?
我已经尝试研究这个问题,但是没有浪费我一个晚上,我想我会在这里问。谢谢!
解决方法
您不应该使用
==
运算符来比较Objects
。您应该使用.equals()
方法:
if (getClickedObject(mouseX,mouseY).equals(PlayerBaseArray[i]))
简而言之,仅当比较Java原语(例如int
,long
等)时,才可以使用==
。
对于所有\“ normal \”对象,请始终使用objecta.equals(objectb)
。
本文将更详细地讨论此问题。
注意肛门保持架:
是的,您是对的,在某些情况下,您可以在对象之间轻松使用con6ѭ,例如String contant,-128和127之间的Integers等。但是,此人需要明确的答案,不要混淆。请抵制对此发表评论的诱惑。