java 一种快速确定是否在 JPanel 中找到组件的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/859691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A Fast Way to Determine Whether A Componet is Found In JPanel
提问by Cheok Yan Cheng
May I know how can I determine whether a component is found in JPanel?
我可以知道如何确定是否在 JPanel 中找到了组件?
boolean isThisComponentFoundInJPanel(Component c)
{
Component[] components = jPanel.getComponents();
for (Component component : components) {
if (c== component) {
return true;
}
}
return false;
}
Using loop is not efficient. Is there any better way?
使用循环效率不高。有没有更好的办法?
回答by kdgregory
if (c.getParent() == jPanel)
Call recursively if you don't want immediate parent-child relationships (which is probably the case in a well-designed panel).
如果您不想要直接的父子关系(在设计良好的面板中可能就是这种情况),请递归调用。
... although in a well-designed panel, it's very questionable why you'd need to know whether a component is contained in the panel.
...虽然在一个设计良好的面板中,但为什么您需要知道面板中是否包含一个组件是非常值得怀疑的。
回答by Alex
you can use
您可以使用
jPanel.isAncestorOf(component)
for recursive search
用于递归搜索
回答by Tom Hawtin - tackline
Performance of this operation is highly unlikely to be a bottleneck.
此操作的性能极不可能成为瓶颈。
Looking through the contents of a container probably indicates bad design. Tell the GUI what to do, don't interrogate its state.
查看容器的内容可能表明设计不佳。告诉 GUI 做什么,不要询问它的状态。
Probably a better way to write the code is to use existing routines. Whilst there is some overhead, they are more likely to be already compiled (therefore possibly faster) and are less code.
编写代码的更好方法可能是使用现有例程。虽然有一些开销,但它们更有可能已经被编译(因此可能更快)并且代码更少。
boolean isComponentInPanel(Component component) {
return
java.util.Arrays.asList(panel.getComponents())
.contains(component);
}
(Or use kdgregory's answer.)
(或使用 kdgregory 的答案。)

