• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

int to combobox

 
trupti
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All
I have one problem. I created one combobox and tried to add int value to it and then retrieve it. But its giving me error. So please tell me what should I do for it?
JComboBox Month = new JComboBox();
for(int i=1;i<=12;i++)
Month.addItem(i)
It gives error like "Incompatible type for method. Can't convert int to java.lang.Object."
And when I try to retrieve value from it,
I done it like this.
int mm = (int)Month.getSelectedItem();
and it give error like "Invalid cast from java.lang.Object to int."
Please tell me what to do for this?
Thank You
Trupti
 
Tanveer Rameez
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
The comboBox accepts an String
so typecast the int to a string, say by concatenation:
Month.addItem(""+i) //concatenation of an int with string
Similarly to retrieve, convert the string to an int:
int mm = Integer.parseInt(Month.getSelectedItem());
typecasting by (int) is done when you change a float/long/double to an int.
hope that helps
bye
Tanveer
 
PierreArnaud Galiana
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More generally, elements in a JComboBox are Objects. The toString() method is then applied to the objects in order to display them in the list or on the button.
So you could use any Object with an appropriate toString method for display, whereas the getSelectedItem() methods returns you the Object, not the String (much more comfortable than the awt Choice, isn't it ?).
In your case, you could use a java.lang.Integer.
Now more details on rendering: the JComboBox uses a ListCellRenderer to... render the objects in a JList. The default implementation of the ListCellRenderer, DefaultListCellRenderer simply extends JLabel, and call toString on the Object to render.

[This message has been edited by PierreArnaud Galiana (edited June 22, 2001).]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic