【问题标题】:GWT RadioButton Change HandlerGWT 单选按钮更改处理程序
【发布时间】:2012-10-20 15:59:53
【问题描述】:

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

  1. 当用户选择一个选项时,选项票应该+1;
  2. When another choice selected, old choice votes should -1 and new choice votes should +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 部分有效)。我该怎么办?

【问题讨论】:

    标签: java gwt radio-button listener


    【解决方案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
    }
    

    不是很优雅,但它应该可以完成这项工作。

    【讨论】:

      【解决方案2】:

      GWT issue tracker 上的这个特定问题存在一个未解决的缺陷。最后一条评论有一个建议,基本上看起来你需要在所有单选按钮上都有 changehandlers 并自己跟踪分组......

      干杯,

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2010-10-31
      • 2011-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多