如何在java中使用鼠标侦听器时发送变量

时间:2017-02-16 13:23:06

标签: java mouseevent jtextfield

这是我的代码:

JTextField[] _CreatePlayers = new JTextField[3];
    for (int i = 1; i < _CreatePlayers.length; i++) {
        _CreatePlayers[i] = new JTextField("Player " + i+" input name here");
        _CreatePlayers[i].addMouseListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            _CreatePlayers[i].setText("");  <- error is here as i is not inside the class made by mouse click
        }
    });
        _2Player.add(_CreatePlayers[i]);
    }

我不确定如何解决这个问题,因为我对事件驱动编程不是很有经验

1 个答案:

答案 0 :(得分:0)

这是一个简单的解决方法:

    for (int i = 1; i < _CreatePlayers.length; i++) {
        final int finalI = i;
        _CreatePlayers[i] = new JTextField("Player " + i+" input name here");
        _CreatePlayers[i].addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
                _CreatePlayers[finalI].setText("");
            }
        });
    }