我正在实施一个棋盘,当我点击棋盘上的一个点时,MousePressed事件会发射两次。我检查了堆栈,我发现AWTEVENTMulticaster位于堆栈顶部。我不知道如何处理这个并防止鼠标压缩事件被多次调用。
代码:
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
) {
}
};
我在其他任何地方都没有其他鼠标。
答案 0 :(得分:1)
我改变了一切以使用JButtons和ActionListeners,但是我遇到了同样的问题。但后来我检查了jbutton数组上已有的监听器数量,一切正常。
if(pnlCells[i][j].getActionListeners().length < 1){
pnlCells[i][j].addActionListener(ml);
}