0

这是我的代码:

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);
}

我想把它放在一个 for 循环中以缩短代码。

if(cboRegion.getSelectedIndex()==ctr) {
    if(ctr==0) {
        cboDivision.setEnabled(false);
    }
    cboDivision.setModel(?????);
}

但是,我不知道在括号内放什么,因为 ComboBoxModel 不是 int。我想不出该放什么。

4

2 回答 2

3

这些 arrDiv1、arrDiv2 等是什么?

实际上这并不重要,问题是更一般的java并且与组合框无关。如果您将它们作为命名属性,您将无法真正轻松地添加它们。名称中的索引指出您可以将它们保存在一个集合中。例如:

而不是拥有

Something arrDiv1;
Something arrDiv2;
Something arrDiv3;

有类似的东西

List<Something> arrDivs=new ArrayList<>();
arrDivs.add(arrDiv1);
arrDivs.add(arrDiv2);
//  etc.

这样,您将在集合中保存相似的对象,而不是将它们命名为 1、2、3 等。如果您需要添加更多元素(使您的代码更通用),这将有助于长期。另一种解决方案是使用名称中的索引创建越来越多的属性。

然后你的代码可以是这样的:

if (cboRegion.getSelectedIndex() == ctr) {
      if (ctr == 0) {
         cboDivision.setEnabled(false);                                
      }

      // Maybe add a check for out of bounds?
      cboDivision.setModel(arrDivs.get(getSelectedIndex())); 
}
于 2018-05-02T07:54:19.627 回答
0

将代码放在 for 循环中对您没有任何好处,因为实际上只有一次迭代可以完成任何工作。所以我建议保留 if 语句。如果您想缩短代码,一种选择是为 arrDiv 元素创建某种映射并使用以下代码:

int index = cboRegion.getSelectedIndex();
if(index == 0) {
  cboDivision.setEnabled(false);
} else {
  cboDivision.setModel(map.get(index));
}
于 2018-05-02T07:55:57.880 回答