This is my code:
ComboBoxModel arrDiv1 = new DefaultComboBoxModel(new String[]{"Alaminos
City", "Batac City", "Candon City", "Dagupan City",
"Ilocos Norte", "Ilocos Sur", "La Union", "Laoag City", "Pangasinan I",
"Pangasinan II", "San Carlos",
"San Fernando", "Urdaneta City", "Vigan City"});
ComboBoxModel arrDiv2 = new DefaultComboBoxModel(new String[]{"Batanes",
"Cagayan", "Cauayan City", "City of Ilagan",
"Isabela", "Nueva Vizcaya", "Quirino", "Santiago City", "Tuguegarao City"});
ComboBoxModel arrDiv3 = new DefaultComboBoxModel(new String[]{"Angeles
City", "Aurora", "Balanga City", "Bataan", "Bulacan",
"Cabanatuan City", "Gapan City", "Mabalacat City", "Malolos City",
"Meycauayan City", "Munoz Science City",
"Nueva Ecija", "Olongapo City", "Pampanga", "San Fernando City", "San Jose
City", "San Jose del Monte City",
"Tarlac", "Tarlac City", "Zambales"});
if(cboRegion.getSelectedIndex()==0) {
cboDivision.setEnabled(false);
}
else if(cboRegion.getSelectedIndex()==1) {
cboDivision.setModel(arrDiv1);
}
else if(cboRegion.getSelectedIndex()==2) {
cboDivision.setModel(arrDiv2);
}
else if(cboRegion.getSelectedIndex()==3) {
cboDivision.setModel(arrDiv3);
}
I want to put it in a for loop to shorten the code.
if(cboRegion.getSelectedIndex()==ctr) {
if(ctr==0) {
cboDivision.setEnabled(false);
}
cboDivision.setModel(?????);
}
However, I don't know what to put inside the parenthesis because ComboBoxModel is not an int. And I can't think what to put.
What are these arrDiv1, arrDiv2 etc?
It doesn't really matter actually and the question is more general java and not related to comboboxes. If you have them as named properties you cannot really add them easily. The indexes in the names point out that you might be able to hold them in a collection. For example:
Instead of having
to have something like
This way you will hold similar objects in a collection instead of naming them 1,2,3 etc. It would help in the long term if you need to add more elements (you make your code more generic). The other solution would be to make more and more properties with index in the name.
Then your code can be something like: