removeMouseListener方法不起作用

时间:2015-10-31 01:23:16

标签: java swing

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

1 个答案:

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