簡體   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