Creating multiple identical text verify listeners in eclipse-rcp/swt

烂漫一生 提交于 2019-12-01 18:52:43

问题


I'm trying to validate the input of multiple text boxes (i.e. they should be a number), and found the useful code snippet below here.

However, if I have three text boxes (text, moreText and evenMoreText), how can I apply a verify listener with the same functionality to each, without having to repeat the (.addVerifyListener(new VerifyListener() {...) code three times?

I don't want to implement a switch statement or similar (to decide which text box to apply it to), I want something more generic (that I can perhaps make available for other classes to use in the future).

text.addVerifyListener(new VerifyListener() {
  @Override
  public void verifyText(VerifyEvent e) {
    final String oldS = text.getText();
    final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

    try {
      BigDecimal bd = new BigDecimal(newS);
      // value is decimal
      // Test value range
    } catch (final NumberFormatException numberFormatException) {
      // value is not decimal
      e.doit = false;
    }
  }
});

回答1:


Define the VerifyListener beforehand and get the actual Text from the VerifyEvent:

VerifyListener listener = new VerifyListener()
{
    @Override
    public void verifyText(VerifyEvent e)
    {
        // Get the source widget
        Text source = (Text) e.getSource();

        // Get the text
        final String oldS = source.getText();
        final String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

        try
        {
            BigDecimal bd = new BigDecimal(newS);
            // value is decimal
            // Test value range
        }
        catch (final NumberFormatException numberFormatException)
        {
            // value is not decimal
            e.doit = false;
        }
    }
};

// Add listener to both texts
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);

If you want to use it in other places as well, create a new class:

public class MyVerifyListener implements VerifyListener
{
    // The above code in here
}

and then use:

MyVerifyListener listener = new MyVerifyListener();

text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);


来源:https://stackoverflow.com/questions/13973133/creating-multiple-identical-text-verify-listeners-in-eclipse-rcp-swt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!