获取jpanels数组列表中某个容器的索引号 [英] Get index number of a certain container in arraylist of jpanels

查看:44
本文介绍了获取jpanels数组列表中某个容器的索引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种类似于 indexOf() 的 ArrayLists 方法可以告诉我特定容器的元素编号是多少.

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.

假设我有一个包含字符串的 ArrayList:

Say I had an ArrayList that held Strings:

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

如果我要查找包含example"的字符串的元素编号,我会调用:

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

stringHolder.indexOf("example");

找到我的答案.

你怎么能用 JPanels 做到这一点?特别是如果所有容器实际上都相同.我需要能够通过按下该容器内的按钮从其父面板中删除特定容器.动作侦听器将从面板中删除容器.但是,我需要知道该特定容器的元素编号.TIA.

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.

推荐答案

要查找容器中某个组件的索引",您需要通过调用 getComponents() 从容器中获取组件数组代码>,然后要找到您想要的组件,您需要遍历数组,测试是否得到了您想要的东西.

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.

请注意,您可以使用静态 Arrays.binarySearch(Object[] a, Object key) 方法来实现此目的,但还要注意,要使其正常工作,您的 JPanel 应覆盖 equals 和hashCode 以便此方法起作用,以便键匹配感兴趣的 JPanel,而无需手头已经拥有感兴趣的组件.

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.

请注意,以这种方式获取对组件的引用相当笨拙",这意味着它可能会导致脆弱的程序比您想要的更容易形成错误.最好有其他更简洁的方法来获取引用,例如将关键组件放在 ArrayList 或 Map 中.

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.

对于您的程序,您已经拥有对单击的 JPanel 的引用.由于 JCheckBox 由该 JPanel 持有,您可以通过其侦听器的 getSource() 方法获取对 JCheckBox 的引用,然后通过调用 getSource() 获取对其父"容器 JPanel 的引用代码>getParent() 在 JCheckBox 上.

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.

这篇关于获取jpanels数组列表中某个容器的索引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆