code for integers 1 to 100 in a JComboBox, not adding them one by one
I'm new in programming and trying to understand the basics. im trying to compute two integers from a JComboBox and have the result in a JTextField when the JButton is clicked. but how do i set the numbers 1 to 100 by not typing them 1,2,3,4,..30,31..and so forth. i just got the code for JButton and it works with this code
// I used this t开发者_开发问答o 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));
This codes worked perfectly fine but I think a shorter code for calling the numbers 1 to 100 is a much help.
You can use a for loop to add all the numbers to your combo box:
for example,
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));
}
for(int i=0;i<=100;i++)
{
cb1.addItem(new Integer(i));
cb2.addItem(new Integer(i));
}
精彩评论