最初我有一个 JFrame
有 3 个按钮:单击时按钮 0 打印 0,按钮 1 打印 1 等等:
JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<3;i++){
final int j=i;
JButton jbutton=new JButton(""+j);
jframe.getContentPane().add(jbutton);
jbutton.setPreferredSize(new Dimension(100,100));
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(""+j);
}
});
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
由于最终变量,我想减少 1 行,因此将 for 循环重构为:
JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(final int[] arr={0};arr[0]<3;arr[0]++){
JButton jbutton=new JButton(""+arr[0]);
jframe.getContentPane().add(jbutton);
jbutton.setPreferredSize(new Dimension(100,100));
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(""+arr[0]);
}
});
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
但是这次所有按钮都打印3,即使按钮索引仍然是0,1,2,是什么原因?
最佳答案
循环结束后,i[0]
为3
。 ActionListeners
都保存对 i
的引用,并且将为 i[0]
读取相同的值,即 3
.
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println(""+arr[0]);
}
});
如果您想更正此问题,请将 i[0]
的值分配给本地最终变量,并将其用于输出,例如:
for(int[] arr = {0}; arr[0] < 3; arr[0]++) {
final int val = arr[0];
...
jbutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("" + val);
}
});
}
关于java - 为什么将 ActionListener 添加到 JButton 时,这 2 个类似的 for 循环会产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44449705/