Reputation: 641
I am implementing a chess board and when I click a point on the board the MousePressed Event fires twice. I checked the stack and I see that AWTEVENTMulticaster is on top of the stack. I am not sure how to handle this and prevent the mousepressed event from being called more than once.
Code:
public static JPanel[][] pnlCells = new JPanel[8][8];
public boolean firstClick = false;
public boolean secondClick = false;
public void test(){
for (int i = 7; i >= 0; i--) {
for (int j = 0; j < 8; j++) {
final int tempi = i;
final int tempj = j;
pnlCells[i][j].add(getPieceObject(str[(7 - i)][j]), BorderLayout.CENTER);
pnlCells[i][j].validate();
pnlCells[i][j].addMouseListener(ml);
}
}
}
MouseListener ml = new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {
try {
if (firstClick == false || secondClick == false) {
JPanel source = (JPanel)e.getSource();
int tempi = 0;
int tempj = 0;
for (int i = 0; i < pnlCells.length; i++) {
for (int j = 0; j < pnlCells[i].length; j++) {
if (pnlCells[i][j] == source) {
tempi = i;
tempj = j;
break;
}
}
}
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);
}
}
@Override
public void mouseClicked(MouseEvent e
) {
}
@Override
public void mouseReleased(MouseEvent e
) {
}
@Override
public void mouseEntered(MouseEvent e
) {
}
@Override
public void mouseExited(MouseEvent e
) {
}
};
I have no other mousepressed anywhere else.
Upvotes: 0
Views: 60
Reputation: 641
I changed everything to use JButtons and ActionListeners, however I had same problem. But then I checked for the amount of listeners already on the jbutton array and everything worked.
if(pnlCells[i][j].getActionListeners().length < 1){
pnlCells[i][j].addActionListener(ml);
}
Upvotes: 1