我有类似下面的代码:
for(int i=0;i<10;i++){
button=new JButton(buttons[i]);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
setPage(i);
}
});
menu.add(button);
}
但是,变量 i
没有在 ActionListener 类的范围内定义。如何传递变量?
最佳答案
一种完全不同的方法是向按钮添加一个属性,然后在您的 Action 监听器中检索该属性。 例如。
button=new JButton(buttons[i]);
button.putClientProperty( "page", i );
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
setPage((Integer)((JButton)e.getSource()).getClientProperty( "page" ));
}
});
关于java - 将变量传递给 Java 中的 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037622/