Durgesh Sahu
Durgesh Sahu

Reputation: 247

How to restrict user from entering some characters in swt textbox

I have a swt text box with which I have a key listener assigned. I want that the first character in the text box should not be the space for that I am using the following code -

  textCSVFileName.addKeyListener(new KeyAdapter(){
        public void keyPressed(KeyEvent e){
            if(textCSVFileName.getCharCount() == 0){

                if(e.keyCode == 32){

                }
            }
        }

now I know when the first character is entered by user is space. but if the above condition is true then how can I restrict it from entering in the textbox? Any help?

Upvotes: 3

Views: 1305

Answers (2)

Baz
Baz

Reputation: 36884

Although the question is answered with a dirty workaround*, I would suggest having a look at the SWT.Verify event, listening to that and preventing spaces at the first position:

final Text textField = new Text(shell, SWT.BORDER);

textField.addListener(SWT.Verify, new Listener() {

    @Override
    public void handleEvent(Event e) {
        // get old text and create new text by using the Event.text
        final String oldS = textField.getText();
        String newS = oldS.substring(0, e.start) + e.text + oldS.substring(e.end);

        if(newS.length() > 0 && newS.charAt(0) == ' ')
            e.doit = false;
    }
});

This will prevent a space at the beginning in any case.


*The "workaround" does not even work. Just think about what happens when you enter a space at the first position, when the text already contains some text. That will not be prevented by that approach.

Upvotes: 3

Waqas Ilyas
Waqas Ilyas

Reputation: 3241

You can also have a look at Text#addVerifyListener. It could be that a user has already typed in some value and then moves the cursor to the beginning of the text and enters a space. If what you want is to disallow a space character in the beginning of the text in all cases you may want to use this.

Upvotes: 3

Related Questions