Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

java - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...