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

前端 未结 1 1380
挽巷
挽巷 2021-01-19 23:13

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 tex

相关标签:
1条回答
  • 2021-01-19 23:35

    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);
    
    0 讨论(0)
提交回复
热议问题