gpt4 book ai didi

java - Java swing 中单击的 JButton 的返回索引

转载 作者:行者123 更新时间:2023-12-01 23:18:02 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com