【问题标题】:Creating multiple identical text verify listeners in eclipse-rcp/swt在 eclipse-rcp/swt 中创建多个相同的文本验证侦听器
【发布时间】:2012-12-08 00:43:06
【问题描述】:

我正在尝试验证多个文本框的输入(即它们应该是一个数字),并在here 下方找到了有用的代码 sn-p。

但是,如果我有三个文本框(textmoreTextevenMoreText),我如何对每个文本框应用具有相同功能的验证侦听器,而不必重复 (.addVerifyListener(new VerifyListener() {...) 代码三倍?

我不想实现 switch 语句或类似语句(以决定将其应用到哪个文本框),我想要更通用的东西(我也许可以让其他类在将来使用)。

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;
    }
  }
});

【问题讨论】:

    标签: java text swt eclipse-rcp validation


    【解决方案1】:

    事先定义VerifyListener,然后从VerifyEvent中获取实际的Text

    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);
    

    如果您也想在其他地方使用它,请创建一个新类:

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

    然后使用:

    MyVerifyListener listener = new MyVerifyListener();
    
    text.addVerifyListener(listener);
    anotherText.addVerifyListener(listener);
    

    【讨论】:

      猜你喜欢
      • 2014-12-02
      • 1970-01-01
      • 2013-10-21
      • 2021-07-05
      • 1970-01-01
      • 2018-01-21
      • 2016-09-16
      • 2012-03-19
      • 2018-12-03
      相关资源
      最近更新 更多