Jon*_*nny 4 java validation swt text eclipse-rcp
我正在尝试验证多个文本框的输入(即它们应该是一个数字),并在此处找到了有用的代码片段.
但是,如果我有三个文本框(text,moreText和evenMoreText),我如何应用具有相同功能的验证侦听器,而不必重复.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;
    }
  }
});
VerifyListener事先定义并Text从以下方面获取实际情况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);
如果您也想在其他地方使用它,请创建一个新类:
public class MyVerifyListener implements VerifyListener
{
    // The above code in here
}
然后使用:
MyVerifyListener listener = new MyVerifyListener();
text.addVerifyListener(listener);
anotherText.addVerifyListener(listener);
| 归档时间: | 
 | 
| 查看次数: | 945 次 | 
| 最近记录: |