I am creating dynamic buttons and dynamic button handlers inside of a JPanel, and thus am selecting them again using the "Panel.getComponentAt(x, y)" method.
This method can obviously select from an area that has nothing in it, and this would return a null pointer exc开发者_如何转开发eption as expected.
I need a way to check whether or not it is selecting an actual component so it does not throw the error, should I just use a try and catch block here? or is there something more elegant? I have tried "isValid()" on a whim, and this doesn't not seem to be what I'm looking for.
Many Thanks
From javadoc for 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.
so you can do
Component c = Panel1.getComponentAt(x, y);
if ( c!= null && c != Panel1)
{
// a child component was found
...
}
精彩评论