gpt4 book ai didi

java - removeMouseListener 方法不起作用

转载 作者:行者123 更新时间:2023-12-02 04:14:44 25 4
gpt4 key购买 nike

removeMouseListener 不起作用:如果我单击旧的 JLabel,它仍然会添加到变量分数中。每次经过一段时间后,旧对象都应该被删除,而新对象应该是唯一拥有它的对象。

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 );
}
});

最佳答案

每次触发 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);
}
});

关于java - removeMouseListener 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com