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.setText(txt);
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;
return;
}
}
}
});