I am trying to have it so once my mouse is pressed its gets fired once and only once. However, it keeps getting fired twice. I am not sure if this is because I am going through a for loop, but I want the mouse listener to catch what index of the array that I am clicking on. That is why I assign it to each index in the 2d array, I am not sure if theres a better way of doing this.
Code:
public boolean firstClick = false;
public boolean secondClick = false;
for (int i = 7; i >= 0; i--) {
for (int j = 0; j < 8; j++) {
int tempi = i;
int tempj = j;
pnlCells[i][j].add(getPieceObject(str[(7 - i)][j]), BorderLayout.CENTER);
pnlCells[i][j].validate();
pnlCells[i][j].addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
try {
if (firstClick == false || secondClick == false) {
if (firstClick == false) {
mouseX = tempj;
mouseY = 7 - tempi;
System.out.println("First You pressed" + mouseX + ", " + mouseY);
firstClick = true;
sourceColor = pnlCells[mouseX][mouseY].getForeground();
pnlCells[mouseX][mouseY].setForeground(Color.yellow);
pnlCells[mouseX][mouseY].repaint();
pnlBoard.repaint();
pnlMain.repaint();
} else if (secondClick == false) {
newMouseX = tempj;
newMouseY = 7 - tempi;
System.out.println("Second You pressed" + newMouseX + ", " + newMouseY);
secondClick = true;
}
if (firstClick == true && secondClick == true) {
firstClick = false;
secondClick = false;
pnlCells[mouseX][mouseY].setForeground(sourceColor);
pnlCells[mouseX][mouseY].repaint();
pnlBoard.repaint();
pnlMain.repaint();
PlayerMove pM = turn(); //send turn to server
objectOut.writeObject(pM); //send turn to server
System.out.println(name + ": sent move to server");
s.suspend();
}
}
} catch (IOException ex) {
Logger.getLogger(Player.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
//System.out.println(j+", "+(i)+":"+v.str[(7-i)][j]);
}
}
Once I click the mouse once it always prints First You pressed xcoord1, ycoord1 Second You pressed xcoord2, ycoord2