【问题标题】:How to get the source of the ActionEvent in an ArrayList如何在 ArrayList 中获取 ActionEvent 的来源
【发布时间】:2013-04-30 21:34:42
【问题描述】:

我正在尝试在 java 上制作幻灯片拼图。现在我有一个小问题。我想知道我单击的按钮的索引,它位于ArrayList 中。

ArrayList<JButton> 按钮,包含多个JButtons,我在每个按钮上添加了一个ActionListener,然后再放入这个ArrayList

我做错了什么?

这里有一些代码作为参考:

public void actionPerformed(ActionEvent ae)
{
    if (buttons.contains(ae.getSource()) == true)
    {
        int click = buttons.indexOf(ae.getSource()); // <--- What's wrong with this?

        System.out.println(click);  /* I checked the index I got by printing 
                                       it out as a test, and it always gives 
                                       me the Integer '0', even if I clicked 
                                       the 9th Button for example. */
    }
    else
    {
        System.out.println("No click");
    }
}

【问题讨论】:

    标签: java arraylist contains


    【解决方案1】:

    您可能想要做的是在每个按钮上设置一个客户端属性:

    JButton one = new JButton("1");
    one.putClientProperty("Which", new Integer(1));
    

    然后在动作监听用户中:

    JButton button = ae.getSource();
    int value = button.getClientProperty("Which").intValue();
    

    你必须添加一些演员表和一些错误检查,但这就是它的要点......

    【讨论】:

      猜你喜欢
      • 2016-06-11
      • 1970-01-01
      • 2013-12-17
      • 2016-08-11
      • 2021-02-06
      • 2016-05-25
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      相关资源
      最近更新 更多