0
JButton[] button = new JButton[noOfDays];

for(int j=0 ;j<studentNameList.size() ;j++) {
    for(int i=0 ;i<button.length ;i++) {
        button[i]=new JButton((i+1)+"");
        attendencepanels.add(button[i]);

        button[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
        ---->  button[i].setBackground(Color.red); //Local variable refenced from inner class must be final or effective final

                //JOptionPane.showMessageDialog(null, "test");
                }
            });

How i can resolve this problem in button[i] within actionPerformed method

default locale
  • 13,035
  • 13
  • 56
  • 62

2 Answers2

3

While I'm not sure about it, you may be able to obtain the JButton reference from the ActionEvent e argument. It seems that's what getSource() returns (The object on which the Event initially occurred) :

Instead of

button[i].setBackground(Color.red);

try

JButton button = (JButton) e.getSource();
button.setBackground(Color.red);
Eran
  • 387,369
  • 54
  • 702
  • 768
1

The variable i gets modified in this context, so the compiler cannot cope with it. Give it a non-changing reference instead:

    for(int j=0 ;j<studentNameList.size() ;j++) {
        for(int i=0 ;i<button.length ;i++) {
            JButton btn = new JButton((i+1)+""); // effectively final in that scope
            button[i] = btn;
            attendencepanels.add(btn);
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    btn.setBackground(Color.red); //works now
                }
            });
        }
    }
mtj
  • 3,381
  • 19
  • 30