[英]Populate a JComboBox with an int[]
是否可以用int []填充JComboBox? 我正在編寫一個代碼,該代碼將使用以年(整數)填充的JComboBox。
我寫的代碼是這樣的:
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
我希望將它們轉換為ComboBox中的整數,以便可以從中減去。 我是否必須用字符串填充ComboBox,然后在輸入字符串后使它們成為整數? 還是有辦法用int []實際填充ComboBox?
JCombobox
是泛型的,但是Java泛型不支持原始類型(而int
是原始類型)。
因此,請改用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);
如果您只想使用整數,則可以選擇一種方法:
JComboBox<Integer> comboBox = new JComboBox<>();
comboBox.addItem(1);
comboBox.addItem(2);
否則,您也可以嘗試以下操作:
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);
並且您可以使用Integer.praseInt("1")
來獲取數字的字符串表示形式,如果需要,可以將其作為int類型。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.