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

标签 java swing indexing jbutton

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

相关文章:

java - 为什么我的照片不再显示了

java - 是否可以从坐标生成对 JButton 的引用?

mysql - liquibase - 为 postgresql 外键创建索引

java - netty 非阻塞反向代理

java - 操作 String 类型的数组列表

Java GUI布局问题

Java向文本文件的特定部分添加行

java - JTable 为自定义类设置默认编辑器

java - MongoDB 不使用多键索引

matlab - 如何使用混合索引格式访问 MATLAB 中的多维数组