Search code examples
javaswingjcomponentinstanceof

Get Specific Type of JComponent


I am using a JComponent array variable to hold both JTextField and JComboBox components. Is there a built in way to check the type of a JComponent for use in a conditional statement? I can't seem to find a suitable method in the API.


Solution

  • It's a language feature rather than an API thing.

    If you want to check whether blah is an instance of SomeClass, you just write

    if (blah instanceof SomeClass) {
        //do stuff
    }
    

    Normally you will then want to treat it as being of that class, so you'll cast it:

    if (blah instanceof SomeClass) {
        SomeClass someBlah = (SomeClass) blah;
        //do stuff
    }
    

    You know that the cast can't fail because you checked with instanceof.

    Note that this is not checking exact types, but whether blah is compatible with SomeClass; i.e., whether it's SomeClass or a subclass of SomeClass.

    It should also be said that most people don't care much for instanceof, and see it as something that should be used sparingly. It usually turns up as a side effect of a bad design. (But not always, say I.)