Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...