Get index number of a certain container in arrayli

2019-08-27 06:17发布

问题:

I was wondering if there was a method for ArrayLists, similar to indexOf(), that could tell me what the element number of a particular container was.

Say I had an ArrayList that held Strings:

ArrayList<String> stringHolder = new ArrayList<>();

If I were looking for the element number of the String that contained "example", I would just call:

stringHolder.indexOf("example");

to find my answer.

How can you do this wth JPanels? Especially if all of the containers are virtually the same. I need to be able to remove a specific container from its parent panel by pressing a button within that container. The action listener would remove the container from the panel. But, I need to know the element number of that particular container. TIA.

回答1:

To find the "index" of a component held in a container, you need to get the component array from container by calling getComponents(), then to find your desired component, you need to iterate through the array, testing to see if you've gotten what you want.

Note that you could use the static Arrays.binarySearch(Object[] a, Object key) method to achieve this, but also note that for this to work well, your JPanel should override equals and hashCode so that this method will work, so that the key will match the JPanel of interest, without having to already have the component of interest in hand.

Note that obtaining a reference to a component this way is fairly "kludgy" meaning it risks leading to brittle programs that can form bugs more easily than you want. Better to have other cleaner ways of getting your reference, such as placing your key components in an ArrayList or Map.


Edit: for your program, you already have a reference to the clicked JPanel. Since the JCheckBox is held by that JPanel, you can get a reference to the JCheckBox via its listener's getSource() method, and then get a reference to its "parent" container, the JPanel, by calling getParent() on the JCheckBox.