Search code examples
javatextswt

How to set a Mask to a SWT Text to only allow Decimals


What I want is that the user can only input decimal numbers on a Text, I don't want it to allow text input as:

  1. HELLO
  2. ABC.34
  3. 34.HEY
  4. 32.3333.123

I have been trying using VerifyListener, but it only gives me the portion of the text that got inserted, so I end up having the text that I want to insert and the text before the insertion, tried also combining the text, but I got problems when you delete a key (backspace) and I end up having a String like 234[BACKSPACE]455.

Is there a way to set a Mask on a Text or successfully combine VerifyEvent with the current text to obtain the "new text" before setting it to the Text?


Solution

  • You will have to add a Listener on the Text using SWT.Verify. Within this Listener you can verify that the input contains only a decimal number.

    The following will only allow the insertion of decimals into the text field. It will check the value each time you change something in the text and reject it, if it's not a decimal. This will solve your problem, since the VerifyListener is executed BEFORE the new text is inserted. The new text has to pass the listener to be accepted.

    public static void main(String[] args) {
        Display display = Display.getDefault();
        final Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());
        
        final Text textField = new Text(shell, SWT.BORDER);
        
        textField.addVerifyListener(new VerifyListener() {
            
            @Override
            public void verifyText(VerifyEvent e) {
                
                Text text = (Text)e.getSource();
                
                // Get old text and create new text by using the VerifyEvent.text
                final String oldS = text.getText();
                String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);
                
                try
                {
                    Float.parseFloat(newS);
                }
                catch(NumberFormatException ex)
                {
                    // Prevent the input from happening, as it's not a float
                    e.doit = false;
                }
                
                System.out.println(newS);
            }
        });
        
        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch())
                display.sleep();
        }
    }