ProgrammingGeek11
ProgrammingGeek11

Reputation: 68

int variable value not accessible in ActionEvent JButton body

My code snippet is below:

static int i=0;
JButton ar[]=new JButton[5];
for( i=0;i<5;i++)
{
     ar[i]=new JButton(" Button number : "+i);
     ar[i].addActionListener((ActionEvent clicked) -> {
     System.out.println(" Clickevent detected on JButton number "+i);
});
panel.add(ar[i]);

In output of program , it is printing "Clickevent detected on JButton number 5" in every instance, I have no idea why this is happening.

Upvotes: 1

Views: 41

Answers (1)

The java programmers
The java programmers

Reputation: 63

Kindly prefer to use a copy of loop variable after before actionevent code in loop and print that and try to declare loop variable inside loop . Like this :

       JButton ar[]=new JButton[5];
for(int i=0;i<5;i++)
{
    ar[i]=new JButton(" Button number : "+i);
int ci=i;
ar[i].addActionListener((ActionEvent clicked) -> {
System.out.println(" Clickevent detected on JButton number "+ci);
});
panel.add(ar[i]);
}

It would work if you make these changes .

Upvotes: 1

Related Questions