Note that there are some explanatory texts on larger screens.

plurals
  1. POReason why my loop to find an object in an Array only works for the first time?
    text
    copied!<p>I am creating a program that displays several bases and the amount of troops each base has. There are two types of bases, friendly and enemy bases. Each Base extends GCompound and consists of a GRect and a GLabel(to display the number of troops). Two arrays are used to keep track of the bases, one for friendly, one for enemy.</p> <p>I want the user to be able to press the mouse down on one friendly base and release on a different friendly base, causing the troop amount to be transferred from the first base to the second one. </p> <p>My problem currently is I am only able to detect the base the user presses the mouse down on, and not the base that the mouse is released on. I am using the method getElementAt from the ACM library to return the GObject that a mouse action takes place on.</p> <p>Code for the mouse press: </p> <pre><code>public void mousePressed(MouseEvent e){ int mouseX = e.getX(); int mouseY = e.getY(); for(int i = 0; i &lt; 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(); } } } </code></pre> <p>Code for the mouse release:</p> <pre><code>public void mouseReleased(MouseEvent m){ int mouseX = m.getX(); int mouseY = m.getY(); for(int i = 0; i &lt; PlayerBaseArray.length; i++){ if(getClickedObject(mouseX, mouseY) == PlayerBaseArray[i]){ // This is always false for some reason. PlayerBaseArray[i].changeTroopCount(pressedBaseTroopCount); PlayerBaseArray[pressedIndex].changeTroopCount(-pressedBaseTroopCount); } } } </code></pre> <p>Method to see what object is clicked:</p> <pre><code> private GObject getClickedObject(int x, int y){ GObject clicked = getElementAt(x, y); if(clicked == null) return null; else return clicked; } </code></pre> <p>For some reason the if statement in <code>mouseReleased()</code> is never true, even though it works properly in <code>mousePressed()</code>. Any idea on why the if statement in <code>mouseReleased()</code> does not work?</p> <p>I've tried researching the problem to no avail, and instead of wasting another night on it I thought I would ask here. Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload