javaswingmouseeventjtextfieldmouseclick-event

How to add local variable inside mouseclick event?


Here I want to call addComponents(i), but it says i is undefined inside the mouseClicked event function.

Exact error:

local variables referenced from an inner class must be final or effectively final

Here is my code:

int i =0;
for (dvc:devicelist) {
    fields[i] = new JTextField("");
    fields[i].setEditable(false);
    fields[i].addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            addComponents(i);
        }
    });i++;
}

Solution

  • Assign value of i to a local final variable like

    for (int i = 0; i < 10; i++) {
        fields[i] = new JTextField("");
        fields[i].setEditable(false);
    final int j=i;
        fields[i].addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                addComponents(j);
            }
        });
    }