Created
November 14, 2012 20:37
-
-
Save gysel/4074617 to your computer and use it in GitHub Desktop.
JTextField only accepting numeric values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
char c = evt.getKeyChar();