Is there any way to accept only numeric values in a JTextField
? Is there any special method for this?
A simple approach is to subclass JTextField and override createDefaultModel() by returning customised PlainDocument subclass. Example - a textfield for integers only:
public class NumberField extends JTextField {
@Override
protected Document createDefaultModel() {
return new Numberdocument();
}
class Numberdocument extends PlainDocument
{
String numbers="1234567890-";
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(!numbers.contains(str));
else super.insertString(offs, str, a);
}
}
Process input in insertString() any way.
A quick solution:
JTextField textField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
if (c >= 48 && c <= 57) { // c = '0' ... c = '9'
super.processKeyEvent(ev);
}
}
};
The problem with the above solution is that the user cannot use the Delete, Left Arrow, Right Arrow, or Backspace keys in the text field, so I suggest using this solution:
this.portTextField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
try {
// Ignore all non-printable characters. Just check the printable ones.
if (c > 31 && c < 127) {
Integer.parseInt(c + "");
}
super.processKeyEvent(ev);
}
catch (NumberFormatException nfe) {
// Do nothing. Character inputted is not a number, so ignore it.
}
}
};
Look at JFormattedTextField.
You can create a beautiful text field in java that accepts or allows only numeric values.. You can even set the precision for the float values... check the code in zybocodes
numberField = new JFormattedTextField(NumberFormat.getInstance());
Formatted text field tutorial
I think it is the best solution:
JTextField textField = new JFormattedTextField(new MaskFormatter("###")); //