繁体   English   中英

GWT RadioButton Change Handler

[英]GWT RadioButton Change Handler

我有一个带有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+"");
}

当用户选择新选项时,较旧的选择侦听器应该跳入else语句,但不会(仅+1部分工作)。 我该怎么办?

它在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
}

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

GWT问题跟踪器上,这个特定问题存在缺陷。 最后一条评论有一个建议,基本上你似乎需要在所有radiobuttons上有更改处理程序并自己跟踪分组...

干杯,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM