[英]Populate a JComboBox with an int[]
Is it possible to populate a JComboBox with an int[]? 是否可以用int []填充JComboBox? I am writing a code that will use a JComboBox populated with years (in integers).
我正在编写一个代码,该代码将使用以年(整数)填充的JComboBox。
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. 我希望将它们转换为ComboBox中的整数,以便可以从中减去。 Do I have to populate the ComboBox with strings, then make them integers after they have been input?
我是否必须用字符串填充ComboBox,然后在输入字符串后使它们成为整数? Or is there a way to actually populate the ComboBox with the int[]?
还是有办法用int []实际填充ComboBox?
JCombobox
is generic, but Java generics don't support primitive type (and int
is a primitive type). JCombobox
是泛型的,但是Java泛型不支持原始类型(而int
是原始类型)。
So use an Integer
array instead : 因此,请改用
Integer
数组:
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);
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. 并且您可以使用
Integer.praseInt("1")
来获取数字的字符串表示形式,如果需要,可以将其作为int类型。
hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.