Skip to content

Instantly share code, notes, and snippets.

@gysel
Created November 14, 2012 20:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gysel/4074617 to your computer and use it in GitHub Desktop.
Save gysel/4074617 to your computer and use it in GitHub Desktop.
JTextField only accepting numeric values
/**
* A {@link JTextField} that skips all non-digit keys. The user is only able to enter numbers.
*
* @author Michi Gysel <michi@scythe.ch>
*
*/
public class JNumberTextField extends JTextField {
private static final long serialVersionUID = 1L;
@Override
public void processKeyEvent(KeyEvent ev) {
if (Character.isDigit(ev.getKeyChar())) {
super.processKeyEvent(ev);
}
ev.consume();
return;
}
/**
* As the user is not even able to enter a dot ("."), only integers (whole numbers) may be entered.
*/
public Long getNumber() {
Long result = null;
String text = getText();
if (text != null && !"".equals(text)) {
result = Long.valueOf(text);
}
return result;
}
}
@busaeed
Copy link

busaeed commented Dec 5, 2019

Unfortunately this code doesn't prevent the user from entering characters through copy paste.

@0xFF1E071F
Copy link

Unfortunately this code doesn't prevent the user from entering characters through copy paste.

same here.
i need a code that a jtextfield accept numbers(or hex numbers) but doesnt accept non-numeric from copy paste

@ActuallyGSM
Copy link

char c = evt.getKeyChar();

    if (!(Character.isDigit(c) || c == KeyEvent.VK_BACK_SPACE || c == KeyEvent.VK_DELETE) || contactMobile.getText().length() == 10) {

        evt.consume();

    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment