如何使用 gwt 跟踪按下了哪个按钮?

时间:2021-07-04 21:11:43

标签: java gwt

如何使用 gwt 跟踪按下了哪个按钮。我有一个按钮列表,单击按钮后,程序应该在屏幕上添加新的按钮计数,该计数将等于按下的按钮名称上的数字。例如,名称为 10 的按钮将生成 10 个新按钮。

我如何跟踪按下的按钮,我试图通过数组来做,但它只是丑陋、错误和可怕。也许有一个特殊的命令来监视按下的按钮。

我有代码尝试像这样找到按下的按钮:

for (Button button : buttons) {

    button.addClickHandler(event1 -> {

        int valueOfNumber = Integer.parseInt(button.getText());

        if (valueOfNumber <= 30) {

            buttons.clear();
            buttonPanel.clear();

            for (int i = 0; i < valueOfNumber; i++) {
                randomValue = (int) (Math.random() * 1000);

                Button updatedButton = new Button(randomValue + "");

                buttons.add(updatedButton);
                buttonPanel.add(updatedButton);
            }
        } else {
            Window.alert("Please select a value less than 30");
        }
    });
}

但这行不通。我该怎么做?

1 个答案:

答案 0 :(得分:0)

不确定,如果我了解您的用例和问题。但是,如果您想在按下按钮时始终执行相同的操作,为什么不创建一个 ClickHandler 实例并将此实例添加到每个按钮?

这样的事情应该可以工作:

// Create a click handler 
class MyClickHandler implements ClickHandler {
    public void onClick(ClickEvent event) {
        // do your stuff here ... 
    }
}

// create and add the handler
MyClickHandler handler = new MyClickHandler();
myButton01.addClickHandler(handler);
myButton02.addClickHandler(handler);
相关问题