removeMouseListener不起作用:如果我点击旧的JLabel,它仍然会添加到变量分数。每次经过时间流逝时,旧对象都应该删除mouseListener
,新的对象应该是唯一的。
Timer picTimer = new Timer(1000, new ActionListener(){
int oldrr=0;
int oldrc=0 ;
final int[] score = {0};
@Override
public void actionPerformed(ActionEvent e) {
MouseAdapter act = new MouseAdapter(){
@Override public void mouseClicked(MouseEvent e){
score[0]++;
lblTimer.setText(String.valueOf(score[0]));
}
};
arrayWM[oldrr][oldrc].removeMouseListener(act);
arrayWM[oldrr][oldrc].setIcon(null);
Random random = new Random();
arrayWM[oldrr][oldrc].setIcon(null);
int rr = random.nextInt(3 - 0 + 1) + 0;
int rc = random.nextInt(3 - 0 + 1) + 0;
oldrr = rr;
oldrc = rc;
arrayWM[rr][rc].setIcon(new ImageIcon("img/one.jpg"));
arrayWM[rr][rc].addMouseListener(act );
}
});
答案 0 :(得分:2)
每次触发Timer
时,您都会创建MouseAdapter
的另一个实例,并尝试从JLabel
中删除此实例,但该标签没有向其注册该实例。然后,您将MouseListener
的另一个实例添加到标签中,复合一次注册到任何一个标签的MouseListener
个数。
相反,创建MouseAdapter
的单个实例并重复使用,可能是这样的......
Timer picTimer = new Timer(1000, new ActionListener() {
int oldrr = 0;
int oldrc = 0;
final int[] score = {0};
MouseAdapter act = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
score[0]++;
lblTimer.setText(String.valueOf(score[0]));
}
};
@Override
public void actionPerformed(ActionEvent e) {
arrayWM[oldrr][oldrc].removeMouseListener(act);
arrayWM[oldrr][oldrc].setIcon(null);
Random random = new Random();
arrayWM[oldrr][oldrc].setIcon(null);
int rr = random.nextInt(3 - 0 + 1) + 0;
int rc = random.nextInt(3 - 0 + 1) + 0;
oldrr = rr;
oldrc = rc;
arrayWM[rr][rc].setIcon(new ImageIcon("img/one.jpg"));
arrayWM[rr][rc].addMouseListener(act);
}
});