Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@busaeed busaeed commented Dec 5, 2019

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

@0xFF1E071F

This comment has been minimized.

Copy link

@0xFF1E071F 0xFF1E071F commented Dec 10, 2019

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

This comment has been minimized.

Copy link

@ActuallyGSM ActuallyGSM commented Jan 4, 2020

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