Search code examples
javaswingcastingwarningstype-safety

How to check which type a JComboBox is before casting it?


I am trying to make a method to clear all of the fields in my JFrame. But I am encountering warnings from Eclipse.

private void clearAll(Container container) {

        for (Component component : container.getComponents()) {
            if (component instanceof JTextField) {
                JTextField field = (JTextField) component;

                field.setText("");
            }

            if (component instanceof JComboBox) {
                JComboBox<String> box = (JComboBox<String>) component;
                box.setSelectedIndex(-1);
            }

            if (component instanceof Checkbox) {
                Checkbox box = (Checkbox) component;

                box.setState(false);
            }

            if (component instanceof Container) {
                clearTextFields((Container) component);
            }
        }
    }

But I am getting this warning message:

Type safety: Unchecked cast from Component to JComboBox

Now all of my Comboboxes are Strings so I don't think it would ever cause an error (I am probably wrong), but I still want to learn the proper way to do this.

If I change the Combobox part of the code to:

    if (component instanceof JComboBox) {
                JComboBox box = (JComboBox) component;
                box.setSelectedIndex(-1);
            }

I get a different warning message:

JComboBox is a raw type. References to generic type JComboBox should be parameterized

I am new to swing so I don't know all of the methods/features. If my method for resetting everything can be done easier/in a better way, please inform me. I got the original method to clear all fields from another post on the site.


Solution

  • How about:

       if (component instanceof JComboBox) {
            JComboBox<?> box = (JComboBox<?>) component;
            box.setSelectedIndex(-1);
       }