Thursday, March 6, 2008

Numeric Only in Eclipse RCP SWT Text Widget

If you wanted to make an Eclipse RCP SWT text field numeric only here is a simple validation you can do. More to come on this as I need better support then this for like money fields, etc.

Text startText = new Text(group, SWT.BORDER);
startText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
startText.addListener (SWT.Verify, new Listener ()
public void handleEvent (Event e)
String string = e.text;
char [] chars = new char [string.length ()];
string.getChars (0, chars.length, chars, 0);
for (int i=0; i < chars.length; i++)

if (!('0' <= chars [i] && chars [i] <= '9') && (chars[i]!='.'))
e.doit = false;


tochi said...

How about the negative symbol (-) ?; also backspace and del. there needs to be a custom widget for this as using Text widget in this way is quite crude.

Glenn Ford said...

I agree whole heartedly. SWT does a terrible job with text boxes and validation. Seems like it should just be part of the widget. I think I wrote some more code to do a lot better validation, I need to find that code and post it. I forgot.