Populate a JComboBox with an int[]

ε祈祈猫儿з 提交于 2020-06-23 16:33:01

问题


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[]?


回答1:


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);



回答2:


one alternative if you just want to work with integers:

JComboBox<Integer> comboBox = new JComboBox<>();

comboBox.addItem(1);
comboBox.addItem(2);

otherwise, you can also try this:

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

birthYearBox = new JComboBox(birthYear); 

and you can use Integer.praseInt("1") to get string representations of a number as a type int if you need it.

hope this helps.



来源:https://stackoverflow.com/questions/20960194/populate-a-jcombobox-with-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!