2017-06-15 79 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