How do I lock the keyboard for a user so that the user cannot enter any numeric value in a JTextField
?
Asked
Active
Viewed 379 times
0

Brian
- 17,079
- 6
- 43
- 66

user1649634
- 1
- 1
-
Do you want the user get err dialog that informs the wrong input? – Roman C Sep 05 '12 at 16:25
2 Answers
2
javax.swing.InputVerifier
works well for most simple tasks.
Here's one I knocked out the other day:
public class TexFieldValidator extends InputVerifier {
String regex;
String errorMsg;
JDialog popup;
public TexFieldValidator(String regex, String errorMsg) {
this.regex = regex;
this.errorMsg = errorMsg;
}
@Override
public boolean verify(JComponent input) {
boolean verified = false;
String text = ((JTextField) input).getText();
if (text.matches(regex)) {
input.setBackground(Color.WHITE);
if (popup != null) {
popup.dispose();
popup = null;
}
verified = true;
} else {
if (popup == null) {
popup = new JDialog((Window) input.getTopLevelAncestor());
input.setBackground(Color.PINK);
popup.setSize(0, 0);
popup.setLocationRelativeTo(input);
Point point = popup.getLocation();
Dimension dim = input.getSize();
popup.setLocation(point.x - (int) dim.getWidth() / 2, point.y + (int) dim.getHeight() / 2);
popup.getContentPane().add(new JLabel(errorMsg));
popup.setUndecorated(true);
popup.setFocusableWindowState(false);
popup.getContentPane().setBackground(Color.PINK);
popup.pack();
}
popup.setVisible(true);
}
return verified;
}
}
Stolen from here.
Example of use:
iDTextField.setInputVerifier(new TexFieldValidator("[a-zA-Z0-9]{3}", "ID must be 3 alphanumerics."));

Dave
- 4,546
- 2
- 38
- 59
1
You could use DocumentFilter for this purpose or perhaps JFormattedTextField.

Reimeus
- 158,255
- 15
- 216
- 276
-
See here: http://stackoverflow.com/questions/11571779/java-force-jtextfield-to-be-uppercase-only for an example of Document Filter – mrranstrom Sep 05 '12 at 16:22