英文:
My JComboBox displays blank entry when I made a range of array
问题
我正在尝试创建一个显示年份的JComboBox GUI。我期望这个组合框从1910年开始,但GUI显示一个空白的条目,只有在向下滚动时才能看到项目,尽管控制台从1910年开始。我不知道是我的组合框还是我的for循环出了问题。有没有办法解决这个问题?作为初学者
Integer[] year = new Integer[2020];
for (int i = 1910; i < year.length; i++) {
year[i] = i;
//System.out.println(year[i]);
}
yearBox = new JComboBox(year);
英文:
I'm trying to make a JComboBox GUI that displays years. I expect the combo box to start at 1910 but the GUI shows a blank entry and you could only see the items when you scroll down, although the console starts at 1910. I don't know if there's something wrong in my combo box or in my for-loop. Is there any way to fix this? Beginner here
Integer[] year = new Integer[2020];
for(int i = 1910; i < year.length; i++) {
year[i] = i;
//System.out.println(year[i]);
}
yearBox = new JComboBox(year);
答案1
得分: 2
但GUI显示一个空白项,只有在向下滚动时才能看到项目。
因为您的数组中有1909个空值,因为您只从1910开始添加值。
for(int i = 1910; i < year.length; i++) {
year[i] = i;
//System.out.println(year[i]);
}
为什么要创建一个数组?
直接将项目添加到组合框中:
yearBox = new JComboBox();
for(int i = 1910; i < year.length; i++) {
yearBox.addItem( Integer.valueOf(i) );
//System.out.println(year[i]);
}
英文:
> but the GUI shows a blank entry and you could only see the items when you scroll down
Because you have 1909 empty values in your Array, since you only add values starting at 1910.
for(int i = 1910; i < year.length; i++) {
year[i] = i;
//System.out.println(year[i]);
}
Why are you creating an Array?
Just add the Items directly to the combo box:
yearBox = new JComboBox();
for(int i = 1910; i < year.length; i++) {
yearBox.addItem( Integer.valueOf(i) );
//System.out.println(year[i]);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论