0

I have an array of JComponent objects containing JTextField and JComboBox objects. I chose to make one array instead of two for more efficiency. But if I iterate over the objects I can't seem to cast them correctly, since my IDE doesn't recognize the .setText() method in the last line of the example code. How do I cast the items properly?

JComponent[] items = {JTextField1, JComboBox1};
for (JComponent item : items) {
    if (item instanceof JTextField) {
        item = (JTextField) item;
        item.setText(null);
    }
    else {
        item = (JComboBox) item ;
        item.setSelectedIndex(-1);
    }
}

1 Answer 1

4

Do it simpy like this

if (item instanceof JTextField) {
    ((JTextField) item).setText(null);
}
else {
    ((JComboBox) item).setSelectedIndex(-1);
}

Explanation

When you are iterating over your List, every item variable is saw as a JComponent. But what you need is to call a method for a specific subtype (e.g JTextField). So the solution is just to cast that item variable into the specific Subtype before calling your desired method.

Sign up to request clarification or add additional context in comments.

1 Comment

This would be a better answer if you explained why you did it that way, instead of just writing the code for him.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.