PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 29, 2022

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

 April 29, 2022     casting, java, swing, type-safety, warnings     No comments   

Issue

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);
   }


Answered By - Maurice Perry
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing