2012-10-31 17 views
6

Ho un widget di sondaggio con scelte RadioButton e Label votiGWT RadioButton Change Handler

  1. Quando l'utente seleziona una scelta, scelta voti dovrebbe +1;
  2. Quando viene scelta un'altra scelta, i voti della vecchia scelta dovrebbero essere -1 e i nuovi voti di scelta dovrebbero fare +1.

Ho usato ValueChangeHandler per questo:

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

Quando l'utente seleziona nuova scelta, più vecchio scelta ascoltatore dovrebbe saltare else, ma non sarà (Solo +1 opere di parte). Cosa dovrei fare?

risposta

9

Si dice nella RadioButton javadoc che non riceverai un ValueChangeEvent quando un pulsante di opzione viene cancellato. Sfortunatamente, questo significa che dovrai fare tutta la contabilità da solo.

Come alterativa alla creazione di una classe RadioButtonGroup come suggerito sulla questione inseguitore GWT, si potrebbe considerare di fare qualcosa di simile:

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

Poi, quando si inizializza i pulsanti di opzione:

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

Il metodo updateVotes ha un aspetto simile al seguente:

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 
} 

Non molto elegante, ma dovrebbe fare il lavoro.

+0

Grazie, penso che funzioni! ;) – united

2

C'è un difetto aperto su questo problema specifico sopra allo GWT issue tracker. L'ultimo commento ha un suggerimento, in pratica sembra è necessario avere changehandlers su tutti radiobutton e tenere traccia dei raggruppamenti te ...

Cheers,

+1

Il problema è stato spostato su github: https://github.com/gwtproject/gwt/issues/3467 –