我有以下 Java 代码: 我有一个 for 循环,并且正在创建 JButton。 我想返回单击按钮的索引。 所以我使用:
JButton jbtn = (JButton) e.getSource();
是否有返回 JButton 索引的方法?
我的代码如下:
for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {
ListofJButtons.get(button).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("I clicked on button !");
JButton buttonSource = (JButton) e.getSource();
System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
}
} );
}//for loop
是否可以获取被点击的JButton的Index?
谢谢
最佳答案
有几种方法。最简单的做法是:
for (int button = 0 ; button <= ListofJButtons.size() - 1; button++) {
final int index = button;
ListofJButtons.get(button).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Because index is final I can access it here and know the index
System.out.println("I clicked on button "+index+"!");
JButton buttonSource = (JButton) e.getSource();
System.out.println( " sourceButton " + buttonSource.getIndex()); //is there any method like that in Java?
}
} );
}//for loop
另一种最简单的方法就是执行ListofJButtons.indexOf(buttonSource)
。
关于java - Java swing 中单击的 JButton 的返回索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20936277/