Why can't I validate a JComponent?

大城市里の小女人 提交于 2019-12-02 01:35:38
Chris

In the docs for isValid() it says:

A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid.

This is the case until you reach a Top-Level Container (JFrame, JInternalFrame or JApplet). In the example you have in your question, your JComponent doesn't have a parent so it can never be valid.

The Javadoc for java.awt.Component.isValid() states:

A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid.

In short, you can't validate the component until it has been added to a container.

To add up to what has been said in the answers, don't forget to override getPreferedSize() method to return your component preferred size. Otherwise the layout manager won't position your JComponent hence will not be displayed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!