I want the user to be able only to write numbers and spaces.
How can I do that in SWT?
I want the user to be able only to write numbers and spaces.
How can I do that in SWT?
Use VerifyListener and reject the chars according to user input.
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class Test {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
final Text text = new Text(shell, SWT.BORDER);
text.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
// allows cut (CTRL + x)
if (e.text.isEmpty()) {
e.doit = true;
} else if (e.keyCode == SWT.ARROW_LEFT ||
e.keyCode == SWT.ARROW_RIGHT ||
e.keyCode == SWT.BS ||
e.keyCode == SWT.DEL ||
e.keyCode == SWT.CTRL ||
e.keyCode == SWT.SHIFT) {
e.doit = true;
} else {
boolean allow = false;
for (int i = 0; i < e.text.length(); i++) {
char c = e.text.charAt(i);
allow = Character.isDigit(c) || Character.isWhitespace(c);
if ( ! allow ) {
break;
}
}
e.doit = allow;
}
}
});
text.setSize(200, 20);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
}
Set a VerifyListener
on the text control that checks that inserted text contains only digits.
This works much better than solutions using key codes. Since it works on the input it doesn't block operations like paste and delete.
Example:
text.addVerifyListener(new VerifyListener() {
@Override
public void verifyText(VerifyEvent e) {
for (int i = 0; i < e.text.length(); i++) {
if (!Character.isDigit(e.text.charAt(i))) {
e.doit = false;
return;
}
}
}
});
In Swing you have a JFormattedTextField which will do exactly that. But I don't think there is anything similar in SWT. You should be able to make some changes to include a JFormattedTextField if that is really what you need. Another option would be to just validate the user's input after they type.
© 2022 - 2024 — McMap. All rights reserved.