6 Replies Latest reply: Aug 11, 2011 6:34 AM by sabre150 RSS

    Generics: Casting JComboBoxes in Java7

    Jörg
      Hello,

      as of Java 7 JComboBoxes need type declarations. In my real app I have an array
      of JComponents among which are also JComboBoxes. Up till now I could easily cast
      the component to the desired type. But with specifying a generic type, the
      compiler does not accept the cast any more. Is there still a way?
      import java.awt.*;
      import javax.swing.*;
      
      public class Y extends JFrame {
        public static final long serialVersionUID = 1L;
      
        public Y() {
          setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          setSize(300,300);
          final Container cp= getContentPane();
          cp.setLayout(null);
      
          JComponent comp= new JComboBox<Integer>(new Integer[]{1, 2, 3});
          comp.setBounds(30,50, 100, 25);
      //    ((JComboBox)comp).addItem(4); // Formerly.
          ((JComboBox<Integer>)comp).addItem(0); // warning: [unchecked] unchecked cast
          cp.add(comp);
          setVisible(true);
        }
      
      
        public static void main(String args[]) {
          EventQueue.invokeLater(new Runnable() {
            public void run() {
           new Y();
            }
          });
        }
      
      }