JComboBox中整数1到100的代码,而不是逐个添加它们

时间:2011-10-08 12:13:47

标签: java jcombobox

我是编程新手,并试图了解基础知识。我试图从JComboBox计算两个整数,并在单击JButton时将结果放在JTextField中。但如何通过不键入1,2,3,4,... 30,31 ......等来设置数字1到100。我刚刚获得了JButton的代码,它可以使用这段代码

// I used this to call the numbers into the JComboBox
// but it would be a nightmare if i will continue to do this until 100  

cb1.addItem(new Integer(1));
cb1.addItem(new Integer(2));
cb1.addItem(new Integer(3));
// ...

cb2.addItem(new Integer(1));
cb2.addItem(new Integer(2));
cb2.addItem(new Integer(3));
// ...

// the code for the JButton which i got from this site

int cb1Int = Integer.parseInt(cb1.getSelectedItem().toString());
int cb2Int = Integer.parseInt(cb2.getSelectedItem().toString());
txt.setText(String.valueOf(cb1Int + cb2Int));

此代码完美无缺,但我认为代码更短 拨打号码1到100是很有帮助的。

2 个答案:

答案 0 :(得分:3)

您可以使用for循环将所有数字添加到组合框中:

例如,

int numbers_to_add_max = 100;
for (int i = 1; i <= numbers_to_add_max; i++) {
    cb1.addItem(new Integer(i));
    cb2.addItem(new Integer(i));
}

答案 1 :(得分:1)

for(int i=0;i<=100;i++) 
{
cb1.addItem(new Integer(i));
cb2.addItem(new Integer(i));
}