我正在使用一个按键处理程序来添加和删除事件处理程序,具体取决于文本框的字符串值。我不想在每个键上添加或删除事件处理程序。如何首先检查处理程序是否已经存在?

HandlerRegistration firstHandler = null;
HandlerRegistration secondHandler = null;

public void onKeyUp(KeyUpEvent event) {
    if (countSpaceChar(textBox.getText()) == 0) {
        // code to check if MyFirstHandler is already attached?
        firstHandler = textBox.addKeyUpHandler(new MyFirstHandler(this));
    } if (countSpaceChar(textBox.getText()) == 1) {
        firstHandler.removeHandler();
        // code to check if MySecondHandler is already attached?
        secondHandler = textBox.addKeyUpHandler(new MySecondHandler(this));
    }

}

最佳答案

if (firstHandler != null)将完成此工作,并且在删除处理程序时,将其注册为空:

firstHandler.removeHandler();
firstHandler = null;

10-02 05:18