for a little test application I need a TextField which only accepts numbers. In addition the user should only be able to enter numbers from 0-255. So far i found this:
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;
/**
* A JTextField that accepts only integers.
*
* @author David Buzatto
*/
public class IntegerField extends JTextField {
public IntegerField() {
super();
}
public IntegerField( int cols ) {
super( cols );
}
@Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
static class UpperCaseDocument extends PlainDocument {
@Override
public void insertString( int offs, String str, AttributeSet a )
throws BadLocationException {
if ( str == null ) {
return;
}
char[] chars = str.toCharArray();
boolean ok = true;
for ( int i = 0; i < chars.length; i++ ) {
try {
Integer.parseInt( String.valueOf( chars[i] ) );
} catch ( NumberFormatException exc ) {
ok = false;
break;
}
}
if ( ok ) {
super.insertString( offs, new String( chars ), a );
}
}
}
I added to the for Loop the following so only Numbers which contain of 3 Digits can be typed
if(super.getLength() == 3) {
ok = false;
System.out.println("tooLong");
break;
}
But how can I set a maximum input value? The user should only enter numbers which goes from 0-255.
Thanks in advance