2012-10-31 70 views
6

我有一個單選按鈕的選擇和標籤票GWT單選按鈕更改處理

  1. 當用戶選擇了選擇,選擇的票應該+1民意調查工具;
  2. 當選擇另一個選項時,舊的選擇投票應爲-1,新的選擇投票應爲+1。

我用ValueChangeHandler此:

valueRadioButton.addValueChangeHandler(new ValueChangeHandler<Boolean>() { 
      @Override 
      public void onValueChange(ValueChangeEvent<Boolean> e) { 
       if(e.getValue() == true) 
       { 
        System.out.println("select"); 
        votesPlusDelta(votesLabel, +1); 
       } 
       else 
       { 
        System.out.println("deselect"); 
        votesPlusDelta(votesLabel, -1); 
       } 
      } 
     }); 

private void votesPlusDelta(Label votesLabel, int delta) 
{ 
    int votes = Integer.parseInt(votesLabel.getText()); 
    votes = votes + delta; 
    votesLabel.setText(votes+""); 
} 

當用戶選擇了新的選擇,選擇較老聽衆應在else語句跳,但它不會(只有+1部分作品)。我該怎麼辦?

回答

9

它說,在RadioButton javadoc,您將不會收到ValueChangeEvent當單選按鈕被清除。不幸的是,這意味着你將不得不自己做所有的簿記。

作爲備選創建的建議在GWT問題跟蹤自己的RadioButtonGroup類,你可以考慮做這樣的事情:

private int lastChoice = -1; 
private Map<Integer, Integer> votes = new HashMap<Integer, Integer>(); 
// Make sure to initialize the map with whatever you need 

然後,當你初始化單選按鈕:

List<RadioButton> allRadioButtons = new ArrayList<RadioButton>(); 

// Add all radio buttons to list here 

for (RadioButton radioButton : allRadioButtons) { 
    radioButton.addValueChangeHandler(new ValueChangeHandler<Boolean>() { 
      @Override 
      public void onValueChange(ValueChangeEvent<Boolean> e) { 
       updateVotes(allRadioButtons.indexOf(radioButton)); 
     }); 
} 

updateVotes方法看起來像這樣:

private void updateVotes(int choice) { 
    if (votes.containsKey(lastChoice)) { 
     votes.put(lastChoice, votes.get(lastChoice) - 1); 
    } 

    votes.put(choice, votes.get(choice) + 1); 
    lastChoice = choice; 

    // Update labels using the votes map here 
} 

不是很優雅,但它應該做的工作。

+0

謝謝,我認爲它的工作原理! ;) – united

2

GWT issue tracker這個特定問題上有一個缺陷。最後的評論有什麼建議,基本上看來你需要對所有的單選按鈕changehandlers和跟蹤分組自己...

乾杯,

+1

問題轉移到github上:https://github.com/gwtproject/gwt/issues/3467 –