Search code examples
javaarraysswingintjcombobox

Populate a JComboBox with an int[]


Is it possible to populate a JComboBox with an int[]? I am writing a code that will use a JComboBox populated with years (in integers).

The code I have written is this:

int[] birthYear = new int[currentYear]; //currentYear is an int variable
int inc=1;
for(int i=0;i<currentYear;i++)
{
    birthYear[i]= inc;
    inc++;
}

birthYearBox = new JComboBox(birthYear); //this is the line in which the error occurs

I want these to integers in the ComboBox so that I can subtract from them. Do I have to populate the ComboBox with strings, then make them integers after they have been input? Or is there a way to actually populate the ComboBox with the int[]?


Solution

  • JCombobox is generic, but Java generics don't support primitive type (and int is a primitive type).

    So use an Integer array instead :

    Integer[] birthYear = new Integer[currentYear]; //currentYear is an int variable
    int inc=1;
    for(int i=0;i<currentYear;i++){
        birthYear[i]= inc;
        inc++;
    }
    JComboBox<Integer> birthYearBox = new JComboBox<>(birthYear);