Search code examples
javamouseeventjtextfield

How to Send across variables when using mouse listener in java


This is my code:

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

i am unsure how to fix this issue as i am not very experienced with event driven programming


Solution

  • This is a simple workaround:

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