-5

When trying to add years from a combobox this error shows:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

at LibraryFrame$addListener.actionPerformed(LibraryFrame.java:103)

The program highlights the 'Integer anInteger = (Integer) selected;' line as the problem?

class addListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
         Object selected = yearCombo.getSelectedItem(); 

        if(e.getSource() == button)
        {
            System.out.println("Add button clicked!");
            String t = title.getText();
            Integer anInteger = (Integer) selected;
            int y = anInteger;
            int q = Integer.parseInt(quantity.getText());
            library.addItem(new LibraryItem(t,y,q));
            library.printLibrary();

            System.out.println("Thank You!");
        }
    }
}

Heres the code where yearCombo is populated:

label1 = new JLabel("Year");
    yearCombo = new JComboBox();
    ArrayList<Integer> countYear = new ArrayList<Integer>();
    for(int y=1800; y<=2014; y++)
    {
        countYear.add(y);
    }
    for(int x=0; x < countYear.size(); x++)
    {
        yearCombo.addItem((countYear.get(x) + " "));            

    }               

CODE NOW THROWING A NUMBER FORMAT EXCEPTION after changing

    Integer anInteger = (Integer) selected;

to

    Integer anInteger = Integer.parseInt(selected.toString());
3
  • I'm guessing yearCombo.getSelectedItem() is a String object. To convert a String to an Integer you should follow the pattern you used for populating the value q. Integer anInteger = Integer.parseInt(selected);
    – Kyle
    Jan 29, 2014 at 23:26
  • 1
    Kyle, that looks like an answer. Why have you posted it as a comment?
    – nhgrif
    Jan 29, 2014 at 23:26
  • that means that the object selected is not a number. if you have a string like "hello", what do you expect it to be as a number?
    – Dima
    Jan 29, 2014 at 23:42

2 Answers 2

6

change

 Integer anInteger = (Integer) selected;

to

 Integer anInteger = Integer.parseInt(selected.toString());

as the error says, String and integer are completely different classes,

you can't cast String to Integer as you can't use television as a car.

edit:

NumberFormatException means that the object selected is not a number. if you have a string like "hello", what do you expect it to be as an integer?

3
1

This:

yearCombo.addItem((countYear.get(x) + " "));
//                                     ^--------------- not numeric

results in a string that cannot be converted to a number, no matter what countYear.get(x) gives you.

Do you really need to add that space there?

1
  • Thanks! The space was unnecessary and I'm not entirely sure why I added it but removing it solved my problem... such a school boy error! :( Jan 29, 2014 at 23:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.