2

From JavaDoc:

public void validate()

Validates this container and all of its subcomponents. Validating a container means laying out its subcomponents.

That is what I want to do. With an as lightweight component as possible. But when I do this whith a JComponent a call to validate() doesn't make the component "valid".

    JComponent c = new JComponent() {};
    System.out.println(c.isValid()); // false
    c.validate();
    System.out.println(c.isValid()); // false

Why can't I make a JComponent valid?

Community
  • 1
  • 1
Jonas
  • 121,568
  • 97
  • 310
  • 388

3 Answers3

4

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Chris
  • 22,923
  • 4
  • 56
  • 50
  • But `JComponent` **is** a `Container` and if a parent is always needed, then infinitly many containers is needed. – Jonas Dec 02 '11 at 21:26
  • Yes it is a container, but it has to have a parent until you get to a TopLevelContainer (http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html#general). – Chris Dec 02 '11 at 21:35
  • Ok, thanks. That was bad :( You should add that to your answer. – Jonas Dec 02 '11 at 21:41
  • However, `validate()` should work, since it only layouts it's subcomponents, I guess. – Jonas Dec 02 '11 at 21:42
0

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.

lhballoti
  • 806
  • 7
  • 17
0

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.

GETah
  • 20,922
  • 7
  • 61
  • 103