【问题标题】:Return index of a clicked JButton in Java swingJava swing中点击的JButton的返回索引
【发布时间】:2026-01-28 05:00:01
【问题描述】:

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

谢谢

【问题讨论】:

  • 为什么?无关:请学习java命名约定并遵守它们

标签: java swing indexing jbutton


【解决方案1】:

有几种方法。最简单的做法是:

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)

【讨论】:

    【解决方案2】:

    我猜ListofJButtonsjava.util.List。如果是这样,您可以使用

    JButton buttonSource = (JButton) e.getSource();
    int index = ListofJButtons.indexOf(buttonSource);
    

    【讨论】:

      【解决方案3】:

      您可以从 ActionEvent 执行 getActionCommand 或从按钮获取 getText 或 getLabel。由于按钮没有任何属性可以为它们提供索引,因此您无法获取索引。没有为它们定义索引。

      【讨论】:

        最近更新 更多