Search code examples
javacomponentsjdialog

How to determine component type


I am processing a number of JDialog components looking for a specific type with a specific client property. I understand how to check a clientproperty but I cannot find a method that returns the component type as a string. I want to do something like this:

Component[] fields = timeLineDialog.getContentPane().getComponents();
for (Component field : fields) {
    if (field.<getType>.equals("JComboBox") {
        .
        .
        .
}

I can get the components but I can't figure out how to determine the type. What method(s) can I use for ? TIA.


Solution

  • Use instanceof operator.

    for (Component field : fields) {
        if (field instanceof JComboBox) {
            // do something
        } else if (field instanceof JButton) {
            // do something
        } else if (field instanceof JPanel) {
            // do something
        }
    }
    

    See: http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm