GWT RadioButton Change Handler

Ary*_*rya 6 java gwt listener radio-button

我有一个带有RadioButton选项和标签投票的投票小部件

  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+"");
}
Run Code Online (Sandbox Code Playgroud)

当用户选择新选项时,较旧的选择侦听器应该跳入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
Run Code Online (Sandbox Code Playgroud)

然后在初始化单选按钮时:

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));
        });
}
Run Code Online (Sandbox Code Playgroud)

然后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
}
Run Code Online (Sandbox Code Playgroud)

不是很优雅,但它应该做的工作.