0

Can a Jcombobox hold an int? because i tried this and got an error.

int[] timeSched = new int[] {200,300,400,500}; JComboBox Jcombo1 = new JComboBox(timeSched);

tinker101
  • 33
  • 11
  • Use `Integer[] timeSched = new Integer[] {200,300,400,500};` instead – MadProgrammer Mar 11 '15 at 00:42
  • yea it work.. why can't i just use int? what;s the difference between that? – tinker101 Mar 11 '15 at 00:43
  • `int` is a primitive type, where as the `JComboBox`, via it's use generics, requires an `Object` type array. Take a look at [this](http://stackoverflow.com/questions/788433/can-you-pass-an-int-array-to-a-generic-method-in-java) and [this](http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types) for more details – MadProgrammer Mar 11 '15 at 00:45
  • can you show me a code in how to change the array int to time? for example 200 become 2:00, 300 to 3:00. I'm trying to do that for hours but i can't seem to get it right.. – tinker101 Mar 11 '15 at 02:06
  • I can think of a multitude of ways you can do it. You could just use `String` instead. Or you could use and `int` value which represents the number of minutes since midnight (2am been 120 minutes) and then use a custom `ListCellRenderer` to render the actual value in the combobox. Or you could use a `JSpinner` and spin the hour/minute value of a `Date` object... – MadProgrammer Mar 11 '15 at 02:14

1 Answers1

2

int[] is not the same as Object[].

Instead of int[] you can use Integer[] which is a wrapper class for the primitive int type, something like...

Integer[] timeSched = new Integer[] {200,300,400,500};

This allows the value to be passed to the JComboBox's constructor which is expecting a generic array of Objects.

Remember, generics in Java don't support primitives as there base class it defined off Object and primitives are a special (non-object) type in Java

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366