GWT RadioButton Change Handler
Asked Answered
S

2

6

I have a poll widget with RadioButton choices and Label votes

  1. When user selects a choice, choice votes should +1;
  2. When another choice selected, old choice votes should -1 and new choice votes should +1.

I used ValueChangeHandler for this:

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

When user selects new choice, older choice listener should jump in else statement, but it won't (Only +1 part works). What should i do?

Sixtieth answered 31/10, 2012 at 8:21 Comment(0)
S
9

It says in the RadioButton javadoc that you won't receive a ValueChangeEvent when a radio button is cleared. Unfortunately, this means you will have to do all bookkeeping yourself.

As an alterative to creating your own RadioButtonGroup class as suggested on the GWT issue tracker, you could consider doing something like this:

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

Then when you initialize the radio buttons:

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

The updateVotes method then looks something like this:

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
}

Not very elegant, but it should do the job.

Siegel answered 31/10, 2012 at 11:35 Comment(0)
B
2

There is an open defect on this specific problem over at the GWT issue tracker. The last comment has a suggestion, basically it appears you need to have changehandlers on all radiobuttons and keep track of the groupings yourself...

Cheers,

Bracey answered 31/10, 2012 at 8:45 Comment(1)
Issue was moved to github: github.com/gwtproject/gwt/issues/3467Hay

© 2022 - 2024 — McMap. All rights reserved.