2017-06-15 60 views
0

该代码获取选中多少个复选框(未选中)。它在超过2个框被选中时工作,但当没有选中复选框时不会输出警告。 应该有什么不同?没有选择复选框时没有输出警告。

下面是获取复选框

private int getCheckBoxes(){ 
    int count = 0; 
    for (int i = 0; i < checkBoxes.size(); i++){ 
     if (checkBoxes.get(i).isSelected()) { 
     count++; 
    } 
    } 
    return count; 
} 

private int getIndex(String cityName) { 
    return cities.indexOf(cityName);   
} 

//Here is the code that I'm putting out my warning 

private void handleCitySelection (int index) { 
    if (checkBoxes.get(index).isSelected()) 
    { 
     int nchecked = getCheckBoxes(); 
     if (nchecked <= 0) 
     { 
      outputDistance.append("Please Select 2 Cities"); 
     }    
     if(nchecked >= 3) 
     { 
      checkBoxes.get(index).setSelected(false); 
     } 
     else 
      if (nchecked == 1) { 
       city1 = index; 
      } 
     else 
      { 
       city2 = index; 
      } 
    } 
} 

还落后每个复选框是代码:

handleCitySelection(getIndex(evt.getActionCommand())); 

在此先感谢!

+0

那么,因为您的警告只显示在选中复选框时,您需要某种方式将您的警告代码绑定到原来的状态当你想检查没有选择框时发生。试试[mcve] –

回答

1

也许当你调用这条线

if (checkBoxes.get(index).isSelected()) 

你只执行,如果如果指数在复选框被选中/ else语句下面。如果没有选中,您将不会执行这些语句,因此不会打印警告

+0

对不起,我会写呢? –

+0

你可以先检查他们是否选择了1个或2个城市。如果没有,发送警告......然后一旦你知道他们已经选择了1或2,将其设置到适当的城市 – mrob