gpt4 book ai didi

java - 检查 Java Swing 面板中的空组件

转载 作者:行者123 更新时间:2023-11-29 06:09:33 25 4
gpt4 key购买 nike

我在 JPanel 中创建动态按钮和动态按钮处理程序,因此使用“Panel.getComponentAt(x, y)”方法再次选择它们。

这个方法显然可以从一个什么都没有的区域中进行选择,并且这会像预期的那样返回一个空指针异常。

我需要一种方法来检查它是否正在选择一个实际的组件,这样它就不会抛出错误,我应该在这里使用 try 和 catch block 吗?还是有更优雅的东西?我一时兴起尝试了“isValid()”,这似乎不是我要找的。

非常感谢

最佳答案

来自 javadoc对于 Container#getComponentAt()

null if the component does not contain the position. If there is no child component at the requested point and the point is within the bounds of the container the container itself is returned; otherwise the top-most child is returned.

所以你可以做

Component c = Panel1.getComponentAt(x, y);

if ( c!= null && c != Panel1)
{
// a child component was found
...
}

关于java - 检查 Java Swing 面板中的空组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7407390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com