如何对e.getSource()进行类型转换以返回ArrayList的索引?

时间:2016-12-06 06:42:03

标签: java arraylist mouseevent

我正在尝试确定何时单击了一个对象(属于arrayList的一部分),然后使用我返回的索引调用了一些代码。

这是我的代码段

this.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {

            if (cursorState==1) {
                 int indx = trees.indexOf(e.getSource()); 
                 Tree tempTree = trees.get(indx); 
                 tempTree.killTree(); //Code I call for the object that was clicked on
                 System.out.println("indx"); //Troubleshoot
                 repaint();
            }


        }

我一直得到一个ArrayIndexOutofBoundsException:-1。

从我的搜索来看,它似乎根本没有获得索引。

1 个答案:

答案 0 :(得分:0)

确保在树类对象的类类型中重写了equals方法,以通过indexOf方法获取数组中任何对象的索引。

请参阅ArrayList not using the overridden equals以了解覆盖equals方法。