Skip to content

Instantly share code, notes, and snippets.

@hadinajafi
Created July 16, 2019 11:13
Show Gist options
  • Save hadinajafi/c5411df49c5ccc9dc757128c732c4603 to your computer and use it in GitHub Desktop.
Save hadinajafi/c5411df49c5ccc9dc757128c732c4603 to your computer and use it in GitHub Desktop.
Accept only numbers for JTextfield in Swing. Pasting a string is also works for match.
//restrict the user to only input numeric format in the account field
accountID.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
char c = e.getKeyChar();
String regex = "[0-9]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(String.valueOf(c));
if(!matcher.matches()){
e.consume();
}
}
});
//add document listener to the account id to accept valid and only numeric input
accountID.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
String regex = "[0-9]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(accountID.getText());
if(!matcher.matches()){
notificationLabel.setText("Invalid ID!");
}
else{
notificationLabel.setText("");
}
}
@Override
public void removeUpdate(DocumentEvent e) {
String regex = "[0-9]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(accountID.getText());
if(!matcher.matches()){
notificationLabel.setText("Invalid ID!");
}
else{
notificationLabel.setText("");
}
}
@Override
public void changedUpdate(DocumentEvent e) {
String regex = "[0-9]*";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(accountID.getText());
if(!matcher.matches()){
notificationLabel.setText("Invalid ID!");
}
else{
notificationLabel.setText("");
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment